@temboplus/tembo-dashboard 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("uuid"),t=require("zod"),r=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var s,a,o=n(t);!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(s||(s={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(a={}));const i=s.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":return Array.isArray(e)?i.array:null===e?i.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?i.promise:"undefined"!=typeof Map&&e instanceof Map?i.map:"undefined"!=typeof Set&&e instanceof Set?i.set:"undefined"!=typeof Date&&e instanceof Date?i.date:i.object;default:return i.unknown}},u=s.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"]);class d extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,s.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}d.create=e=>new d(e);const l=(e,t)=>{let r;switch(e.code){case u.invalid_type:r=e.received===i.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case u.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,s.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:r=`Unrecognized key(s) in object: ${s.joinValues(e.keys,", ")}`;break;case u.invalid_union:r="Invalid input";break;case u.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${s.joinValues(e.options)}`;break;case u.invalid_enum_value:r=`Invalid enum value. Expected ${s.joinValues(e.options)}, received '${e.received}'`;break;case u.invalid_arguments:r="Invalid function arguments";break;case u.invalid_return_type:r="Invalid function return type";break;case u.invalid_date:r="Invalid date";break;case u.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:s.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case u.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case u.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case u.custom:r="Invalid input";break;case u.invalid_intersection_types:r="Intersection results could not be merged";break;case u.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case u.not_finite:r="Number must be finite";break;default:r=t.defaultError,s.assertNever(e)}return{message:r}};let h=l;function m(){return h}const p=e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,a=[...r,...s.path||[]],o={...s,path:a};let i="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)i=e(o,{data:t,defaultError:i}).message;return{...s,path:a,message:s.message||i}};function f(e,t){const r=p({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m(),l].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return g;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t)r.push({key:await e.key,value:await e.value});return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return g;if("aborted"===s.status)return g;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const g=Object.freeze({status:"aborted"}),T=e=>({status:"dirty",value:e}),A=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,E=e=>"dirty"===e.status,_=e=>"valid"===e.status,N=e=>"undefined"!=typeof Promise&&e instanceof Promise;var S;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(S||(S={}));class I{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const C=(e,t)=>{if(_(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new d(e.common.issues);return this._error=t,this._error}}};function O(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=n?n:t.defaultError}:{message:null!=r?r:t.defaultError},description:s}}class b{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)}get description(){return this._def.description}_getType(e){return c(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(N(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},s=this._parseSync({data:e,path:n.path,parent:n});return C(n,s)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(N(n)?n:Promise.resolve(n));return C(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const s=e(t),a=()=>n.addIssue({code:u.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(a(),!1)):!!s||(a(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new ge({schema:this,typeName:we.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Te.create(this,this._def)}nullable(){return Ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this,this._def)}promise(){return ye.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return ae.create(this,e,this._def)}transform(e){return new ge({...O(this._def),schema:this,typeName:we.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ve({...O(this._def),innerType:this,defaultValue:t,typeName:we.ZodDefault})}brand(){return new Se({typeName:we.ZodBranded,type:this,...O(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ee({...O(this._def),innerType:this,catchValue:t,typeName:we.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ie.create(this,e)}readonly(){return Ce.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const w=/^c[^\s-]{8,}$/i,x=/^[a-z][a-z0-9]*$/,R=/[0-9A-HJKMNP-TV-Z]{26}/,L=/^[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,P=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,D=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,U=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,k=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,F=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):0===e.precision?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function z(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!k.test(e))}class M extends b{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:u.invalid_string,...S.errToObj(r)}),this.nonempty=e=>this.min(1,S.errToObj(e)),this.trim=()=>new M({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new M({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new M({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==i.string){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.string,received:t.parsedType}),g}const t=new y;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const s=e.data.length>n.value,a=e.data.length<n.value;(s||a)&&(r=this._getOrReturnCtx(e,r),s?f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):a&&f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:u.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)D.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:u.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)L.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)w.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:u.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)R.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:u.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(s){r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:u.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:u.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){F(n).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else"ip"===n.kind?z(e.data,n.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:u.invalid_string,message:n.message}),t.dirty()):s.assertNever(n);return{status:t.value,value:e.data}}_addCheck(e){return new M({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...S.errToObj(e)})}url(e){return this._addCheck({kind:"url",...S.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...S.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...S.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...S.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...S.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...S.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...S.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,...S.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...S.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...S.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...S.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...S.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...S.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...S.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...S.errToObj(t)})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function j(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}M.create=e=>{var t;return new M({checks:[],typeName:we.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...O(e)})};class B extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==i.number){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.number,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("int"===n.kind)s.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==j(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_finite,message:n.message}),r.dirty()):s.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,r,n){return new B({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:S.toString(n)}]})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:S.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:S.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:S.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:S.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&s.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}B.create=e=>new B({checks:[],typeName:we.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class Z extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==i.bigint){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.bigint,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):s.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,r,n){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:S.toString(n)}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Z.create=e=>{var t;return new Z({checks:[],typeName:we.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...O(e)})};class V extends b{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==i.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.boolean,received:t.parsedType}),g}return A(e.data)}}V.create=e=>new V({typeName:we.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...O(e)});class $ extends b{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==i.date){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.date,received:t.parsedType}),g}if(isNaN(e.data.getTime())){return f(this._getOrReturnCtx(e),{code:u.invalid_date}),g}const t=new y;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):s.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:S.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:S.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}$.create=e=>new $({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:we.ZodDate,...O(e)});class J extends b{_parse(e){if(this._getType(e)!==i.symbol){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.symbol,received:t.parsedType}),g}return A(e.data)}}J.create=e=>new J({typeName:we.ZodSymbol,...O(e)});class Y extends b{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.undefined,received:t.parsedType}),g}return A(e.data)}}Y.create=e=>new Y({typeName:we.ZodUndefined,...O(e)});class q extends b{_parse(e){if(this._getType(e)!==i.null){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.null,received:t.parsedType}),g}return A(e.data)}}q.create=e=>new q({typeName:we.ZodNull,...O(e)});class W extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return A(e.data)}}W.create=e=>new W({typeName:we.ZodAny,...O(e)});class G extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return A(e.data)}}G.create=e=>new G({typeName:we.ZodUnknown,...O(e)});class H extends b{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.never,received:t.parsedType}),g}}H.create=e=>new H({typeName:we.ZodNever,...O(e)});class K extends b{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.void,received:t.parsedType}),g}return A(e.data)}}K.create=e=>new K({typeName:we.ZodVoid,...O(e)});class Q extends b{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==i.array)return f(t,{code:u.invalid_type,expected:i.array,received:t.parsedType}),g;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(f(t,{code:e?u.too_big:u.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(f(t,{code:u.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(f(t,{code:u.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new I(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new I(t,e,t.path,r)));return y.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:S.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:S.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:S.toString(t)}})}nonempty(e){return this.min(1,e)}}function X(e){if(e instanceof ee){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Te.create(X(n))}return new ee({...e._def,shape:()=>t})}return e instanceof Q?new Q({...e._def,type:X(e.element)}):e instanceof Te?Te.create(X(e.unwrap())):e instanceof Ae?Ae.create(X(e.unwrap())):e instanceof oe?oe.create(e.items.map(e=>X(e))):e}Q.create=(e,t)=>new Q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:we.ZodArray,...O(t)});class ee extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=s.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==i.object){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.object,received:t.parsedType}),g}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof H&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||a.push(e);const o=[];for(const e of s){const t=n[e],s=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new I(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof H){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(f(r,{code:u.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new I(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return S.errToObj,new ee({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,a,o;const i=null!==(a=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(o=S.errToObj(e).message)&&void 0!==o?o:i}:{message:i}}}:{}})}strip(){return new ee({...this._def,unknownKeys:"strip"})}passthrough(){return new ee({...this._def,unknownKeys:"passthrough"})}extend(e){return new ee({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ee({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:we.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ee({...this._def,catchall:e})}pick(e){const t={};return s.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}omit(e){const t={};return s.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}deepPartial(){return X(this)}partial(e){const t={};return s.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new ee({...this._def,shape:()=>t})}required(e){const t={};return s.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Te;)e=e._def.innerType;t[r]=e}}),new ee({...this._def,shape:()=>t})}keyof(){return me(s.objectKeys(this.shape))}}ee.create=(e,t)=>new ee({shape:()=>e,unknownKeys:"strip",catchall:H.create(),typeName:we.ZodObject,...O(t)}),ee.strictCreate=(e,t)=>new ee({shape:()=>e,unknownKeys:"strict",catchall:H.create(),typeName:we.ZodObject,...O(t)}),ee.lazycreate=(e,t)=>new ee({shape:e,unknownKeys:"strip",catchall:H.create(),typeName:we.ZodObject,...O(t)});class te extends b{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new d(e.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:r}),g});{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map(e=>new d(e));return f(t,{code:u.invalid_union,unionErrors:s}),g}}get options(){return this._def.options}}te.create=(e,t)=>new te({options:e,typeName:we.ZodUnion,...O(t)});const re=e=>e instanceof le?re(e.schema):e instanceof ge?re(e.innerType()):e instanceof he?[e.value]:e instanceof pe?e.options:e instanceof fe?Object.keys(e.enum):e instanceof ve?re(e._def.innerType):e instanceof Y?[void 0]:e instanceof q?[null]:null;class ne extends b{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return f(t,{code:u.invalid_type,expected:i.object,received:t.parsedType}),g;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=re(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new ne({typeName:we.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...O(r)})}}function se(e,t){const r=c(e),n=c(t);if(e===t)return{valid:!0,data:e};if(r===i.object&&n===i.object){const r=s.objectKeys(t),n=s.objectKeys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=se(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===i.array&&n===i.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const s=se(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===i.date&&n===i.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ae extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return g;const s=se(e.value,n.value);return s.valid?((E(e)||E(n))&&t.dirty(),{status:t.value,value:s.data}):(f(r,{code:u.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ae.create=(e,t,r)=>new ae({left:e,right:t,typeName:we.ZodIntersection,...O(r)});class oe extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return f(r,{code:u.invalid_type,expected:i.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new I(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>y.mergeArray(t,e)):y.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new oe({...this._def,rest:e})}}oe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:e,typeName:we.ZodTuple,rest:null,...O(t)})};class ie extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.object)return f(r,{code:u.invalid_type,expected:i.object,received:r.parsedType}),g;const n=[],s=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new I(r,e,r.path,e)),value:a._parse(new I(r,r.data[e],r.path,e))});return r.common.async?y.mergeObjectAsync(t,n):y.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ie(t instanceof b?{keyType:e,valueType:t,typeName:we.ZodRecord,...O(r)}:{keyType:M.create(),valueType:e,typeName:we.ZodRecord,...O(t)})}}class ce extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.map)return f(r,{code:u.invalid_type,expected:i.map,received:r.parsedType}),g;const n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([e,t],a)=>({key:n._parse(new I(r,e,r.path,[a,"key"])),value:s._parse(new I(r,t,r.path,[a,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return g;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return g;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}ce.create=(e,t,r)=>new ce({valueType:t,keyType:e,typeName:we.ZodMap,...O(r)});class ue extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return f(r,{code:u.invalid_type,expected:i.set,received:r.parsedType}),g;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(f(r,{code:u.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(f(r,{code:u.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return g;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>s._parse(new I(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(e,t){return new ue({...this._def,minSize:{value:e,message:S.toString(t)}})}max(e,t){return new ue({...this._def,maxSize:{value:e,message:S.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ue.create=(e,t)=>new ue({valueType:e,minSize:null,maxSize:null,typeName:we.ZodSet,...O(t)});class de extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.function)return f(t,{code:u.invalid_type,expected:i.function,received:t.parsedType}),g;function r(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_arguments,argumentsError:r}})}function n(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_return_type,returnTypeError:r}})}const s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ye){const e=this;return A(async function(...t){const o=new d([]),i=await e._def.args.parseAsync(t,s).catch(e=>{throw o.addIssue(r(t,e)),o}),c=await Reflect.apply(a,this,i);return await e._def.returns._def.type.parseAsync(c,s).catch(e=>{throw o.addIssue(n(c,e)),o})})}{const e=this;return A(function(...t){const o=e._def.args.safeParse(t,s);if(!o.success)throw new d([r(t,o.error)]);const i=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(i,s);if(!c.success)throw new d([n(i,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new de({...this._def,args:oe.create(e).rest(G.create())})}returns(e){return new de({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new de({args:e||oe.create([]).rest(G.create()),returns:t||G.create(),typeName:we.ZodFunction,...O(r)})}}class le extends b{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}le.create=(e,t)=>new le({getter:e,typeName:we.ZodLazy,...O(t)});class he extends b{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}function me(e,t){return new pe({values:e,typeName:we.ZodEnum,...O(t)})}he.create=(e,t)=>new he({value:e,typeName:we.ZodLiteral,...O(t)});class pe extends b{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:s.joinValues(r),received:t.parsedType,code:u.invalid_type}),g}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:r}),g}return A(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e){return pe.create(e)}exclude(e){return pe.create(this.options.filter(t=>!e.includes(t)))}}pe.create=me;class fe extends b{_parse(e){const t=s.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==i.string&&r.parsedType!==i.number){const e=s.objectValues(t);return f(r,{expected:s.joinValues(e),received:r.parsedType,code:u.invalid_type}),g}if(-1===t.indexOf(e.data)){const e=s.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:e}),g}return A(e.data)}get enum(){return this._def.values}}fe.create=(e,t)=>new fe({values:e,typeName:we.ZodNativeEnum,...O(t)});class ye extends b{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.promise&&!1===t.common.async)return f(t,{code:u.invalid_type,expected:i.promise,received:t.parsedType}),g;const r=t.parsedType===i.promise?t.data:Promise.resolve(t.data);return A(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ye.create=(e,t)=>new ye({type:e,typeName:we.ZodPromise,...O(t)});class ge extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===we.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:e=>{f(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){const e=n.transform(r.data,a);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(e).then(e=>this._def.schema._parseAsync({data:e,path:r.path,parent:r})):this._def.schema._parseSync({data:e,path:r.path,parent:r})}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?g:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?g:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_(e))return e;const s=n.transform(e.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>_(e)?Promise.resolve(n.transform(e.value,a)).then(e=>({status:t.value,value:e})):e)}s.assertNever(n)}}ge.create=(e,t,r)=>new ge({schema:e,typeName:we.ZodEffects,effect:t,...O(r)}),ge.createWithPreprocess=(e,t,r)=>new ge({schema:t,effect:{type:"preprocess",transform:e},typeName:we.ZodEffects,...O(r)});class Te extends b{_parse(e){return this._getType(e)===i.undefined?A(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:we.ZodOptional,...O(t)});class Ae extends b{_parse(e){return this._getType(e)===i.null?A(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:we.ZodNullable,...O(t)});class ve extends b{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ve.create=(e,t)=>new ve({innerType:e,typeName:we.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...O(t)});class Ee extends b{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return N(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:we.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...O(t)});class _e extends b{_parse(e){if(this._getType(e)!==i.nan){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.nan,received:t.parsedType}),g}return{status:"valid",value:e.data}}}_e.create=e=>new _e({typeName:we.ZodNaN,...O(e)});const Ne=Symbol("zod_brand");class Se extends b{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ie extends b{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),T(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Ie({in:e,out:t,typeName:we.ZodPipeline})}}class Ce extends b{_parse(e){const t=this._def.innerType._parse(e);return _(t)&&(t.value=Object.freeze(t.value)),t}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:we.ZodReadonly,...O(t)});const Oe=(e,t={},r)=>e?W.create().superRefine((n,s)=>{var a,o;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,i=null===(o=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===o||o,c="string"==typeof e?{message:e}:e;s.addIssue({code:"custom",...c,fatal:i})}}):W.create(),be={object:ee.lazycreate};var we;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(we||(we={}));const xe=M.create,Re=B.create,Le=_e.create,Pe=Z.create,De=V.create,Ue=$.create,ke=J.create,Fe=Y.create,ze=q.create,Me=W.create,je=G.create,Be=H.create,Ze=K.create,Ve=Q.create,$e=ee.create,Je=ee.strictCreate,Ye=te.create,qe=ne.create,We=ae.create,Ge=oe.create,He=ie.create,Ke=ce.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=pe.create,nt=fe.create,st=ye.create,at=ge.create,ot=Te.create,it=Ae.create,ct=ge.createWithPreprocess,ut=Ie.create,dt={string:e=>M.create({...e,coerce:!0}),number:e=>B.create({...e,coerce:!0}),boolean:e=>V.create({...e,coerce:!0}),bigint:e=>Z.create({...e,coerce:!0}),date:e=>$.create({...e,coerce:!0})},lt=g;var ht=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){h=e},getErrorMap:m,makeIssue:p,EMPTY_PATH:[],addIssueToContext:f,ParseStatus:y,INVALID:g,DIRTY:T,OK:A,isAborted:v,isDirty:E,isValid:_,isAsync:N,get util(){return s},get objectUtil(){return a},ZodParsedType:i,getParsedType:c,ZodType:b,ZodString:M,ZodNumber:B,ZodBigInt:Z,ZodBoolean:V,ZodDate:$,ZodSymbol:J,ZodUndefined:Y,ZodNull:q,ZodAny:W,ZodUnknown:G,ZodNever:H,ZodVoid:K,ZodArray:Q,ZodObject:ee,ZodUnion:te,ZodDiscriminatedUnion:ne,ZodIntersection:ae,ZodTuple:oe,ZodRecord:ie,ZodMap:ce,ZodSet:ue,ZodFunction:de,ZodLazy:le,ZodLiteral:he,ZodEnum:pe,ZodNativeEnum:fe,ZodPromise:ye,ZodEffects:ge,ZodTransformer:ge,ZodOptional:Te,ZodNullable:Ae,ZodDefault:ve,ZodCatch:Ee,ZodNaN:_e,BRAND:Ne,ZodBranded:Se,ZodPipeline:Ie,ZodReadonly:Ce,custom:Oe,Schema:b,ZodSchema:b,late:be,get ZodFirstPartyTypeKind(){return we},coerce:dt,any:Me,array:Ve,bigint:Pe,boolean:De,date:Ue,discriminatedUnion:qe,effect:at,enum:rt,function:Xe,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Oe(t=>t instanceof e,t),intersection:We,lazy:et,literal:tt,map:Ke,nan:Le,nativeEnum:nt,never:Be,null:ze,nullable:it,number:Re,object:$e,oboolean:()=>De().optional(),onumber:()=>Re().optional(),optional:ot,ostring:()=>xe().optional(),pipeline:ut,preprocess:ct,promise:st,record:He,set:Qe,strictObject:Je,string:xe,symbol:ke,transformer:at,tuple:Ge,undefined:Fe,union:Ye,unknown:je,void:Ze,NEVER:lt,ZodIssueCode:u,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:d});const mt=e=>"function"==typeof(null==e?void 0:e.passthrough),pt=ht.object({name:ht.literal("ZodError"),issues:ht.array(ht.object({path:ht.array(ht.union([ht.string(),ht.number()])),message:ht.string().optional(),code:ht.nativeEnum(ht.ZodIssueCode)}).catchall(ht.any()))});class ft extends Error{constructor(e){super(JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t,2)),this.name="ValidationError",this.issues=e}toString(){return this.message}}ht.object({message:ht.literal("Request validation failed"),pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({paramsResult:pt.nullable(),headersResult:pt.nullable(),queryResult:pt.nullable(),bodyResult:pt.nullable()});const yt="zod-ts-rest-polyfill",gt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof ee&&t instanceof ee){return n=t,mt(r=e)?mt(n)?r.merge(n):r:mt(n)?n:Object.assign({},r,n)}var r,n;return{...e,...t}},Tt=Symbol("ContractNoBody"),At=e=>"method"in e&&"path"in e,vt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,s,a;return At(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:gt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(s=r.validateResponseOnClient)&&void 0!==s?s:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,vt(r,t)]})),Et=Symbol("ContractPlainType"),_t=()=>({router:(e,t)=>vt(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Et,body:()=>Et,type:()=>Et,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>Tt}),Nt=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",St=e=>e?Object.keys(e).flatMap(t=>It(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",It=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>It(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>It(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Ct extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const Ot=async({route:e,path:t,method:r,headers:n,body:s,validateResponse:a,fetchOptions:o})=>{const i=await fetch(t,{...o,method:r,headers:n,body:s}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t=e.responses[i.status],r={status:i.status,body:t===Tt?void 0:await i.json(),headers:i.headers},n=(e=>{if((e=>{if(!e)return!1;const t=null==e?void 0:e["~standard"];return!!t&&1===t.version&&"function"==typeof t.validate})(e))return e;if("function"==typeof(null==(t=e)?void 0:t.safeParse)){const t={vendor:yt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(n&&(null!=a?a:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const n=t["~standard"].validate(e);if(n instanceof Promise)throw new Error("Schema validation must be synchronous");return n.issues?t["~standard"].vendor===yt?{error:new d(n.issues)}:{error:new ft(n.issues)}:r&&"object"==typeof e&&n.value?{value:{...e,...n.value}}:{value:n.value}})(r.body,n);if(e.error)throw e.error;return{...r,body:e.value}}return r}return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},bt=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},wt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),xt=(e,t,r,n,s)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),o=((e,t=!1)=>{const r=t?Nt(e):St(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,s);return t.endsWith("/")&&a.startsWith("/")?`${t}${a.substring(1)}${o}`:`${t}${a}${o}`},Rt=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const s=((e,t,r)=>{const{query:n,params:s,body:a,headers:o,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof s?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,String(t)])):{};return{path:xt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:a,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...o}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:s,query:a,extraInputArgs:o,headers:i,fetchOptions:c}=e,u=r.api||Ot,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&wt(d),...wt(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let h={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:s,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:s instanceof FormData?s:bt(s)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof s?s:new URLSearchParams(s)}:null!=s&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(s)})),u({...h,...o})})(s);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new Ct(a,r)}},Lt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>At(r)?[e,Rt(r,t)]:[e,Lt(r,t)]));class Pt extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,e.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return Pt.schema.safeParse(e).success}static unknown(e){return new Pt({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.z.object({message:t.z.string(),statusCode:t.z.number().int(),error:t.z.string().optional(),details:t.z.object({}).optional()})}}const Dt=o.default.object({statusCode:o.default.number().int(),reason:o.default.string().optional(),error:o.default.string().optional(),details:o.default.record(o.default.string(),o.default.unknown()).optional(),message:o.default.string().optional()}),Ut=Dt.extend({statusCode:o.default.literal(400)}),kt=Dt.extend({statusCode:o.default.literal(401)}),Ft=Dt.extend({statusCode:o.default.literal(403)}),zt=Dt.extend({statusCode:o.default.literal(404)}),Mt=Dt.extend({statusCode:o.default.literal(500)}),jt=o.default.object({page:o.default.number().int().positive(),limit:o.default.number().int().positive(),total:o.default.number().int().min(0),totalPages:o.default.number().int().min(0),hasNext:o.default.boolean(),hasPrev:o.default.boolean()}),Bt=o.default.object({balance:o.default.number(),availableBalance:o.default.number(),accountNumber:o.default.string(),accountName:o.default.string()}),Zt=o.default.object({yesterday:o.default.number(),today:o.default.number(),thisMonth:o.default.number(),lastMonth:o.default.number()});const Vt=o.default.string().nullish().transform(e=>{if(!e||""===e.trim())return null;try{return function(e){if(!e||""===e.trim())throw new Error("Date string cannot be empty");const[t,r]=e.trim().split(" ");if(!t||!r)throw new Error("Invalid date format. Expected 'YYYY-MM-DD HH:mm:ss'");const n=new Date(`${t}T${r}.000Z`);return new Date(n.getTime()-108e5).toISOString()}(e)}catch(e){throw new Error(`Failed to convert EAT date to UTC: ${e instanceof Error?e.message:"Unknown error"}`)}}),$t=o.default.object({accountNo:o.default.string().nullish(),debitOrCredit:o.default.enum(["CR","DR"],{error:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:o.default.string().nullish(),cbaRefNo:o.default.string().nullish(),narration:o.default.string().nullish(),txnDate:Vt,valueDate:Vt,amountCredited:o.default.union([o.default.number().min(0,"Credited amount cannot be negative"),o.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid credited amount format");return t})],{error:()=>({message:"Credited amount must be a number or numeric string"})}).nullish(),amountDebited:o.default.union([o.default.number().min(0,"Debited amount cannot be negative"),o.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid debited amount format");return t})],{error:()=>({message:"Debited amount must be a number or numeric string"})}).nullish(),balance:o.default.number({error:e=>void 0===e.input?"Balance is required":"Balance must be a number"})}),Jt={apiError:Dt,validationError:Ut,unauthorizedError:kt,forbiddenError:Ft,notFoundError:zt,serverError:Mt,pagination:jt,transactionSummary:Zt,walletSummary:Bt,statementEntry:$t};class Yt{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){return this.getClientWithHeaders()}getClientWithHeaders(t){const r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",s=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,a={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e.v4()},o={baseUrl:s,baseHeaders:t?{...a,...t}:a};return Lt(this.contract,o)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=Jt.apiError.safeParse(e.body),n=r.success?r.data:void 0,s=(t,r)=>new Pt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw s("Bad request","BAD_REQUEST");if(401===e.status)throw s("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw s("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw s("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw s("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw s("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class qt{accountNo;debitOrCredit;tranRefNo;cbaRefNo;narration;txnDate;valueDate;amountCredited;amountDebited;balance;currency;constructor(e,t="TZS"){let n="TZS";r.CurrencyHelpers.isCode(t)&&(n=t),this.accountNo=e.accountNo,this.debitOrCredit=e.debitOrCredit,this.tranRefNo=e.tranRefNo,this.cbaRefNo=e.cbaRefNo,this.narration=e.narration,this.txnDate=e.txnDate?new Date(e.txnDate):null,this.valueDate=e.valueDate?new Date(e.valueDate):null,this.currency=n;const s=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===s?null:s>0?r.Amount.from(s,n)??r.Amount.from(0,n):null;const a=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===a?null:a>0?r.Amount.from(a,n)??r.Amount.from(0,n):null,this.balance=r.Amount.from(e.balance,n)??r.Amount.from(0,n)}parseAmountValue(e){if("number"==typeof e)return e;if("string"==typeof e&&""!==e.trim()){const t=parseFloat(e);return Number.isNaN(t)?0:t}return 0}isCredit(){return"CR"===this.debitOrCredit}isDebit(){return"DR"===this.debitOrCredit}getTransactionAmount(){return this.amountCredited||this.amountDebited}getTransactionValue(){const e=this.getTransactionAmount();return e?e.numericValue:0}static from(e,t="TZS"){try{return Jt.statementEntry.safeParse(e).success?new qt(e,t):void console.error("Missing required StatementEntry fields:",e)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){const r=[];for(const n of e){const e=qt.from(n,t);if(!e)return;r.push(e)}return r}toJSON(){return{accountNo:this.accountNo,debitOrCredit:this.debitOrCredit,tranRefNo:this.tranRefNo,cbaRefNo:this.cbaRefNo,narration:this.narration,txnDate:this.txnDate?.toISOString(),valueDate:this.valueDate?.toISOString(),amountCredited:this.amountCredited?.toJSON()??null,amountDebited:this.amountDebited?.toJSON()??null,balance:this.balance.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=r.Amount.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let n=0;if(e.amountCredited){const t=r.Amount.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);n=t.numericValue}let s=0;if(e.amountDebited){const t=r.Amount.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);s=t.numericValue}const a={accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,cbaRefNo:e.cbaRefNo,narration:e.narration,txnDate:e.txnDate?e.txnDate:null,valueDate:e.valueDate?e.valueDate:null,amountCredited:n,amountDebited:s,balance:t.numericValue};return new qt(a,e.currency)}catch(e){return void console.error("Error creating StatementEntry from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=qt.fromJSON(r);if(!e)return;t.push(e)}return t}static getTotalCredits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isCredit()&&t.amountCredited?e+t.amountCredited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getTotalDebits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isDebit()&&t.amountDebited?e+t.amountDebited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",n=qt.getTotalCredits(e).numericValue,s=qt.getTotalDebits(e).numericValue;return r.Amount.from(n-s,t)??r.Amount.from(0,t)}}class Wt{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=r.Amount.from(e.yesterday,t)??r.Amount.from(0,t),this.today=r.Amount.from(e.today,t)??r.Amount.from(0,t),this.thisMonth=r.Amount.from(e.thisMonth,t)??r.Amount.from(0,t),this.lastMonth=r.Amount.from(e.lastMonth,t)??r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new Wt(e,t)}toJSON(){return{yesterday:this.yesterday.toJSON(),today:this.today.toJSON(),thisMonth:this.thisMonth.toJSON(),lastMonth:this.lastMonth.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!(r.AmountFactory.getInstance().isAmountJSON(e.yesterday)&&r.AmountFactory.getInstance().isAmountJSON(e.today)&&r.AmountFactory.getInstance().isAmountJSON(e.thisMonth)&&r.AmountFactory.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJSON(e.yesterday),n=r.Amount.fromJSON(e.today),s=r.Amount.fromJSON(e.thisMonth),a=r.Amount.fromJSON(e.lastMonth);if(!(t&&n&&s&&a))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const o={yesterday:t.numericValue,today:n.numericValue,thisMonth:s.numericValue,lastMonth:a.numericValue};return new Wt(o,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class Gt{accountName;accountNo;accountNumber;availableBalance;currentBalance;actualBalance;accountStatus;type;currencyCode;countryCode;currency;constructor(e){let t="TZS";e.currencyCode&&r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.accountName=e.accountName,this.accountNo=e.accountNo,this.accountNumber=e.accountNo,this.currency=t,this.currencyCode=t,this.countryCode=e.countryCode,this.availableBalance=r.Amount.from(e.availableBalance,t)??r.Amount.from(0,t),this.currentBalance=r.Amount.from(e.currentBalance,t)??r.Amount.from(0,t),this.actualBalance=this.currentBalance,this.accountStatus=e.accountStatus,this.type=e.type}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new Gt(e)}toJSON(){return{accountName:this.accountName,accountNo:this.accountNo,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJSON(),currentBalance:this.currentBalance.toJSON(),actualBalance:this.actualBalance.toJSON(),accountStatus:this.accountStatus,type:this.type,currencyCode:this.currencyCode,countryCode:this.countryCode,currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.availableBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=r.Amount.fromJSON(e.availableBalance),n=e.currentBalance??e.actualBalance;if(!r.AmountFactory.getInstance().isAmountJSON(n))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const s=r.Amount.fromJSON(n);if(!t||!s)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const a=e.accountNo||e.accountNumber;if(!a)return void console.error("Missing account number in WalletInfo JSON:",e);const o={accountName:e.accountName,accountNo:a,availableBalance:t.numericValue,currentBalance:s.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new Gt(o)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=Gt.fromJSON(r);if(!e)return;t.push(e)}return t}}var Ht,Kt;exports.FilterOperator=void 0,(Ht=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",Ht.NOT_EQUALS="neq",Ht.LESS_THAN="lt",Ht.LESS_THAN_OR_EQUAL="lte",Ht.GREATER_THAN="gt",Ht.GREATER_THAN_OR_EQUAL="gte",Ht.LIKE="like",Ht.LIKE_LOWER="likeLower",Ht.IS_NULL="isNull",Ht.IS_NOT_NULL="isNotNull",Ht.IN="in",exports.SortDirection=void 0,(Kt=exports.SortDirection||(exports.SortDirection={})).ASC="asc",Kt.DESC="desc";const Qt=Symbol("query-builder-type");class Xt{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[Qt]="query-builder";static is(e){return null!==e&&"object"==typeof e&&Qt in e&&"query-builder"===e[Qt]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new Xt(e)}}const er={AIRTEL:{key:"AIRTEL",networkOperator:"Airtel",serviceName:"Airtel Money"},VODACOM:{key:"VODACOM",networkOperator:"Vodacom",serviceName:"M-Pesa"},TIGO:{key:"TIGO",networkOperator:"Yas",serviceName:"Mixx by Yas"},HALOTEL:{key:"HALOTEL",networkOperator:"Halotel",serviceName:"HaloPesa"},SAFARICOM:{key:"SAFARICOM",networkOperator:"Safaricom",serviceName:"M-Pesa"}};var tr;exports.USER_ROLE=void 0,(tr=exports.USER_ROLE||(exports.USER_ROLE={})).READ_ONLY="ReadOnly",tr.ADMIN="Admin",tr.INITIATOR="Initiator",tr.APPROVER="Approver";const rr=t.z.enum(exports.USER_ROLE),nr={user:t.z.object({token:t.z.string(),identity:t.z.string(),name:t.z.string(),role:rr}),userRole:rr,loginRequest:t.z.object({identity:t.z.email(),password:t.z.string()}),updatePassword:t.z.object({currentPassword:t.z.string(),newPassword:t.z.string()})},sr=_t().router({login:{method:"POST",path:"/login",body:nr.loginRequest,responses:{201:nr.user,400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:nr.updatePassword,responses:{201:o.default.object({}),400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Update password",description:"Update user password"}});class ar{identity;name;role;constructor(e){this.identity=e.identity,this.name=e.name,this.role=e.role}static from(e){return new ar(e)}static fromJSON(e){return ar.from(e)}toJSON(){return{identity:this.identity,name:this.name,role:this.role}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}hasRole(e){return this.role===e}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(this.identity)}getInitials(){return this.getDisplayName().split(" ").map(e=>e.charAt(0).toUpperCase()).slice(0,2).join("")}equals(e){return this.identity===e.identity&&this.name===e.name&&this.role===e.role}}var or,ir,cr;function ur(e){return Object.values(exports.COLLECTION_STATUS_CODE).find(t=>t===e)??exports.COLLECTION_STATUS_CODE.UNKNOWN}exports.COLLECTION_STATUS=void 0,(or=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",or.PENDING_ACK="PENDING_ACK",or.PAYMENT_FAILED="PAYMENT_FAILED",or.PAYMENT_EXPIRED="PAYMENT_EXPIRED",or.GENERIC_FAILURE="GENERIC_FAILURE",or.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",or.INVALID_REFERENCE="INVALID_REFERENCE",or.PAYMENT_REJECTED="PAYMENT_REJECTED",or.PENDING="PENDING",or.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_STATUS_CODE=void 0,(ir=exports.COLLECTION_STATUS_CODE||(exports.COLLECTION_STATUS_CODE={})).AWAITING_USER="AWAITING_USER",ir.PROVIDER_UNCERTAIN="PROVIDER_UNCERTAIN",ir.SUCCESS="SUCCESS",ir.USER_TIMEOUT="USER_TIMEOUT",ir.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",ir.INVALID_NUMBER="INVALID_NUMBER",ir.INVALID_PIN="INVALID_PIN",ir.ACCOUNT_LOCKED="ACCOUNT_LOCKED",ir.ACCOUNT_RESTRICTED="ACCOUNT_RESTRICTED",ir.USER_CANCELLED="USER_CANCELLED",ir.USER_BUSY="USER_BUSY",ir.USER_UNREACHABLE="USER_UNREACHABLE",ir.LIMIT_EXCEEDED="LIMIT_EXCEEDED",ir.INVALID_AMOUNT="INVALID_AMOUNT",ir.PROVIDER_BUSY="PROVIDER_BUSY",ir.PROVIDER_ERROR="PROVIDER_ERROR",ir.UNKNOWN="UNKNOWN",exports.COLLECTION_CHANNEL=void 0,(cr=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",cr.TIGO="TZ-TIGO-C2B",cr.HALOTEL="TZ-HALOTEL-C2B",cr.SAFARICOM="KE-SAFARICOM-C2B",cr.VODACOM="TZ-VODACOM-C2B",cr.CRDB="TZ-CRDB",cr.ECOBANK="TZ-ECOBANK";const dr=t.z.enum(exports.COLLECTION_STATUS),lr=t.z.enum(exports.COLLECTION_STATUS_CODE),hr=t.z.enum(exports.COLLECTION_CHANNEL),mr=e=>{const t=Array.isArray(e)?e.flatMap(e=>mr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},pr=t.z.union([t.z.string(),t.z.array(t.z.string())]),fr={collection:t.z.object({id:t.z.string().min(1),status:dr,statusCode:t.z.unknown().optional().transform(ur),statusMessage:t.z.string(),accountNo:t.z.string().min(1),walletId:t.z.string(),transactionDate:t.z.iso.datetime(),narration:t.z.string(),msisdn:t.z.string().min(1),channel:hr,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),reference:t.z.string(),partnerReference:t.z.string().nullable().optional(),payerName:t.z.string().nullable().optional(),payerReference:t.z.string().nullable().optional(),merchantName:t.z.string().nullable().optional(),merchantReference:t.z.string().nullable().optional(),transactionId:t.z.string().nullable().optional(),serviceFeeTransactionId:t.z.string().nullable().optional(),requestId:t.z.string().nullable().optional(),completedAt:t.z.iso.datetime().nullable().optional(),createdAt:t.z.iso.datetime(),updatedAt:t.z.iso.datetime(),notes:t.z.string().optional(),currencyCode:t.z.string().default("TZS")}),collectionFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.iso.datetime().optional(),endDate:t.z.iso.datetime().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),reference:t.z.string().optional(),referenceIn:t.z.array(t.z.string()).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:hr.optional(),channelIn:t.z.array(hr).optional(),status:dr.optional(),statusIn:t.z.array(dr).optional(),statusCode:lr.optional(),statusCodeIn:t.z.array(lr).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),collectionURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:pr.transform(mr).optional(),reference:t.z.string().optional(),referenceIn:pr.transform(mr).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:t.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),channelIn:pr.transform(mr).pipe(t.z.array(hr)).optional(),status:t.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),statusIn:pr.transform(mr).pipe(t.z.array(dr)).optional(),statusCode:lr.optional(),statusCodeIn:pr.transform(mr).pipe(t.z.array(lr)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),paymentStatus:dr,statusCode:lr,paymentChannel:hr},yr=_t().router({getCollections:{method:"GET",path:"/",query:fr.collectionURLQueryParams,responses:{200:t.z.object({results:t.z.array(fr.collection),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:fr.collection,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),gr={[exports.COLLECTION_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS.PENDING]:{label:"Pending",description:"The payment is pending",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_FAILED]:{label:"Payment Failed",description:"The payment did not go through. See the status code for the reason",category:"failed",color:"error",userFriendlyMessage:"Payment failed. Please try again"},[exports.COLLECTION_STATUS.PAYMENT_EXPIRED]:{label:"Payment Expired",description:"The customer did not respond to the payment prompt in time",category:"failed",color:"error",userFriendlyMessage:"Payment request expired before it was approved"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS]:{label:"Insufficient Funds",description:"The payer has insufficient funds to complete the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.COLLECTION_STATUS.INVALID_REFERENCE]:{label:"Invalid Reference",description:"This collection was not found on the provider's side",category:"failed",color:"error",userFriendlyMessage:"Payment could not be found with the provider"},[exports.COLLECTION_STATUS.PROVIDER_FAILED]:{label:"Provider Failed",description:"An error occurred on the telecom provider's side, and the payment request was not successfully processed",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an issue with the provider"}},Tr={[exports.COLLECTION_STATUS_CODE.AWAITING_USER]:{label:"Awaiting Customer",description:"The prompt was sent and the customer has not responded yet",status:exports.COLLECTION_STATUS.PENDING_ACK,userFriendlyMessage:"Waiting for the customer to approve the payment"},[exports.COLLECTION_STATUS_CODE.PROVIDER_UNCERTAIN]:{label:"Outcome Unconfirmed",description:"The outcome is not yet known",status:exports.COLLECTION_STATUS.PENDING_ACK,userFriendlyMessage:"Payment is being confirmed with the provider"},[exports.COLLECTION_STATUS_CODE.SUCCESS]:{label:"Success",description:"Payment completed",status:exports.COLLECTION_STATUS.PAYMENT_ACCEPTED,userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS_CODE.USER_TIMEOUT]:{label:"Customer Timeout",description:"The prompt reached the customer but they did not answer in time",status:exports.COLLECTION_STATUS.PAYMENT_EXPIRED,userFriendlyMessage:"The customer did not approve the payment in time"},[exports.COLLECTION_STATUS_CODE.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Not enough money in the customer's wallet",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"Insufficient balance to complete the payment"},[exports.COLLECTION_STATUS_CODE.INVALID_NUMBER]:{label:"Invalid Number",description:"The phone number is wrong or not registered for mobile money",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The phone number is not registered for mobile money"},[exports.COLLECTION_STATUS_CODE.INVALID_PIN]:{label:"Invalid PIN",description:"The customer entered a wrong PIN",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer entered a wrong PIN"},[exports.COLLECTION_STATUS_CODE.ACCOUNT_LOCKED]:{label:"Account Locked",description:"Too many wrong PINs. The customer's wallet is locked",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is locked"},[exports.COLLECTION_STATUS_CODE.ACCOUNT_RESTRICTED]:{label:"Account Restricted",description:"The wallet is barred, blocked or not activated",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is restricted"},[exports.COLLECTION_STATUS_CODE.USER_CANCELLED]:{label:"Cancelled by Customer",description:"The customer declined or cancelled the prompt",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer cancelled the payment"},[exports.COLLECTION_STATUS_CODE.USER_BUSY]:{label:"Customer Busy",description:"The customer has another USSD session open",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone was busy with another session"},[exports.COLLECTION_STATUS_CODE.USER_UNREACHABLE]:{label:"Customer Unreachable",description:"The prompt could not be delivered (phone off, no network)",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone could not be reached"},[exports.COLLECTION_STATUS_CODE.LIMIT_EXCEEDED]:{label:"Limit Exceeded",description:"The customer hit a transaction, daily or wallet limit",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's transaction limit was exceeded"},[exports.COLLECTION_STATUS_CODE.INVALID_AMOUNT]:{label:"Invalid Amount",description:"The amount is below the minimum, above the maximum, or badly formatted",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The payment amount is not allowed"},[exports.COLLECTION_STATUS_CODE.PROVIDER_BUSY]:{label:"Provider Busy",description:"The mobile money provider is busy",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The mobile money provider is busy"},[exports.COLLECTION_STATUS_CODE.PROVIDER_ERROR]:{label:"Provider Error",description:"A system error on TemboPlus's side or the provider's side",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"Payment failed due to a system error"},[exports.COLLECTION_STATUS_CODE.UNKNOWN]:{label:"Unknown Reason",description:"The payment failed but the reason was not given",status:exports.COLLECTION_STATUS.PAYMENT_FAILED,userFriendlyMessage:"Payment failed for an unknown reason"}},Ar={[exports.COLLECTION_CHANNEL.AIRTEL]:er.AIRTEL,[exports.COLLECTION_CHANNEL.TIGO]:er.TIGO,[exports.COLLECTION_CHANNEL.HALOTEL]:er.HALOTEL,[exports.COLLECTION_CHANNEL.VODACOM]:er.VODACOM,[exports.COLLECTION_CHANNEL.SAFARICOM]:er.SAFARICOM};function vr(e){return Object.entries(gr).filter(([t,r])=>r.category===e).map(([e])=>e)}class Er{id;status;statusCode;statusMessage;accountNo;walletId;transactionDate;narration;msisdn;channel;amount;serviceFee;postedAmount;reference;partnerReference;payerName;payerReference;merchantName;merchantReference;transactionId;serviceFeeTransactionId;requestId;completedAt;createdAt;updatedAt;notes;currencyCode;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,this.statusCode=ur(e.statusCode),this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.serviceFee=e.serviceFee?r.Amount.from(parseFloat(e.serviceFee),t)??r.Amount.from(0,t):void 0,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t)??r.Amount.from(0,t):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.payerName=e.payerName,this.payerReference=e.payerReference,this.merchantName=e.merchantName,this.merchantReference=e.merchantReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return"pending"===gr[this.status]?.category}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return"failed"===gr[this.status]?.category}isExpired(){return this.status===exports.COLLECTION_STATUS.PAYMENT_EXPIRED}isFinal(){return this.isSuccessful()||this.isFailed()}getStatusInfo(){return gr[this.status]}getStatusCode(){return this.statusCode}getStatusCodeInfo(){return Tr[this.statusCode]}getChannelInfo(){return Ar[this.channel]}getProviderName(){return this.getChannelInfo()?.networkOperator}getServiceName(){return this.getChannelInfo()?.serviceName}isMobileCollection(){return this.channel in Ar}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Er(t):void console.error("Missing required Collection fields:",e)}catch(e){return void console.error("Error creating Collection:",e)}}static createMany(e){const t=[];for(const r of e){const e=Er.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Collection JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,s;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);s=t.numericValue.toString()}const a={id:e.id,status:e.status,statusCode:e.statusCode,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee:n,postedAmount:s,reference:e.reference,partnerReference:e.partnerReference,payerName:e.payerName,payerReference:e.payerReference,merchantName:e.merchantName,merchantReference:e.merchantReference,transactionId:e.transactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,requestId:e.requestId,completedAt:e.completedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,notes:e.notes,currencyCode:e.currencyCode};return new Er(a)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=Er.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,statusCode:this.statusCode,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJSON(),serviceFee:this.serviceFee?.toJSON(),postedAmount:this.postedAmount?.toJSON(),reference:this.reference,partnerReference:this.partnerReference,payerName:this.payerName,payerReference:this.payerReference,merchantName:this.merchantName,merchantReference:this.merchantReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:this.completedAt?.toISOString()??null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}const _r=["id","reference","channel","status","statusCode"];class Nr extends Xt{static create(){return new Nr}static fromFilters(e){return(new Nr).applyFilters(e)}static fromUrlParams(e){try{const t=fr.collectionURLQueryParams.parse(Nr.normalizeUrlParams(e)),r=fr.collectionFilters.parse(t);return Nr.fromFilters(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Nr.fromUrlParams(Nr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Nr.fromSearchParams(t)}static from(e){try{return null==e?new Nr:Xt.is(e)?new Nr(e.options):e instanceof URLSearchParams?Nr.fromSearchParams(e):Nr.isUrlParamsRecord(e)?Nr.fromUrlParams(e):Nr.fromFilters(e)}catch(e){throw console.log(e),new Error("Invalid input! Could not create a CollectionQuery instance.")}}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of _r){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,o=`${e}In[]`,i=t[r],c=mr([t[n],t[s],t[a],t[o],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[s],delete t[a],delete t[o]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereStatusCode(e){return this.where("statusCode",e)}whereStatusCodeIn(e){return this.whereInValues("statusCode",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}whereIdIn(e){return this.whereInValues("id",e)}whereReferenceIn(e){return this.whereInValues("reference",e)}wherePending(){return this.whereStatusIn(vr("pending"))}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereStatusIn(vr("failed"))}whereExpired(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_EXPIRED)}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("reference",e)}wherePartnerReference(e){return this.where("partnerReference",e)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.statusCodeIn?.length?this.whereStatusCodeIn(e.statusCodeIn):e.statusCode&&this.whereStatusCode(e.statusCode),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.referenceIn?.length?this.whereReferenceIn(e.referenceIn):e.reference&&this.whereReference(e.reference),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,id:e.id,idIn:e.idIn,reference:e.reference,referenceIn:e.referenceIn,accountNo:e.accountNo,walletId:e.walletId,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),statusCode:this.isValidStatusCode(e.statusCode)?e.statusCode:void 0,statusCodeIn:this.getValidStatusCodes(e.statusCodeIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.idIn?.length||e.reference||e.referenceIn?.length||e.accountNo||e.walletId||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.statusCode||e.statusCodeIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.statusCodeIn?.length?e.push(`Reason: ${t.statusCodeIn.join(", ")}`):t.statusCode&&e.push(`Reason: ${t.statusCode}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.referenceIn?.length?e.push(`Reference: ${t.referenceIn.join(", ")}`):t.reference&&e.push(`Reference: ${t.reference}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=mr(t.value);r.length>0&&(e[`${t.field}In`]=r);continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"reference":case"accountNo":case"walletId":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=mr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=mr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidStatusCodes(e){const t=mr(e).filter(e=>this.isValidStatusCode(e));return t.length>0?t:void 0}getValidChannels(e){const t=mr(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).some(t=>t===e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).some(t=>t===e)}isValidStatusCode(e){return Object.values(exports.COLLECTION_STATUS_CODE).some(t=>t===e)}}var Sr,Ir;exports.PAYOUT_STATUS=void 0,(Sr=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",Sr.GENERIC_FAILURE="GENERIC_FAILURE",Sr.WALLET_DEBITED="WALLET_DEBITED",Sr.PAYMENT_REJECTED="PAYMENT_REJECTED",Sr.PENDING="PENDING",Sr.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",Sr.PENDING_ACK="PENDING_ACK",Sr.REVERSED="REVERSED",Sr.INVALID_SERVICE="INVALID_SERVICE",Sr.INVALID_NUMBER="INVALID_NUMBER",Sr.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Sr.THIRDPARTY_FAILED="THIRDPARTY_FAILED",Sr.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(Ir=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",Ir.VODACOM="TZ-VODACOM-B2C",Ir.TIGO="TZ-TIGO-B2C",Ir.HALOTEL="TZ-HALOTEL-B2C",Ir.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const Cr=t.z.enum(exports.PAYOUT_STATUS),Or=t.z.enum(exports.MOBILE_PAYOUT_CHANNEL),br=t.z.enum(exports.BANK_PAYOUT_CHANNEL),wr=t.z.union([Or,br]),xr=e=>{const t=Array.isArray(e)?e.flatMap(e=>xr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},Rr=t.z.union([t.z.string(),t.z.array(t.z.string())]),Lr={payout:t.z.object({id:t.z.string().min(1),statusCode:t.z.string(),statusCodeText:Cr,statusDescription:t.z.string(),countryCode:t.z.string(),serviceCode:wr,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),walletId:t.z.string().optional(),msisdn:t.z.string().min(1),narration:t.z.string(),currencyCode:t.z.string(),recipientNames:t.z.string().optional(),transactionRef:t.z.string(),transactionDate:t.z.iso.datetime(),externalId:t.z.string().nullable().optional(),cbaReferenceNo:t.z.string().optional(),beepTransactionId:t.z.string().optional(),receiptNumber:t.z.string().optional(),createdAt:t.z.iso.datetime(),reversedTransactionId:t.z.string().nullable().optional(),transactionId:t.z.string(),serviceFeeTransactionId:t.z.string().optional(),isReconciled:t.z.number().optional(),requestId:t.z.string().optional(),notes:t.z.string().optional(),updatedAt:t.z.iso.datetime().optional()}),payoutFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.iso.datetime().optional(),endDate:t.z.iso.datetime().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),ref:t.z.string().optional(),refIn:t.z.array(t.z.string()).optional(),channelRef:t.z.string().optional(),channelRefIn:t.z.array(t.z.string()).optional(),channel:wr.optional(),channelIn:t.z.array(wr).optional(),status:Cr.optional(),statusIn:t.z.array(Cr).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),payoutURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:Rr.transform(xr).optional(),ref:t.z.string().optional(),refIn:Rr.transform(xr).optional(),channelRef:t.z.string().optional(),channelRefIn:Rr.transform(xr).optional(),channel:t.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),channelIn:Rr.transform(xr).pipe(t.z.array(wr)).optional(),status:t.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),statusIn:Rr.transform(xr).pipe(t.z.array(Cr)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),payoutStatus:Cr,payoutChannel:wr,mobileChannel:Or,bankChannel:br,walletSummary:t.z.object({balance:t.z.number(),currency:t.z.string(),lastUpdated:t.z.iso.datetime()}),transactionSummary:t.z.object({yesterday:t.z.number(),today:t.z.number(),thisMonth:t.z.number(),lastMonth:t.z.number()}),pagination:t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),totalPages:t.z.number(),hasNext:t.z.boolean(),hasPrev:t.z.boolean()})},Pr=_t().router({getPayouts:{method:"GET",path:"",query:Lr.payoutURLQueryParams,responses:{200:t.z.object({results:t.z.array(Lr.payout),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:Lr.payout,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),Dr={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.PROVIDER_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"},[exports.PAYOUT_STATUS.INVALID_NUMBER]:{label:"Invalid Number",description:"The number used is either barred or invalid",category:"failed",color:"error",userFriendlyMessage:"Recipient’s number is invalid, inactive, or temporarily blocked."}},Ur={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:er.AIRTEL,[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:er.VODACOM,[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:er.TIGO,[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:er.HALOTEL,[exports.MOBILE_PAYOUT_CHANNEL.SAFARICOM]:er.SAFARICOM};function kr(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function Fr(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class zr{id;serviceCode;msisdn;amount;transactionDate;statusDescription;statusCodeText;transactionId;transactionRef;recipientNames;narration;serviceFee;notes;swiftCode;createdAt;updatedAt;statusCode;countryCode;postedAmount;walletId;currencyCode;externalId;cbaReferenceNo;beepTransactionId;receiptNumber;reversedTransactionId;serviceFeeTransactionId;isReconciled;requestId;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.transactionDate=new Date(e.transactionDate),this.statusDescription=e.statusDescription,this.statusCodeText=e.statusCodeText,this.transactionId=e.transactionId,this.transactionRef=e.transactionRef,this.recipientNames=e.recipientNames,this.narration=e.narration,this.serviceFee=void 0===e.serviceFee?void 0:r.Amount.from(e.serviceFee,t)??r.Amount.from(0,t),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=e.updatedAt?new Date(e.updatedAt):void 0,this.statusCode=e.statusCode,this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t):void 0,this.walletId=e.walletId,this.currencyCode=e.currencyCode,this.externalId=e.externalId,this.cbaReferenceNo=e.cbaReferenceNo,this.beepTransactionId=e.beepTransactionId,this.receiptNumber=e.receiptNumber,this.reversedTransactionId=e.reversedTransactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.isReconciled=e.isReconciled,this.requestId=e.requestId}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Dr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return Dr[this.statusCodeText]}getChannelInfo(){if(kr(this.serviceCode))return Ur[this.serviceCode];if(Fr(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankHelpers.validateSwiftCode(e)){if(r.BankHelpers.getCountryFromSwiftCode(e))try{return r.BankRegistry.getInstance().detectBank(e)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankHelpers.getCountryFromSwiftCode(this.swiftCode)){if(r.BankHelpers.getCountryFromSwiftCode(this.swiftCode))try{return r.BankRegistry.getInstance().detectBank(this.swiftCode)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getAccountNumber(){try{if(kr(this.serviceCode))return this.msisdn;if(Fr(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch{console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return kr(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new zr(t):void console.error("Missing required Payout fields:",e)}catch(e){return void console.error("Error creating Payout:",e)}}static createMany(e){const t=[];for(const r of e){const e=zr.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Payout JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,s;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);s=t.numericValue.toString()}const a={id:e.id,serviceCode:e.serviceCode,msisdn:e.msisdn,amount:t.numericValue,transactionDate:e.transactionDate,statusDescription:e.statusDescription,statusCodeText:e.statusCodeText,transactionId:e.transactionId,transactionRef:e.transactionRef,recipientNames:e.recipientNames,narration:e.narration,serviceFee:n,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:s,walletId:e.walletId,currencyCode:e.currencyCode,externalId:e.externalId,cbaReferenceNo:e.cbaReferenceNo,beepTransactionId:e.beepTransactionId,receiptNumber:e.receiptNumber,reversedTransactionId:e.reversedTransactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,isReconciled:e.isReconciled,requestId:e.requestId};return new zr(a)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=zr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJSON(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:this.serviceFee?.toJSON(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt?.toISOString(),statusCode:this.statusCode,countryCode:this.countryCode,postedAmount:this.postedAmount?.toJSON(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}const Mr=["status","channel","id","ref","channelRef"],jr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class Br extends Xt{static create(){return new Br}static fromFilters(e){return(new Br).applyFilters(e)}static fromUrlParams(e){try{const t=Lr.payoutURLQueryParams.parse(Br.normalizeUrlParams(e)),r=Lr.payoutFilters.parse(t);return Br.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Br.fromUrlParams(Br.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Br.fromSearchParams(t)}static from(e){return null==e?new Br:Xt.is(e)?new Br(e.options):e instanceof URLSearchParams?Br.fromSearchParams(e):Br.isUrlParamsRecord(e)?Br.fromUrlParams(e):Br.fromFilters(e)}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of Mr){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,o=`${e}In[]`,i=t[r],c=xr([t[n],t[s],t[a],t[o],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[s],delete t[a],delete t[o]}return t}whereStatus(e){return this.where("statusCodeText",e)}whereStatusIn(e){return this.whereInValues("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}whereChannelIn(e){return this.whereInValues("serviceCode",e)}whereIdIn(e){return this.whereInValues("id",e)}whereRefIn(e){return this.whereInValues("transactionRef",e)}whereChannelRef(e){return this.whereContains("channelReference",e)}whereChannelRefIn(e){return this.whereInValues("channelReference",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.refIn?.length?this.whereRefIn(e.refIn):e.ref&&this.whereReference(e.ref),e.channelRefIn?.length?this.whereChannelRefIn(e.channelRefIn):e.channelRef&&this.whereChannelRef(e.channelRef),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,accountNo:e.accountNo,walletId:e.walletId,id:e.id,idIn:e.idIn,ref:e.transactionRef,refIn:e.refIn,channelRef:e.channelReference,channelRefIn:e.channelRefIn,channel:this.isValidChannel(e.serviceCode)?e.serviceCode:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.statusCodeText)?e.statusCodeText:void 0,statusIn:this.getValidStatuses(e.statusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.accountNo||e.walletId||e.id||e.idIn?.length||e.ref||e.refIn?.length||e.channelRef||e.channelRefIn?.length||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Recipient: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.refIn?.length?e.push(`Reference: ${t.refIn.join(", ")}`):t.ref&&e.push(`Reference: ${t.ref}`),t.channelRefIn?.length?e.push(`Channel Ref: ${t.channelRefIn.join(", ")}`):t.channelRef&&e.push(`Channel Ref: ${t.channelRef}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=xr(t.value);if(0===r.length)continue;e[`${jr[t.field]??t.field}In`]=r;continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"accountNo":case"walletId":case"transactionRef":case"channelReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=xr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=xr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=xr(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).some(t=>t===e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).some(t=>t===e)}}var Zr,Vr,$r,Jr;exports.SETTLEMENT_STATUS=void 0,(Zr=exports.SETTLEMENT_STATUS||(exports.SETTLEMENT_STATUS={})).PENDING="PENDING",Zr.APPROVED="APPROVED",Zr.PROCESSING="PROCESSING",Zr.PROCESSED="PROCESSED",Zr.REJECTED="REJECTED",exports.SETTLEMENT_ACTION=void 0,(Vr=exports.SETTLEMENT_ACTION||(exports.SETTLEMENT_ACTION={})).APPROVED="APPROVED",Vr.REJECTED="REJECTED",exports.CREATE_SETTLEMENT_STATUS=void 0,($r=exports.CREATE_SETTLEMENT_STATUS||(exports.CREATE_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",$r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",$r.INITIATOR_NOT_AUTHORIZED="INITIATOR_NOT_AUTHORIZED",$r.MISSING_BANK_DETAILS="MISSING_BANK_DETAILS",$r.UNSUPPORTED_BANK_CODE="UNSUPPORTED_BANK_CODE",$r.FAILED="FAILED",exports.ACTION_SETTLEMENT_STATUS=void 0,(Jr=exports.ACTION_SETTLEMENT_STATUS||(exports.ACTION_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",Jr.SETTLEMENT_NOT_FOUND="SETTLEMENT_NOT_FOUND",Jr.ACTIONER_NOT_AUTHORIZED="ACTIONER_NOT_AUTHORIZED",Jr.SELF_ACTION_NOT_ALLOWED="SELF_ACTION_NOT_ALLOWED",Jr.INVALID_STATE="INVALID_STATE",Jr.FAILED="FAILED";const Yr=t.z.enum(exports.SETTLEMENT_STATUS),qr=t.z.enum(exports.SETTLEMENT_ACTION),Wr=t.z.enum(exports.CREATE_SETTLEMENT_STATUS),Gr=t.z.enum(exports.ACTION_SETTLEMENT_STATUS),Hr=t.z.object({id:t.z.string().min(1),date:t.z.string(),initiatedAt:t.z.string().nullish(),initiatedById:t.z.string().nullish(),actionedAt:t.z.string().nullish(),actionedById:t.z.string().nullish(),vendorId:t.z.string(),walletId:t.z.string(),accountNo:t.z.string(),status:Yr,statusCode:t.z.string().nullish(),description:t.z.string(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),amount:t.z.number(),payoutId:t.z.string().nullish(),transactionId:t.z.string().nullish(),createdAt:t.z.string(),updatedAt:t.z.string()}),Kr=t.z.object({status:Yr.optional(),amount:t.z.number().optional(),accountNo:t.z.string().optional()}),Qr=t.z.object({status:Yr.optional(),amount:t.z.coerce.number().optional(),accountNo:t.z.string().optional()}),Xr=t.z.object({accountNo:t.z.string().min(1,"Account number is required"),description:t.z.string().min(1,"Description is required"),amount:t.z.number().refine(e=>0!==e,"Amount must not be 0")}),en=t.z.object({status:Wr,data:Hr.optional()}),tn=t.z.object({status:qr}),rn=t.z.object({status:Gr,data:Hr.optional()}),nn={settlement:Hr,settlementStatus:Yr,settlementAction:qr,settlementFilters:Kr,settlementURLQueryParams:Qr,createSettlementRequest:Xr,createSettlementStatus:Wr,createSettlementResponse:en,actionSettlementRequest:tn,actionSettlementStatus:Gr,actionSettlementResponse:rn},sn=_t().router({getSettlements:{method:"GET",path:"",query:nn.settlementFilters,responses:{200:t.z.array(nn.settlement),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List settlements",description:"Retrieve settlements belonging to your vendor, with optional filtering and sorting via query params"},getSettlement:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:nn.settlement,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get settlement details",description:"Retrieve detailed information about a specific settlement"},createSettlement:{method:"POST",path:"",body:nn.createSettlementRequest,responses:{201:nn.createSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Create settlement",description:"Create a new settlement request initiated by the authenticated user. Expected failures (e.g. WALLET_NOT_FOUND) are reported via the body `status` field, not HTTP errors"},actionSettlement:{method:"POST",path:"/:id/action",pathParams:t.z.object({id:t.z.string()}),body:nn.actionSettlementRequest,responses:{201:nn.actionSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Action settlement",description:"Approve or reject a PENDING settlement as the authenticated user. Expected failures (e.g. INVALID_STATE) are reported via the body `status` field, not HTTP errors"}}),an={[exports.SETTLEMENT_STATUS.PENDING]:{label:"Pending",description:"Pending approval or rejection",category:"pending",color:"warning",userFriendlyMessage:"Settlement is awaiting approval"},[exports.SETTLEMENT_STATUS.APPROVED]:{label:"Approved",description:"Approved by an admin or approver",category:"success",color:"success",userFriendlyMessage:"Settlement was approved"},[exports.SETTLEMENT_STATUS.PROCESSING]:{label:"Processing",description:"Approved and being processed to the settlement bank account",category:"processing",color:"info",userFriendlyMessage:"Settlement is being processed to your bank account"},[exports.SETTLEMENT_STATUS.PROCESSED]:{label:"Processed",description:"Approved and processed successfully",category:"success",color:"success",userFriendlyMessage:"Settlement was processed successfully"},[exports.SETTLEMENT_STATUS.REJECTED]:{label:"Rejected",description:"Rejected by an admin or approver",category:"failed",color:"error",userFriendlyMessage:"Settlement was rejected"}};function on(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}class cn{id;date;initiatedAt;initiatedById;actionedAt;actionedById;vendorId;walletId;accountNo;status;statusCode;description;bankAccountNo;bankAccountName;bankCode;amount;payoutId;transactionId;createdAt;updatedAt;_originalData;constructor(e){this._originalData={...e},this.id=e.id,this.date=new Date(e.date),this.initiatedAt=on(e.initiatedAt),this.initiatedById=e.initiatedById,this.actionedAt=on(e.actionedAt),this.actionedById=e.actionedById,this.vendorId=e.vendorId,this.walletId=e.walletId,this.accountNo=e.accountNo,this.status=e.status,this.statusCode=e.statusCode,this.description=e.description,this.bankAccountNo=e.bankAccountNo,this.bankAccountName=e.bankAccountName,this.bankCode=e.bankCode,this.amount=r.Amount.from(e.amount,"TZS")??r.Amount.from(0,"TZS"),this.payoutId=e.payoutId,this.transactionId=e.transactionId,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}isPending(){return this.status===exports.SETTLEMENT_STATUS.PENDING}isApproved(){return this.status===exports.SETTLEMENT_STATUS.APPROVED}isProcessing(){return this.status===exports.SETTLEMENT_STATUS.PROCESSING}isProcessed(){return this.status===exports.SETTLEMENT_STATUS.PROCESSED}isRejected(){return this.status===exports.SETTLEMENT_STATUS.REJECTED}canBeActioned(){return this.isPending()}getStatusInfo(){return an[this.status]}static from(e){try{const t=e;return t?.id&&t?.accountNo&&void 0!==t?.amount?new cn(t):void console.error("Missing required Settlement fields:",e)}catch(e){return void console.error("Error creating Settlement:",e)}}static createMany(e){const t=[];for(const r of e){const e=cn.from(r);e&&t.push(e)}return t}static fromJSON(e){return cn.from(e)}toJSON(){return{...this._originalData}}}class un{filters;constructor(e={}){this.filters={...e}}static create(){return new un}static fromFilters(e){return new un(nn.settlementFilters.parse(e))}static fromUrlParams(e){try{const t=un.flattenParams(e),r=nn.settlementURLQueryParams.parse(t);return new un(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return un.fromUrlParams(un.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return un.fromSearchParams(t)}static from(e){try{return null==e?new un:un.is(e)?e.clone():e instanceof URLSearchParams?un.fromSearchParams(e):un.isUrlParamsRecord(e)?un.fromUrlParams(e):un.fromFilters(e)}catch(e){throw console.log(e),new Error("Invalid input! Could not create a SettlementQuery instance.")}}static is(e){return e instanceof un}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static flattenParams(e){const t=["status","amount","accountNo"],r={};for(const n of t){const t=e[n],s=(Array.isArray(t)?t[0]:t)?.trim();s&&(r[n]=s)}return r}whereStatus(e){return this.filters.status=e,this}whereAmount(e){return this.filters.amount=e,this}whereAccountNo(e){return this.filters.accountNo=e,this}wherePending(){return this.whereStatus(exports.SETTLEMENT_STATUS.PENDING)}whereApproved(){return this.whereStatus(exports.SETTLEMENT_STATUS.APPROVED)}whereProcessing(){return this.whereStatus(exports.SETTLEMENT_STATUS.PROCESSING)}whereProcessed(){return this.whereStatus(exports.SETTLEMENT_STATUS.PROCESSED)}whereRejected(){return this.whereStatus(exports.SETTLEMENT_STATUS.REJECTED)}clone(){return new un(this.filters)}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withAmount(e){const t=this.clone();return void 0!==e&&t.whereAmount(e),t}withAccountNo(e){const t=this.clone();return e&&t.whereAccountNo(e),t}toFilters(){const e={};return void 0!==this.filters.status&&(e.status=this.filters.status),void 0!==this.filters.amount&&(e.amount=this.filters.amount),void 0!==this.filters.accountNo&&(e.accountNo=this.filters.accountNo),e}build(){return this.toFilters()}toUrlParams(){const e=this.toFilters(),t={};for(const[r,n]of Object.entries(e))null!=n&&(t[r]=String(n));return t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}hasFilters(){const e=this.toFilters();return void 0!==e.status||void 0!==e.amount||void 0!==e.accountNo}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),void 0!==t.amount&&e.push(`Amount: ${t.amount}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),e}}const dn={localTransferRequest:t.z.object({amount:t.z.number().int().positive(),from:t.z.string().min(1),to:t.z.string().min(1),description:t.z.string().min(1)}),localTransferResponse:t.z.object({transactionId:t.z.string(),from:t.z.string(),to:t.z.string(),transactionDate:t.z.string(),narration:t.z.string(),amount:t.z.number(),transactionRef:t.z.string()})},ln=_t().router({localTransfer:{method:"POST",path:"/local-transfer",body:dn.localTransferRequest,responses:{201:dn.localTransferResponse,400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});const hn={vendor:t.z.object({businessName:t.z.string(),tradeName:t.z.string(),enableCollections:t.z.number(),enablePayouts:t.z.number(),enableRemittance:t.z.number(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),enableAutoSettlement:t.z.number(),disablePaymentApproval:t.z.number()})},mn=_t().router({getMe:{method:"GET",path:"/me",responses:{200:hn.vendor,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get vendor profile",description:"Retrieve the vendor profile of the authenticated user, including feature flags and bank details"}});class pn{businessName;tradeName;canCollect;canPayout;canRemit;automatedSettlements;disabledPaymentApproval;settlementAccount;constructor(e){this.businessName=e.businessName,this.tradeName=e.tradeName,this.canCollect=e.canCollect,this.canPayout=e.canPayout,this.canRemit=e.canRemit,this.automatedSettlements=e.automatedSettlements,this.disabledPaymentApproval=e.disabledPaymentApproval,this.settlementAccount=e.settlementAccount}hasSettlementAccount(){return null!==this.settlementAccount}getDisplayName(){return this.tradeName||this.businessName}static from(e){try{const t=e;if(!t?.businessName)return void console.error("Missing required Vendor fields:",e);const n=t,s=n.bankCode?r.Bank.fromBIC(n.bankCode):void 0,a=s&&n.bankAccountName&&n.bankAccountNo?{accountName:n.bankAccountName,accountNo:n.bankAccountNo,bank:s}:null;return new pn({businessName:n.businessName,tradeName:n.tradeName,canCollect:1===n.enableCollections,canPayout:1===n.enablePayouts,canRemit:1===n.enableRemittance,automatedSettlements:1===n.enableAutoSettlement,disabledPaymentApproval:1===n.disablePaymentApproval,settlementAccount:a})}catch(e){return void console.error("Error creating Vendor:",e)}}static fromJSON(e){let t=null;if(e.settlementAccount){const n=r.Bank.fromJSON(e.settlementAccount.bank);n&&(t={accountName:e.settlementAccount.accountName,accountNo:e.settlementAccount.accountNo,bank:n})}return new pn({...e,settlementAccount:t})}toJSON(){return{businessName:this.businessName,tradeName:this.tradeName,canCollect:this.canCollect,canPayout:this.canPayout,canRemit:this.canRemit,automatedSettlements:this.automatedSettlements,disabledPaymentApproval:this.disabledPaymentApproval,settlementAccount:this.settlementAccount?{accountName:this.settlementAccount.accountName,accountNo:this.settlementAccount.accountNo,bank:this.settlementAccount.bank.toJSON()}:null}}}var fn;function yn(e){switch(e){case"DEFAULT COLLECTION":case exports.WALLET_TYPE.COLLECTION:return exports.WALLET_TYPE.COLLECTION;case"Vendor":case"DEFAULT DISBURSEMENT":case exports.WALLET_TYPE.DISBURSEMENT:return exports.WALLET_TYPE.DISBURSEMENT;default:throw new TypeError(`Unsupported wallet type: ${String(e)}`)}}exports.WALLET_TYPE=void 0,(fn=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).COLLECTION="COLLECTION",fn.DISBURSEMENT="DISBURSEMENT";const gn=t.z.enum(exports.WALLET_TYPE),Tn=t.z.enum(["Vendor","DEFAULT DISBURSEMENT","DEFAULT COLLECTION","COLLECTION","DISBURSEMENT"]).transform(yn),An=t.z.object({id:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1),shadowAccountNo:t.z.string().nullish(),externalId:t.z.string().nullish(),reference:t.z.string().nullish(),type:Tn,vendorId:t.z.string().nullish(),balance:t.z.number(),minBalance:t.z.union([t.z.number(),t.z.string()]),approvalLimit:t.z.union([t.z.number(),t.z.string()]),currency:t.z.string().min(1),countryCode:t.z.string().min(1),createdAt:t.z.string().min(1),updatedAt:t.z.string().min(1)}),vn=t.z.object({availableBalance:t.z.number(),currentBalance:t.z.number(),accountStatus:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1)}),En={wallet:An,walletType:gn,walletPathParams:t.z.object({accountNo:t.z.string().min(1)}),walletBalance:vn,walletStatementQuery:t.z.object({startDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},_n=_t().router({listWallets:{method:"GET",path:"",responses:{200:t.z.array(En.wallet),401:Jt.unauthorizedError,500:Jt.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:t.z.object({accountNo:t.z.string().min(1)}),responses:{200:En.wallet,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Get wallet info",description:"Retrieve wallet metadata including balance, currency, and type for a specific wallet."},getWalletBalance:{method:"GET",path:"/:accountNo/balance",pathParams:En.walletPathParams,responses:{200:En.walletBalance,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet balance",description:"Retrieve the current and available balance for a specific wallet account number."},getWalletStatement:{method:"GET",path:"/:accountNo/statement",pathParams:En.walletPathParams,query:En.walletStatementQuery,responses:{200:t.z.array(Jt.statementEntry),400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class Nn{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){const t=yn(e.type);this._originalData={...e,type:t};let n="TZS";r.CurrencyHelpers.isCode(e.currency)?n=e.currency:"KSH"===e.currency&&(n="KES"),this.id=e.id,this.accountNo=e.accountNo,this.accountName=e.accountName,this.shadowAccountNo=e.shadowAccountNo,this.externalId=e.externalId,this.reference=e.reference,this.type=t,this.vendorId=e.vendorId,this.balance=r.Amount.from(e.balance,n)??r.Amount.from(0,n),this.minBalance=r.Amount.from(this.parseAmountValue(e.minBalance),n)??r.Amount.from(0,n),this.approvalLimit=r.Amount.from(this.parseAmountValue(e.approvalLimit),n)??r.Amount.from(0,n),this.currency=n,this.countryCode=e.countryCode,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}parseAmountValue(e){if("number"==typeof e)return e;const t=parseFloat(e);return Number.isNaN(t)?0:t}isCollectionWallet(){return this.type===exports.WALLET_TYPE.COLLECTION}isDisbursementWallet(){return this.type===exports.WALLET_TYPE.DISBURSEMENT}isDefaultWallet(){return!1}static from(e){return new Nn(e)}static createMany(e){const t=[];for(const r of e)try{t.push(Nn.from(r))}catch(e){console.warn("Skipping unsupported wallet:",e)}return t}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.minBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=r.Amount.fromJSON(e.balance),n=r.Amount.fromJSON(e.minBalance),s=r.Amount.fromJSON(e.approvalLimit);return t&&n&&s?new Nn({id:e.id,accountNo:e.accountNo,accountName:e.accountName,shadowAccountNo:e.shadowAccountNo,externalId:e.externalId,reference:e.reference,type:e.type,vendorId:e.vendorId,balance:t.numericValue,minBalance:n.numericValue,approvalLimit:s.numericValue,currency:e.currency,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt}):void console.error("Failed to reconstruct balance Amount from JSON:",e)}catch(e){return void console.error("Error creating Wallet from JSON:",e)}}}exports.APIError=Pt,exports.AuthDTOSchemas=nr,exports.AuthRepository=class extends Yt{constructor(e){super("auth",sr,e)}async login(e){const t=o.default.object({email:o.default.email().trim().toLowerCase(),password:o.default.string().min(1)}).safeParse(e);if(!t.success)throw new Pt({message:"Invalid email or password",statusCode:400});const{email:r,password:n}=t.data,s=await this.client.login({body:{identity:r,password:n}});if(400===s.status||401===s.status)throw new Pt({message:"Invalid email or password",statusCode:s.status});const{token:a,...i}=this.handleResponse(s,201);if(!a)throw new Pt({message:"Authentication token missing from server response",statusCode:500});const c=ar.from(i);if(!c)throw new Pt({message:"Invalid user data received from server",statusCode:500});return{user:c,token:a}}async updatePassword(e){const t=await this.client.updatePassword({body:e});if(201!==t.status){if(400===t.status)throw new Error("Validation error");if(401===t.status)throw new Error("Unauthorized");throw new Error("Failed to update password")}return!0}},exports.BaseRepository=Yt,exports.COLLECTION_STATUS_CODE_INFO=Tr,exports.COLLECTION_STATUS_INFO=gr,exports.Collection=Er,exports.CollectionDTOSchemas=fr,exports.CollectionQuery=Nr,exports.CollectionRepository=class extends Yt{constructor(e){super("collection",yr,e)}async getCollections(e){try{const t=Nr.from(e),r=t.build(),n=await this.client.getCollections({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),o={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},i=Er.createMany(s.results);if(!i)throw new Error("Invalid collection data received from server");return{collections:i,pagination:o}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=Nr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=Er.from(r);if(!n)throw new Error("Invalid collection data received from server");return n}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=Wt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.CommonSchemas=Jt,exports.MobileChannels=er,exports.PAYOUT_STATUS_INFO=Dr,exports.Payout=zr,exports.PayoutDTOSchemas=Lr,exports.PayoutQuery=Br,exports.PayoutRepository=class extends Yt{constructor(e){super("payout",Pr,e)}async getPayouts(e){try{const t=Br.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),o={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},i=zr.createMany(s.results);if(!i)throw new Error("Invalid payout data received from server");return{payouts:i,pagination:o}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Br.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=zr.from(r);if(!n)throw new Error("Invalid payout data received from server");return n}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=Wt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.QUERY_BUILDER_TYPE=Qt,exports.QueryBuilder=Xt,exports.SETTLEMENT_STATUS_INFO=an,exports.Settlement=cn,exports.SettlementDTOSchemas=nn,exports.SettlementQuery=un,exports.SettlementRepository=class extends Yt{constructor(e){super("settlement",sn,e)}async getSettlements(e){const t=un.from(e),r=await this.client.getSettlements({query:t.build()}),n=this.handleResponse(r,200);return cn.createMany(n)}async getSettlementsFromRequest(e){return this.getSettlements(un.fromRequest(e))}async getSettlement(e){const t=await this.client.getSettlement({params:{id:e}}),r=this.handleResponse(t,200),n=cn.from(r);if(!n)throw new Error("Invalid settlement data received from server");return n}async createSettlement(e){const t=await this.client.createSettlement({body:e}),r=this.handleResponse(t,201);return{status:r.status,settlement:r.data?cn.from(r.data):void 0}}async actionSettlement(e,t){const r=await this.client.actionSettlement({params:{id:e},body:{status:t}}),n=this.handleResponse(r,201);return{status:n.status,settlement:n.data?cn.from(n.data):void 0}}async approveSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.APPROVED)}async rejectSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.REJECTED)}},exports.StatementEntry=qt,exports.TransactionDTOSchemas=dn,exports.TransactionRepository=class extends Yt{constructor(e){super("transaction",ln,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=Wt,exports.User=ar,exports.Vendor=pn,exports.VendorDTOSchemas=hn,exports.VendorRepository=class extends Yt{constructor(e){super("vendor",mn,e)}async getMe(){const e=await this.client.getMe(),t=this.handleResponse(e,200),r=pn.from(t);if(!r)throw new Error("Invalid vendor data received from server");return r}},exports.Wallet=Nn,exports.WalletDTOSchemas=En,exports.WalletInfo=Gt,exports.WalletRepository=class extends Yt{constructor(e){super("wallet",_n,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=Nn.createMany(t);if(!r)throw new Error("Invalid wallet data received from server");return r}async getWalletInfo(e){const t=await this.client.getWalletInfo({params:{accountNo:e}}),r=this.handleResponse(t,200);return Nn.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return Gt.from(r)}async getWalletStatement(e){const t=await this.client.getWalletStatement({params:{accountNo:e.accountNo},query:{startDate:this.formatStatementDate(e.startDate),endDate:this.formatStatementDate(e.endDate)}}),r=this.handleResponse(t,200),n=qt.createMany(r);if(!n)throw new Error("Invalid statement entry data received from server");return n}formatStatementDate(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Error("Invalid statement date provided.");return e.toISOString().slice(0,10)}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;const t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error(`Invalid statement date: ${e}`);return t.toISOString().slice(0,10)}},exports.authContract=sr,exports.collectionContract=yr,exports.collectionToStringArray=mr,exports.getCollectionStatusesByCategory=vr,exports.normalizeWalletType=yn,exports.payoutContract=Pr,exports.payoutToStringArray=xr,exports.settlementContract=sn,exports.statementEntrySchema=$t,exports.toCollectionStatusCode=ur,exports.transactionContract=ln,exports.vendorContract=mn,exports.walletContract=_n;
1
+ "use strict";var e=require("uuid"),t=require("zod"),r=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var s,a,o=n(t);!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(s||(s={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(a={}));const i=s.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":return Array.isArray(e)?i.array:null===e?i.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?i.promise:"undefined"!=typeof Map&&e instanceof Map?i.map:"undefined"!=typeof Set&&e instanceof Set?i.set:"undefined"!=typeof Date&&e instanceof Date?i.date:i.object;default:return i.unknown}},u=s.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"]);class d extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,s.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}d.create=e=>new d(e);const l=(e,t)=>{let r;switch(e.code){case u.invalid_type:r=e.received===i.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case u.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,s.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:r=`Unrecognized key(s) in object: ${s.joinValues(e.keys,", ")}`;break;case u.invalid_union:r="Invalid input";break;case u.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${s.joinValues(e.options)}`;break;case u.invalid_enum_value:r=`Invalid enum value. Expected ${s.joinValues(e.options)}, received '${e.received}'`;break;case u.invalid_arguments:r="Invalid function arguments";break;case u.invalid_return_type:r="Invalid function return type";break;case u.invalid_date:r="Invalid date";break;case u.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:s.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case u.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case u.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case u.custom:r="Invalid input";break;case u.invalid_intersection_types:r="Intersection results could not be merged";break;case u.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case u.not_finite:r="Number must be finite";break;default:r=t.defaultError,s.assertNever(e)}return{message:r}};let h=l;function m(){return h}const p=e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,a=[...r,...s.path||[]],o={...s,path:a};let i="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)i=e(o,{data:t,defaultError:i}).message;return{...s,path:a,message:s.message||i}};function f(e,t){const r=p({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m(),l].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return g;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t)r.push({key:await e.key,value:await e.value});return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return g;if("aborted"===s.status)return g;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const g=Object.freeze({status:"aborted"}),A=e=>({status:"dirty",value:e}),T=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,E=e=>"dirty"===e.status,_=e=>"valid"===e.status,S=e=>"undefined"!=typeof Promise&&e instanceof Promise;var N;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(N||(N={}));class I{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const C=(e,t)=>{if(_(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new d(e.common.issues);return this._error=t,this._error}}};function b(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=n?n:t.defaultError}:{message:null!=r?r:t.defaultError},description:s}}class O{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)}get description(){return this._def.description}_getType(e){return c(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(S(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},s=this._parseSync({data:e,path:n.path,parent:n});return C(n,s)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(S(n)?n:Promise.resolve(n));return C(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const s=e(t),a=()=>n.addIssue({code:u.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(a(),!1)):!!s||(a(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new ge({schema:this,typeName:we.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Ae.create(this,this._def)}nullable(){return Te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this,this._def)}promise(){return ye.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return ae.create(this,e,this._def)}transform(e){return new ge({...b(this._def),schema:this,typeName:we.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ve({...b(this._def),innerType:this,defaultValue:t,typeName:we.ZodDefault})}brand(){return new Ne({typeName:we.ZodBranded,type:this,...b(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ee({...b(this._def),innerType:this,catchValue:t,typeName:we.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ie.create(this,e)}readonly(){return Ce.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const w=/^c[^\s-]{8,}$/i,x=/^[a-z][a-z0-9]*$/,R=/[0-9A-HJKMNP-TV-Z]{26}/,D=/^[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,P=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,U=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,z=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,M=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):0===e.precision?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function k(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!z.test(e))}class F extends O{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:u.invalid_string,...N.errToObj(r)}),this.nonempty=e=>this.min(1,N.errToObj(e)),this.trim=()=>new F({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new F({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new F({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==i.string){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.string,received:t.parsedType}),g}const t=new y;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const s=e.data.length>n.value,a=e.data.length<n.value;(s||a)&&(r=this._getOrReturnCtx(e,r),s?f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):a&&f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:u.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)L.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:u.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)D.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)w.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:u.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)R.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:u.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(s){r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:u.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:u.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){M(n).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else"ip"===n.kind?k(e.data,n.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:u.invalid_string,message:n.message}),t.dirty()):s.assertNever(n);return{status:t.value,value:e.data}}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,...N.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...N.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errToObj(t)})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Z(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}F.create=e=>{var t;return new F({checks:[],typeName:we.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...b(e)})};class j extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==i.number){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.number,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("int"===n.kind)s.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==Z(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_finite,message:n.message}),r.dirty()):s.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,r,n){return new j({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:N.toString(n)}]})}_addCheck(e){return new j({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&s.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}j.create=e=>new j({checks:[],typeName:we.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...b(e)});class B extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==i.bigint){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.bigint,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):s.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,r,n){return new B({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:N.toString(n)}]})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}B.create=e=>{var t;return new B({checks:[],typeName:we.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...b(e)})};class V extends O{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==i.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.boolean,received:t.parsedType}),g}return T(e.data)}}V.create=e=>new V({typeName:we.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...b(e)});class $ extends O{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==i.date){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.date,received:t.parsedType}),g}if(isNaN(e.data.getTime())){return f(this._getOrReturnCtx(e),{code:u.invalid_date}),g}const t=new y;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):s.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}$.create=e=>new $({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:we.ZodDate,...b(e)});class J extends O{_parse(e){if(this._getType(e)!==i.symbol){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.symbol,received:t.parsedType}),g}return T(e.data)}}J.create=e=>new J({typeName:we.ZodSymbol,...b(e)});class Y extends O{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.undefined,received:t.parsedType}),g}return T(e.data)}}Y.create=e=>new Y({typeName:we.ZodUndefined,...b(e)});class q extends O{_parse(e){if(this._getType(e)!==i.null){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.null,received:t.parsedType}),g}return T(e.data)}}q.create=e=>new q({typeName:we.ZodNull,...b(e)});class W extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}}W.create=e=>new W({typeName:we.ZodAny,...b(e)});class G extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}}G.create=e=>new G({typeName:we.ZodUnknown,...b(e)});class H extends O{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.never,received:t.parsedType}),g}}H.create=e=>new H({typeName:we.ZodNever,...b(e)});class K extends O{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.void,received:t.parsedType}),g}return T(e.data)}}K.create=e=>new K({typeName:we.ZodVoid,...b(e)});class Q extends O{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==i.array)return f(t,{code:u.invalid_type,expected:i.array,received:t.parsedType}),g;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(f(t,{code:e?u.too_big:u.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(f(t,{code:u.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(f(t,{code:u.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new I(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new I(t,e,t.path,r)));return y.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:N.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:N.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:N.toString(t)}})}nonempty(e){return this.min(1,e)}}function X(e){if(e instanceof ee){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ae.create(X(n))}return new ee({...e._def,shape:()=>t})}return e instanceof Q?new Q({...e._def,type:X(e.element)}):e instanceof Ae?Ae.create(X(e.unwrap())):e instanceof Te?Te.create(X(e.unwrap())):e instanceof oe?oe.create(e.items.map(e=>X(e))):e}Q.create=(e,t)=>new Q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:we.ZodArray,...b(t)});class ee extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=s.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==i.object){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.object,received:t.parsedType}),g}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof H&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||a.push(e);const o=[];for(const e of s){const t=n[e],s=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new I(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof H){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(f(r,{code:u.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new I(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new ee({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,a,o;const i=null!==(a=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(o=N.errToObj(e).message)&&void 0!==o?o:i}:{message:i}}}:{}})}strip(){return new ee({...this._def,unknownKeys:"strip"})}passthrough(){return new ee({...this._def,unknownKeys:"passthrough"})}extend(e){return new ee({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ee({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:we.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ee({...this._def,catchall:e})}pick(e){const t={};return s.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}omit(e){const t={};return s.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}deepPartial(){return X(this)}partial(e){const t={};return s.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new ee({...this._def,shape:()=>t})}required(e){const t={};return s.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ae;)e=e._def.innerType;t[r]=e}}),new ee({...this._def,shape:()=>t})}keyof(){return me(s.objectKeys(this.shape))}}ee.create=(e,t)=>new ee({shape:()=>e,unknownKeys:"strip",catchall:H.create(),typeName:we.ZodObject,...b(t)}),ee.strictCreate=(e,t)=>new ee({shape:()=>e,unknownKeys:"strict",catchall:H.create(),typeName:we.ZodObject,...b(t)}),ee.lazycreate=(e,t)=>new ee({shape:e,unknownKeys:"strip",catchall:H.create(),typeName:we.ZodObject,...b(t)});class te extends O{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new d(e.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:r}),g});{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map(e=>new d(e));return f(t,{code:u.invalid_union,unionErrors:s}),g}}get options(){return this._def.options}}te.create=(e,t)=>new te({options:e,typeName:we.ZodUnion,...b(t)});const re=e=>e instanceof le?re(e.schema):e instanceof ge?re(e.innerType()):e instanceof he?[e.value]:e instanceof pe?e.options:e instanceof fe?Object.keys(e.enum):e instanceof ve?re(e._def.innerType):e instanceof Y?[void 0]:e instanceof q?[null]:null;class ne extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return f(t,{code:u.invalid_type,expected:i.object,received:t.parsedType}),g;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=re(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new ne({typeName:we.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...b(r)})}}function se(e,t){const r=c(e),n=c(t);if(e===t)return{valid:!0,data:e};if(r===i.object&&n===i.object){const r=s.objectKeys(t),n=s.objectKeys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=se(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===i.array&&n===i.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const s=se(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===i.date&&n===i.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ae extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return g;const s=se(e.value,n.value);return s.valid?((E(e)||E(n))&&t.dirty(),{status:t.value,value:s.data}):(f(r,{code:u.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ae.create=(e,t,r)=>new ae({left:e,right:t,typeName:we.ZodIntersection,...b(r)});class oe extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return f(r,{code:u.invalid_type,expected:i.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new I(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>y.mergeArray(t,e)):y.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new oe({...this._def,rest:e})}}oe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:e,typeName:we.ZodTuple,rest:null,...b(t)})};class ie extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.object)return f(r,{code:u.invalid_type,expected:i.object,received:r.parsedType}),g;const n=[],s=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new I(r,e,r.path,e)),value:a._parse(new I(r,r.data[e],r.path,e))});return r.common.async?y.mergeObjectAsync(t,n):y.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ie(t instanceof O?{keyType:e,valueType:t,typeName:we.ZodRecord,...b(r)}:{keyType:F.create(),valueType:e,typeName:we.ZodRecord,...b(t)})}}class ce extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.map)return f(r,{code:u.invalid_type,expected:i.map,received:r.parsedType}),g;const n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([e,t],a)=>({key:n._parse(new I(r,e,r.path,[a,"key"])),value:s._parse(new I(r,t,r.path,[a,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return g;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return g;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}ce.create=(e,t,r)=>new ce({valueType:t,keyType:e,typeName:we.ZodMap,...b(r)});class ue extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return f(r,{code:u.invalid_type,expected:i.set,received:r.parsedType}),g;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(f(r,{code:u.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(f(r,{code:u.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return g;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>s._parse(new I(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(e,t){return new ue({...this._def,minSize:{value:e,message:N.toString(t)}})}max(e,t){return new ue({...this._def,maxSize:{value:e,message:N.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ue.create=(e,t)=>new ue({valueType:e,minSize:null,maxSize:null,typeName:we.ZodSet,...b(t)});class de extends O{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.function)return f(t,{code:u.invalid_type,expected:i.function,received:t.parsedType}),g;function r(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_arguments,argumentsError:r}})}function n(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_return_type,returnTypeError:r}})}const s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ye){const e=this;return T(async function(...t){const o=new d([]),i=await e._def.args.parseAsync(t,s).catch(e=>{throw o.addIssue(r(t,e)),o}),c=await Reflect.apply(a,this,i);return await e._def.returns._def.type.parseAsync(c,s).catch(e=>{throw o.addIssue(n(c,e)),o})})}{const e=this;return T(function(...t){const o=e._def.args.safeParse(t,s);if(!o.success)throw new d([r(t,o.error)]);const i=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(i,s);if(!c.success)throw new d([n(i,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new de({...this._def,args:oe.create(e).rest(G.create())})}returns(e){return new de({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new de({args:e||oe.create([]).rest(G.create()),returns:t||G.create(),typeName:we.ZodFunction,...b(r)})}}class le extends O{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}le.create=(e,t)=>new le({getter:e,typeName:we.ZodLazy,...b(t)});class he extends O{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}function me(e,t){return new pe({values:e,typeName:we.ZodEnum,...b(t)})}he.create=(e,t)=>new he({value:e,typeName:we.ZodLiteral,...b(t)});class pe extends O{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:s.joinValues(r),received:t.parsedType,code:u.invalid_type}),g}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:r}),g}return T(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e){return pe.create(e)}exclude(e){return pe.create(this.options.filter(t=>!e.includes(t)))}}pe.create=me;class fe extends O{_parse(e){const t=s.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==i.string&&r.parsedType!==i.number){const e=s.objectValues(t);return f(r,{expected:s.joinValues(e),received:r.parsedType,code:u.invalid_type}),g}if(-1===t.indexOf(e.data)){const e=s.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:e}),g}return T(e.data)}get enum(){return this._def.values}}fe.create=(e,t)=>new fe({values:e,typeName:we.ZodNativeEnum,...b(t)});class ye extends O{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.promise&&!1===t.common.async)return f(t,{code:u.invalid_type,expected:i.promise,received:t.parsedType}),g;const r=t.parsedType===i.promise?t.data:Promise.resolve(t.data);return T(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ye.create=(e,t)=>new ye({type:e,typeName:we.ZodPromise,...b(t)});class ge extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===we.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:e=>{f(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){const e=n.transform(r.data,a);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(e).then(e=>this._def.schema._parseAsync({data:e,path:r.path,parent:r})):this._def.schema._parseSync({data:e,path:r.path,parent:r})}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?g:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?g:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_(e))return e;const s=n.transform(e.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>_(e)?Promise.resolve(n.transform(e.value,a)).then(e=>({status:t.value,value:e})):e)}s.assertNever(n)}}ge.create=(e,t,r)=>new ge({schema:e,typeName:we.ZodEffects,effect:t,...b(r)}),ge.createWithPreprocess=(e,t,r)=>new ge({schema:t,effect:{type:"preprocess",transform:e},typeName:we.ZodEffects,...b(r)});class Ae extends O{_parse(e){return this._getType(e)===i.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:we.ZodOptional,...b(t)});class Te extends O{_parse(e){return this._getType(e)===i.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:we.ZodNullable,...b(t)});class ve extends O{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ve.create=(e,t)=>new ve({innerType:e,typeName:we.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...b(t)});class Ee extends O{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return S(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:we.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...b(t)});class _e extends O{_parse(e){if(this._getType(e)!==i.nan){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:i.nan,received:t.parsedType}),g}return{status:"valid",value:e.data}}}_e.create=e=>new _e({typeName:we.ZodNaN,...b(e)});const Se=Symbol("zod_brand");class Ne extends O{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ie extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),A(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Ie({in:e,out:t,typeName:we.ZodPipeline})}}class Ce extends O{_parse(e){const t=this._def.innerType._parse(e);return _(t)&&(t.value=Object.freeze(t.value)),t}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:we.ZodReadonly,...b(t)});const be=(e,t={},r)=>e?W.create().superRefine((n,s)=>{var a,o;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,i=null===(o=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===o||o,c="string"==typeof e?{message:e}:e;s.addIssue({code:"custom",...c,fatal:i})}}):W.create(),Oe={object:ee.lazycreate};var we;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(we||(we={}));const xe=F.create,Re=j.create,De=_e.create,Pe=B.create,Le=V.create,Ue=$.create,ze=J.create,Me=Y.create,ke=q.create,Fe=W.create,Ze=G.create,je=H.create,Be=K.create,Ve=Q.create,$e=ee.create,Je=ee.strictCreate,Ye=te.create,qe=ne.create,We=ae.create,Ge=oe.create,He=ie.create,Ke=ce.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=pe.create,nt=fe.create,st=ye.create,at=ge.create,ot=Ae.create,it=Te.create,ct=ge.createWithPreprocess,ut=Ie.create,dt={string:e=>F.create({...e,coerce:!0}),number:e=>j.create({...e,coerce:!0}),boolean:e=>V.create({...e,coerce:!0}),bigint:e=>B.create({...e,coerce:!0}),date:e=>$.create({...e,coerce:!0})},lt=g;var ht=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){h=e},getErrorMap:m,makeIssue:p,EMPTY_PATH:[],addIssueToContext:f,ParseStatus:y,INVALID:g,DIRTY:A,OK:T,isAborted:v,isDirty:E,isValid:_,isAsync:S,get util(){return s},get objectUtil(){return a},ZodParsedType:i,getParsedType:c,ZodType:O,ZodString:F,ZodNumber:j,ZodBigInt:B,ZodBoolean:V,ZodDate:$,ZodSymbol:J,ZodUndefined:Y,ZodNull:q,ZodAny:W,ZodUnknown:G,ZodNever:H,ZodVoid:K,ZodArray:Q,ZodObject:ee,ZodUnion:te,ZodDiscriminatedUnion:ne,ZodIntersection:ae,ZodTuple:oe,ZodRecord:ie,ZodMap:ce,ZodSet:ue,ZodFunction:de,ZodLazy:le,ZodLiteral:he,ZodEnum:pe,ZodNativeEnum:fe,ZodPromise:ye,ZodEffects:ge,ZodTransformer:ge,ZodOptional:Ae,ZodNullable:Te,ZodDefault:ve,ZodCatch:Ee,ZodNaN:_e,BRAND:Se,ZodBranded:Ne,ZodPipeline:Ie,ZodReadonly:Ce,custom:be,Schema:O,ZodSchema:O,late:Oe,get ZodFirstPartyTypeKind(){return we},coerce:dt,any:Fe,array:Ve,bigint:Pe,boolean:Le,date:Ue,discriminatedUnion:qe,effect:at,enum:rt,function:Xe,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>be(t=>t instanceof e,t),intersection:We,lazy:et,literal:tt,map:Ke,nan:De,nativeEnum:nt,never:je,null:ke,nullable:it,number:Re,object:$e,oboolean:()=>Le().optional(),onumber:()=>Re().optional(),optional:ot,ostring:()=>xe().optional(),pipeline:ut,preprocess:ct,promise:st,record:He,set:Qe,strictObject:Je,string:xe,symbol:ze,transformer:at,tuple:Ge,undefined:Me,union:Ye,unknown:Ze,void:Be,NEVER:lt,ZodIssueCode:u,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:d});const mt=e=>"function"==typeof(null==e?void 0:e.passthrough),pt=ht.object({name:ht.literal("ZodError"),issues:ht.array(ht.object({path:ht.array(ht.union([ht.string(),ht.number()])),message:ht.string().optional(),code:ht.nativeEnum(ht.ZodIssueCode)}).catchall(ht.any()))});class ft extends Error{constructor(e){super(JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t,2)),this.name="ValidationError",this.issues=e}toString(){return this.message}}ht.object({message:ht.literal("Request validation failed"),pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({paramsResult:pt.nullable(),headersResult:pt.nullable(),queryResult:pt.nullable(),bodyResult:pt.nullable()});const yt="zod-ts-rest-polyfill",gt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof ee&&t instanceof ee){return n=t,mt(r=e)?mt(n)?r.merge(n):r:mt(n)?n:Object.assign({},r,n)}var r,n;return{...e,...t}},At=Symbol("ContractNoBody"),Tt=e=>"method"in e&&"path"in e,vt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,s,a;return Tt(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:gt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(s=r.validateResponseOnClient)&&void 0!==s?s:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,vt(r,t)]})),Et=Symbol("ContractPlainType"),_t=()=>({router:(e,t)=>vt(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Et,body:()=>Et,type:()=>Et,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>At}),St=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",Nt=e=>e?Object.keys(e).flatMap(t=>It(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",It=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>It(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>It(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Ct extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const bt=async({route:e,path:t,method:r,headers:n,body:s,validateResponse:a,fetchOptions:o})=>{const i=await fetch(t,{...o,method:r,headers:n,body:s}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t=e.responses[i.status],r={status:i.status,body:t===At?void 0:await i.json(),headers:i.headers},n=(e=>{if((e=>{if(!e)return!1;const t=null==e?void 0:e["~standard"];return!!t&&1===t.version&&"function"==typeof t.validate})(e))return e;if("function"==typeof(null==(t=e)?void 0:t.safeParse)){const t={vendor:yt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(n&&(null!=a?a:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const n=t["~standard"].validate(e);if(n instanceof Promise)throw new Error("Schema validation must be synchronous");return n.issues?t["~standard"].vendor===yt?{error:new d(n.issues)}:{error:new ft(n.issues)}:r&&"object"==typeof e&&n.value?{value:{...e,...n.value}}:{value:n.value}})(r.body,n);if(e.error)throw e.error;return{...r,body:e.value}}return r}return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},Ot=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},wt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),xt=(e,t,r,n,s)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),o=((e,t=!1)=>{const r=t?St(e):Nt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,s);return t.endsWith("/")&&a.startsWith("/")?`${t}${a.substring(1)}${o}`:`${t}${a}${o}`},Rt=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const s=((e,t,r)=>{const{query:n,params:s,body:a,headers:o,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof s?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,String(t)])):{};return{path:xt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:a,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...o}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:s,query:a,extraInputArgs:o,headers:i,fetchOptions:c}=e,u=r.api||bt,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&wt(d),...wt(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let h={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:s,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:s instanceof FormData?s:Ot(s)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof s?s:new URLSearchParams(s)}:null!=s&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(s)})),u({...h,...o})})(s);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new Ct(a,r)}},Dt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>Tt(r)?[e,Rt(r,t)]:[e,Dt(r,t)]));class Pt extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,e.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return Pt.schema.safeParse(e).success}static unknown(e){return new Pt({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.z.object({message:t.z.string(),statusCode:t.z.number().int(),error:t.z.string().optional(),details:t.z.object({}).optional()})}}const Lt=o.default.object({statusCode:o.default.number().int(),reason:o.default.string().optional(),error:o.default.string().optional(),details:o.default.record(o.default.string(),o.default.unknown()).optional(),message:o.default.string().optional()}),Ut=Lt.extend({statusCode:o.default.literal(400)}),zt=Lt.extend({statusCode:o.default.literal(401)}),Mt=Lt.extend({statusCode:o.default.literal(403)}),kt=Lt.extend({statusCode:o.default.literal(404)}),Ft=Lt.extend({statusCode:o.default.literal(500)}),Zt=o.default.object({page:o.default.number().int().positive(),limit:o.default.number().int().positive(),total:o.default.number().int().min(0),totalPages:o.default.number().int().min(0),hasNext:o.default.boolean(),hasPrev:o.default.boolean()}),jt=o.default.object({balance:o.default.number(),availableBalance:o.default.number(),accountNumber:o.default.string(),accountName:o.default.string()}),Bt=o.default.object({yesterday:o.default.number(),today:o.default.number(),thisMonth:o.default.number(),lastMonth:o.default.number()});const Vt=o.default.string().nullish().transform(e=>{if(!e||""===e.trim())return null;try{return function(e){if(!e||""===e.trim())throw new Error("Date string cannot be empty");const[t,r]=e.trim().split(" ");if(!t||!r)throw new Error("Invalid date format. Expected 'YYYY-MM-DD HH:mm:ss'");const n=new Date(`${t}T${r}.000Z`);return new Date(n.getTime()-108e5).toISOString()}(e)}catch(e){throw new Error(`Failed to convert EAT date to UTC: ${e instanceof Error?e.message:"Unknown error"}`)}}),$t=o.default.object({accountNo:o.default.string().nullish(),debitOrCredit:o.default.enum(["CR","DR"],{error:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:o.default.string().nullish(),cbaRefNo:o.default.string().nullish(),narration:o.default.string().nullish(),txnDate:Vt,valueDate:Vt,amountCredited:o.default.union([o.default.number().min(0,"Credited amount cannot be negative"),o.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid credited amount format");return t})],{error:()=>({message:"Credited amount must be a number or numeric string"})}).nullish(),amountDebited:o.default.union([o.default.number().min(0,"Debited amount cannot be negative"),o.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid debited amount format");return t})],{error:()=>({message:"Debited amount must be a number or numeric string"})}).nullish(),balance:o.default.number({error:e=>void 0===e.input?"Balance is required":"Balance must be a number"})}),Jt={apiError:Lt,validationError:Ut,unauthorizedError:zt,forbiddenError:Mt,notFoundError:kt,serverError:Ft,pagination:Zt,transactionSummary:Bt,walletSummary:jt,statementEntry:$t};class Yt{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){return this.getClientWithHeaders()}getClientWithHeaders(t){const r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",s=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,a={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e.v4()},o={baseUrl:s,baseHeaders:t?{...a,...t}:a};return Dt(this.contract,o)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=Jt.apiError.safeParse(e.body),n=r.success?r.data:void 0,s=(t,r)=>new Pt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw s("Bad request","BAD_REQUEST");if(401===e.status)throw s("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw s("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw s("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw s("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw s("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class qt{accountNo;debitOrCredit;tranRefNo;cbaRefNo;narration;txnDate;valueDate;amountCredited;amountDebited;balance;currency;constructor(e,t="TZS"){let n="TZS";r.CurrencyHelpers.isCode(t)&&(n=t),this.accountNo=e.accountNo,this.debitOrCredit=e.debitOrCredit,this.tranRefNo=e.tranRefNo,this.cbaRefNo=e.cbaRefNo,this.narration=e.narration,this.txnDate=e.txnDate?new Date(e.txnDate):null,this.valueDate=e.valueDate?new Date(e.valueDate):null,this.currency=n;const s=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===s?null:s>0?r.Amount.from(s,n)??r.Amount.from(0,n):null;const a=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===a?null:a>0?r.Amount.from(a,n)??r.Amount.from(0,n):null,this.balance=r.Amount.from(e.balance,n)??r.Amount.from(0,n)}parseAmountValue(e){if("number"==typeof e)return e;if("string"==typeof e&&""!==e.trim()){const t=parseFloat(e);return Number.isNaN(t)?0:t}return 0}isCredit(){return"CR"===this.debitOrCredit}isDebit(){return"DR"===this.debitOrCredit}getTransactionAmount(){return this.amountCredited||this.amountDebited}getTransactionValue(){const e=this.getTransactionAmount();return e?e.numericValue:0}static from(e,t="TZS"){try{return Jt.statementEntry.safeParse(e).success?new qt(e,t):void console.error("Missing required StatementEntry fields:",e)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){const r=[];for(const n of e){const e=qt.from(n,t);if(!e)return;r.push(e)}return r}toJSON(){return{accountNo:this.accountNo,debitOrCredit:this.debitOrCredit,tranRefNo:this.tranRefNo,cbaRefNo:this.cbaRefNo,narration:this.narration,txnDate:this.txnDate?.toISOString(),valueDate:this.valueDate?.toISOString(),amountCredited:this.amountCredited?.toJSON()??null,amountDebited:this.amountDebited?.toJSON()??null,balance:this.balance.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=r.Amount.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let n=0;if(e.amountCredited){const t=r.Amount.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);n=t.numericValue}let s=0;if(e.amountDebited){const t=r.Amount.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);s=t.numericValue}const a={accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,cbaRefNo:e.cbaRefNo,narration:e.narration,txnDate:e.txnDate?e.txnDate:null,valueDate:e.valueDate?e.valueDate:null,amountCredited:n,amountDebited:s,balance:t.numericValue};return new qt(a,e.currency)}catch(e){return void console.error("Error creating StatementEntry from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=qt.fromJSON(r);if(!e)return;t.push(e)}return t}static getTotalCredits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isCredit()&&t.amountCredited?e+t.amountCredited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getTotalDebits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isDebit()&&t.amountDebited?e+t.amountDebited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",n=qt.getTotalCredits(e).numericValue,s=qt.getTotalDebits(e).numericValue;return r.Amount.from(n-s,t)??r.Amount.from(0,t)}}class Wt{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=r.Amount.from(e.yesterday,t)??r.Amount.from(0,t),this.today=r.Amount.from(e.today,t)??r.Amount.from(0,t),this.thisMonth=r.Amount.from(e.thisMonth,t)??r.Amount.from(0,t),this.lastMonth=r.Amount.from(e.lastMonth,t)??r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new Wt(e,t)}toJSON(){return{yesterday:this.yesterday.toJSON(),today:this.today.toJSON(),thisMonth:this.thisMonth.toJSON(),lastMonth:this.lastMonth.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!(r.AmountFactory.getInstance().isAmountJSON(e.yesterday)&&r.AmountFactory.getInstance().isAmountJSON(e.today)&&r.AmountFactory.getInstance().isAmountJSON(e.thisMonth)&&r.AmountFactory.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJSON(e.yesterday),n=r.Amount.fromJSON(e.today),s=r.Amount.fromJSON(e.thisMonth),a=r.Amount.fromJSON(e.lastMonth);if(!(t&&n&&s&&a))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const o={yesterday:t.numericValue,today:n.numericValue,thisMonth:s.numericValue,lastMonth:a.numericValue};return new Wt(o,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class Gt{accountName;accountNo;accountNumber;availableBalance;currentBalance;actualBalance;accountStatus;type;currencyCode;countryCode;currency;constructor(e){let t="TZS";e.currencyCode&&r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.accountName=e.accountName,this.accountNo=e.accountNo,this.accountNumber=e.accountNo,this.currency=t,this.currencyCode=t,this.countryCode=e.countryCode,this.availableBalance=r.Amount.from(e.availableBalance,t)??r.Amount.from(0,t),this.currentBalance=r.Amount.from(e.currentBalance,t)??r.Amount.from(0,t),this.actualBalance=this.currentBalance,this.accountStatus=e.accountStatus,this.type=e.type}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new Gt(e)}toJSON(){return{accountName:this.accountName,accountNo:this.accountNo,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJSON(),currentBalance:this.currentBalance.toJSON(),actualBalance:this.actualBalance.toJSON(),accountStatus:this.accountStatus,type:this.type,currencyCode:this.currencyCode,countryCode:this.countryCode,currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.availableBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=r.Amount.fromJSON(e.availableBalance),n=e.currentBalance??e.actualBalance;if(!r.AmountFactory.getInstance().isAmountJSON(n))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const s=r.Amount.fromJSON(n);if(!t||!s)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const a=e.accountNo||e.accountNumber;if(!a)return void console.error("Missing account number in WalletInfo JSON:",e);const o={accountName:e.accountName,accountNo:a,availableBalance:t.numericValue,currentBalance:s.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new Gt(o)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=Gt.fromJSON(r);if(!e)return;t.push(e)}return t}}var Ht,Kt;exports.FilterOperator=void 0,(Ht=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",Ht.NOT_EQUALS="neq",Ht.LESS_THAN="lt",Ht.LESS_THAN_OR_EQUAL="lte",Ht.GREATER_THAN="gt",Ht.GREATER_THAN_OR_EQUAL="gte",Ht.LIKE="like",Ht.LIKE_LOWER="likeLower",Ht.IS_NULL="isNull",Ht.IS_NOT_NULL="isNotNull",Ht.IN="in",exports.SortDirection=void 0,(Kt=exports.SortDirection||(exports.SortDirection={})).ASC="asc",Kt.DESC="desc";const Qt=Symbol("query-builder-type");class Xt{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[Qt]="query-builder";static is(e){return null!==e&&"object"==typeof e&&Qt in e&&"query-builder"===e[Qt]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new Xt(e)}}var er,tr;exports.NORMALIZED_STATUS=void 0,(er=exports.NORMALIZED_STATUS||(exports.NORMALIZED_STATUS={})).PENDING_ACK="PENDING_ACK",er.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",er.PAYMENT_FAILED="PAYMENT_FAILED",er.PAYMENT_EXPIRED="PAYMENT_EXPIRED",exports.NORMALIZED_STATUS_CODE=void 0,(tr=exports.NORMALIZED_STATUS_CODE||(exports.NORMALIZED_STATUS_CODE={})).AWAITING_USER="AWAITING_USER",tr.PROVIDER_UNCERTAIN="PROVIDER_UNCERTAIN",tr.SUCCESS="SUCCESS",tr.USER_TIMEOUT="USER_TIMEOUT",tr.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",tr.INVALID_NUMBER="INVALID_NUMBER",tr.INVALID_PIN="INVALID_PIN",tr.ACCOUNT_LOCKED="ACCOUNT_LOCKED",tr.ACCOUNT_RESTRICTED="ACCOUNT_RESTRICTED",tr.USER_CANCELLED="USER_CANCELLED",tr.USER_BUSY="USER_BUSY",tr.USER_UNREACHABLE="USER_UNREACHABLE",tr.LIMIT_EXCEEDED="LIMIT_EXCEEDED",tr.INVALID_AMOUNT="INVALID_AMOUNT",tr.PROVIDER_BUSY="PROVIDER_BUSY",tr.PROVIDER_ERROR="PROVIDER_ERROR",tr.UNKNOWN="UNKNOWN";const rr={[exports.NORMALIZED_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.NORMALIZED_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.NORMALIZED_STATUS.PAYMENT_FAILED]:{label:"Payment Failed",description:"The payment did not go through. See the status code for the reason",category:"failed",color:"error",userFriendlyMessage:"Payment failed. Please try again"},[exports.NORMALIZED_STATUS.PAYMENT_EXPIRED]:{label:"Payment Expired",description:"The customer did not respond to the payment prompt in time",category:"failed",color:"error",userFriendlyMessage:"Payment request expired before it was approved"}},nr={[exports.NORMALIZED_STATUS_CODE.AWAITING_USER]:{label:"Awaiting Customer",description:"The prompt was sent and the customer has not responded yet",status:exports.NORMALIZED_STATUS.PENDING_ACK,userFriendlyMessage:"Waiting for the customer to approve the payment"},[exports.NORMALIZED_STATUS_CODE.PROVIDER_UNCERTAIN]:{label:"Outcome Unconfirmed",description:"The outcome is not yet known",status:exports.NORMALIZED_STATUS.PENDING_ACK,userFriendlyMessage:"Payment is being confirmed with the provider"},[exports.NORMALIZED_STATUS_CODE.SUCCESS]:{label:"Success",description:"Payment completed",status:exports.NORMALIZED_STATUS.PAYMENT_ACCEPTED,userFriendlyMessage:"Payment received successfully"},[exports.NORMALIZED_STATUS_CODE.USER_TIMEOUT]:{label:"Customer Timeout",description:"The prompt reached the customer but they did not answer in time",status:exports.NORMALIZED_STATUS.PAYMENT_EXPIRED,userFriendlyMessage:"The customer did not approve the payment in time"},[exports.NORMALIZED_STATUS_CODE.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Not enough money in the customer's wallet",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"Insufficient balance to complete the payment"},[exports.NORMALIZED_STATUS_CODE.INVALID_NUMBER]:{label:"Invalid Number",description:"The phone number is wrong or not registered for mobile money",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The phone number is not registered for mobile money"},[exports.NORMALIZED_STATUS_CODE.INVALID_PIN]:{label:"Invalid PIN",description:"The customer entered a wrong PIN",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer entered a wrong PIN"},[exports.NORMALIZED_STATUS_CODE.ACCOUNT_LOCKED]:{label:"Account Locked",description:"Too many wrong PINs. The customer's wallet is locked",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is locked"},[exports.NORMALIZED_STATUS_CODE.ACCOUNT_RESTRICTED]:{label:"Account Restricted",description:"The wallet is barred, blocked or not activated",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is restricted"},[exports.NORMALIZED_STATUS_CODE.USER_CANCELLED]:{label:"Cancelled by Customer",description:"The customer declined or cancelled the prompt",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer cancelled the payment"},[exports.NORMALIZED_STATUS_CODE.USER_BUSY]:{label:"Customer Busy",description:"The customer has another USSD session open",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone was busy with another session"},[exports.NORMALIZED_STATUS_CODE.USER_UNREACHABLE]:{label:"Customer Unreachable",description:"The prompt could not be delivered (phone off, no network)",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone could not be reached"},[exports.NORMALIZED_STATUS_CODE.LIMIT_EXCEEDED]:{label:"Limit Exceeded",description:"The customer hit a transaction, daily or wallet limit",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The customer's transaction limit was exceeded"},[exports.NORMALIZED_STATUS_CODE.INVALID_AMOUNT]:{label:"Invalid Amount",description:"The amount is below the minimum, above the maximum, or badly formatted",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The payment amount is not allowed"},[exports.NORMALIZED_STATUS_CODE.PROVIDER_BUSY]:{label:"Provider Busy",description:"The mobile money provider is busy",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"The mobile money provider is busy"},[exports.NORMALIZED_STATUS_CODE.PROVIDER_ERROR]:{label:"Provider Error",description:"A system error on TemboPlus's side or the provider's side",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"Payment failed due to a system error"},[exports.NORMALIZED_STATUS_CODE.UNKNOWN]:{label:"Unknown Reason",description:"The payment failed but the reason was not given",status:exports.NORMALIZED_STATUS.PAYMENT_FAILED,userFriendlyMessage:"Payment failed for an unknown reason"}};function sr(e){return Object.values(exports.NORMALIZED_STATUS).find(t=>t===e)}function ar(e){return Object.values(exports.NORMALIZED_STATUS_CODE).find(t=>t===e)}function or(e){if(null!=e&&""!==e)return ar(e)??exports.NORMALIZED_STATUS_CODE.UNKNOWN}function ir(e){return e.status&&e.statusCode?{status:e.status,statusInfo:e.statusInfo,statusCode:e.statusCode,statusCodeInfo:nr[e.statusCode],source:"native"}:e.normalizedStatus?{status:e.normalizedStatus,statusInfo:rr[e.normalizedStatus],statusCode:e.normalizedStatusCode,statusCodeInfo:e.normalizedStatusCode?nr[e.normalizedStatusCode]:void 0,source:"normalized"}:{status:e.status,statusInfo:e.statusInfo,source:"legacy"}}const cr={AIRTEL:{key:"AIRTEL",networkOperator:"Airtel",serviceName:"Airtel Money"},VODACOM:{key:"VODACOM",networkOperator:"Vodacom",serviceName:"M-Pesa"},TIGO:{key:"TIGO",networkOperator:"Yas",serviceName:"Mixx by Yas"},HALOTEL:{key:"HALOTEL",networkOperator:"Halotel",serviceName:"HaloPesa"},SAFARICOM:{key:"SAFARICOM",networkOperator:"Safaricom",serviceName:"M-Pesa"}};var ur;exports.USER_ROLE=void 0,(ur=exports.USER_ROLE||(exports.USER_ROLE={})).READ_ONLY="ReadOnly",ur.ADMIN="Admin",ur.INITIATOR="Initiator",ur.APPROVER="Approver";const dr=t.z.enum(exports.USER_ROLE),lr={user:t.z.object({token:t.z.string(),identity:t.z.string(),name:t.z.string(),role:dr}),userRole:dr,loginRequest:t.z.object({identity:t.z.email(),password:t.z.string()}),updatePassword:t.z.object({currentPassword:t.z.string(),newPassword:t.z.string()})},hr=_t().router({login:{method:"POST",path:"/login",body:lr.loginRequest,responses:{201:lr.user,400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:lr.updatePassword,responses:{201:o.default.object({}),400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Update password",description:"Update user password"}});class mr{identity;name;role;constructor(e){this.identity=e.identity,this.name=e.name,this.role=e.role}static from(e){return new mr(e)}static fromJSON(e){return mr.from(e)}toJSON(){return{identity:this.identity,name:this.name,role:this.role}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}hasRole(e){return this.role===e}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(this.identity)}getInitials(){return this.getDisplayName().split(" ").map(e=>e.charAt(0).toUpperCase()).slice(0,2).join("")}equals(e){return this.identity===e.identity&&this.name===e.name&&this.role===e.role}}var pr,fr;exports.COLLECTION_STATUS=void 0,(pr=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",pr.PENDING_ACK="PENDING_ACK",pr.PAYMENT_FAILED="PAYMENT_FAILED",pr.PAYMENT_EXPIRED="PAYMENT_EXPIRED",pr.GENERIC_FAILURE="GENERIC_FAILURE",pr.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",pr.INVALID_REFERENCE="INVALID_REFERENCE",pr.PAYMENT_REJECTED="PAYMENT_REJECTED",pr.PENDING="PENDING",pr.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_CHANNEL=void 0,(fr=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",fr.TIGO="TZ-TIGO-C2B",fr.HALOTEL="TZ-HALOTEL-C2B",fr.SAFARICOM="KE-SAFARICOM-C2B",fr.VODACOM="TZ-VODACOM-C2B",fr.CRDB="TZ-CRDB",fr.ECOBANK="TZ-ECOBANK";const yr=t.z.enum(exports.COLLECTION_STATUS),gr=t.z.enum(exports.NORMALIZED_STATUS_CODE),Ar=t.z.enum(exports.COLLECTION_CHANNEL),Tr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Tr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},vr=t.z.union([t.z.string(),t.z.array(t.z.string())]),Er={collection:t.z.object({id:t.z.string().min(1),status:yr,statusCode:t.z.unknown().optional().transform(or),normalizedStatus:t.z.unknown().optional().transform(sr),normalizedStatusCode:t.z.unknown().optional().transform(or),statusMessage:t.z.string(),accountNo:t.z.string().min(1),walletId:t.z.string(),transactionDate:t.z.iso.datetime(),narration:t.z.string(),msisdn:t.z.string().min(1),channel:Ar,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),reference:t.z.string(),partnerReference:t.z.string().nullable().optional(),payerName:t.z.string().nullable().optional(),payerReference:t.z.string().nullable().optional(),merchantName:t.z.string().nullable().optional(),merchantReference:t.z.string().nullable().optional(),transactionId:t.z.string().nullable().optional(),serviceFeeTransactionId:t.z.string().nullable().optional(),requestId:t.z.string().nullable().optional(),completedAt:t.z.iso.datetime().nullable().optional(),createdAt:t.z.iso.datetime(),updatedAt:t.z.iso.datetime(),notes:t.z.string().optional(),currencyCode:t.z.string().default("TZS")}),collectionFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.iso.datetime().optional(),endDate:t.z.iso.datetime().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),reference:t.z.string().optional(),referenceIn:t.z.array(t.z.string()).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:Ar.optional(),channelIn:t.z.array(Ar).optional(),status:yr.optional(),statusIn:t.z.array(yr).optional(),statusCode:gr.optional(),statusCodeIn:t.z.array(gr).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),collectionURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:vr.transform(Tr).optional(),reference:t.z.string().optional(),referenceIn:vr.transform(Tr).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:t.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),channelIn:vr.transform(Tr).pipe(t.z.array(Ar)).optional(),status:t.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),statusIn:vr.transform(Tr).pipe(t.z.array(yr)).optional(),statusCode:gr.optional(),statusCodeIn:vr.transform(Tr).pipe(t.z.array(gr)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),paymentStatus:yr,statusCode:gr,paymentChannel:Ar},_r=_t().router({getCollections:{method:"GET",path:"/",query:Er.collectionURLQueryParams,responses:{200:t.z.object({results:t.z.array(Er.collection),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:Er.collection,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),Sr={...rr,[exports.COLLECTION_STATUS.PENDING]:{label:"Pending",description:"The payment is pending",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS]:{label:"Insufficient Funds",description:"The payer has insufficient funds to complete the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.COLLECTION_STATUS.INVALID_REFERENCE]:{label:"Invalid Reference",description:"This collection was not found on the provider's side",category:"failed",color:"error",userFriendlyMessage:"Payment could not be found with the provider"},[exports.COLLECTION_STATUS.PROVIDER_FAILED]:{label:"Provider Failed",description:"An error occurred on the telecom provider's side, and the payment request was not successfully processed",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an issue with the provider"}},Nr={[exports.COLLECTION_CHANNEL.AIRTEL]:cr.AIRTEL,[exports.COLLECTION_CHANNEL.TIGO]:cr.TIGO,[exports.COLLECTION_CHANNEL.HALOTEL]:cr.HALOTEL,[exports.COLLECTION_CHANNEL.VODACOM]:cr.VODACOM,[exports.COLLECTION_CHANNEL.SAFARICOM]:cr.SAFARICOM};function Ir(e){return Object.entries(Sr).filter(([t,r])=>r.category===e).map(([e])=>e)}class Cr{id;status;statusCode;normalizedStatus;normalizedStatusCode;statusMessage;accountNo;walletId;transactionDate;narration;msisdn;channel;amount;serviceFee;postedAmount;reference;partnerReference;payerName;payerReference;merchantName;merchantReference;transactionId;serviceFeeTransactionId;requestId;completedAt;createdAt;updatedAt;notes;currencyCode;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,this.statusCode=or(e.statusCode),this.normalizedStatus=sr(e.normalizedStatus),this.normalizedStatusCode=or(e.normalizedStatusCode),this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.serviceFee=e.serviceFee?r.Amount.from(parseFloat(e.serviceFee),t)??r.Amount.from(0,t):void 0,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t)??r.Amount.from(0,t):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.payerName=e.payerName,this.payerReference=e.payerReference,this.merchantName=e.merchantName,this.merchantReference=e.merchantReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return"pending"===Sr[this.status]?.category}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return"failed"===Sr[this.status]?.category}isExpired(){return this.status===exports.COLLECTION_STATUS.PAYMENT_EXPIRED}isFinal(){return this.isSuccessful()||this.isFailed()}getStatusInfo(){return Sr[this.status]}getStatusCode(){return this.statusCode}getStatusCodeInfo(){return this.statusCode?nr[this.statusCode]:void 0}getDisplayStatus(){return ir({status:this.status,statusInfo:Sr[this.status],statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode})}getChannelInfo(){return Nr[this.channel]}getProviderName(){return this.getChannelInfo()?.networkOperator}getServiceName(){return this.getChannelInfo()?.serviceName}isMobileCollection(){return this.channel in Nr}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Cr(t):void console.error("Missing required Collection fields:",e)}catch(e){return void console.error("Error creating Collection:",e)}}static createMany(e){const t=[];for(const r of e){const e=Cr.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Collection JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,s;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);s=t.numericValue.toString()}const a={id:e.id,status:e.status,statusCode:e.statusCode,normalizedStatus:e.normalizedStatus,normalizedStatusCode:e.normalizedStatusCode,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee:n,postedAmount:s,reference:e.reference,partnerReference:e.partnerReference,payerName:e.payerName,payerReference:e.payerReference,merchantName:e.merchantName,merchantReference:e.merchantReference,transactionId:e.transactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,requestId:e.requestId,completedAt:e.completedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,notes:e.notes,currencyCode:e.currencyCode};return new Cr(a)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=Cr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJSON(),serviceFee:this.serviceFee?.toJSON(),postedAmount:this.postedAmount?.toJSON(),reference:this.reference,partnerReference:this.partnerReference,payerName:this.payerName,payerReference:this.payerReference,merchantName:this.merchantName,merchantReference:this.merchantReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:this.completedAt?.toISOString()??null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}const br=["id","reference","channel","status","statusCode"];class Or extends Xt{static create(){return new Or}static fromFilters(e){return(new Or).applyFilters(e)}static fromUrlParams(e){try{const t=Er.collectionURLQueryParams.parse(Or.normalizeUrlParams(e)),r=Er.collectionFilters.parse(t);return Or.fromFilters(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Or.fromUrlParams(Or.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Or.fromSearchParams(t)}static from(e){try{return null==e?new Or:Xt.is(e)?new Or(e.options):e instanceof URLSearchParams?Or.fromSearchParams(e):Or.isUrlParamsRecord(e)?Or.fromUrlParams(e):Or.fromFilters(e)}catch(e){throw console.log(e),new Error("Invalid input! Could not create a CollectionQuery instance.")}}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of br){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,o=`${e}In[]`,i=t[r],c=Tr([t[n],t[s],t[a],t[o],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[s],delete t[a],delete t[o]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereStatusCode(e){return this.where("statusCode",e)}whereStatusCodeIn(e){return this.whereInValues("statusCode",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}whereIdIn(e){return this.whereInValues("id",e)}whereReferenceIn(e){return this.whereInValues("reference",e)}wherePending(){return this.whereStatusIn(Ir("pending"))}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereStatusIn(Ir("failed"))}whereExpired(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_EXPIRED)}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("reference",e)}wherePartnerReference(e){return this.where("partnerReference",e)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.statusCodeIn?.length?this.whereStatusCodeIn(e.statusCodeIn):e.statusCode&&this.whereStatusCode(e.statusCode),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.referenceIn?.length?this.whereReferenceIn(e.referenceIn):e.reference&&this.whereReference(e.reference),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,id:e.id,idIn:e.idIn,reference:e.reference,referenceIn:e.referenceIn,accountNo:e.accountNo,walletId:e.walletId,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),statusCode:this.isValidStatusCode(e.statusCode)?e.statusCode:void 0,statusCodeIn:this.getValidStatusCodes(e.statusCodeIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.idIn?.length||e.reference||e.referenceIn?.length||e.accountNo||e.walletId||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.statusCode||e.statusCodeIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.statusCodeIn?.length?e.push(`Reason: ${t.statusCodeIn.join(", ")}`):t.statusCode&&e.push(`Reason: ${t.statusCode}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.referenceIn?.length?e.push(`Reference: ${t.referenceIn.join(", ")}`):t.reference&&e.push(`Reference: ${t.reference}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=Tr(t.value);r.length>0&&(e[`${t.field}In`]=r);continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"reference":case"accountNo":case"walletId":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=Tr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Tr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidStatusCodes(e){const t=Tr(e).filter(e=>this.isValidStatusCode(e));return t.length>0?t:void 0}getValidChannels(e){const t=Tr(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).some(t=>t===e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).some(t=>t===e)}isValidStatusCode(e){return Object.values(exports.NORMALIZED_STATUS_CODE).some(t=>t===e)}}var wr,xr;exports.PAYOUT_STATUS=void 0,(wr=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",wr.GENERIC_FAILURE="GENERIC_FAILURE",wr.WALLET_DEBITED="WALLET_DEBITED",wr.PAYMENT_REJECTED="PAYMENT_REJECTED",wr.PENDING="PENDING",wr.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",wr.PENDING_ACK="PENDING_ACK",wr.REVERSED="REVERSED",wr.INVALID_SERVICE="INVALID_SERVICE",wr.INVALID_NUMBER="INVALID_NUMBER",wr.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",wr.THIRDPARTY_FAILED="THIRDPARTY_FAILED",wr.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(xr=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",xr.VODACOM="TZ-VODACOM-B2C",xr.TIGO="TZ-TIGO-B2C",xr.HALOTEL="TZ-HALOTEL-B2C",xr.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const Rr=t.z.enum(exports.PAYOUT_STATUS),Dr=t.z.enum(exports.MOBILE_PAYOUT_CHANNEL),Pr=t.z.enum(exports.BANK_PAYOUT_CHANNEL),Lr=t.z.union([Dr,Pr]),Ur=e=>{const t=Array.isArray(e)?e.flatMap(e=>Ur(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},zr=t.z.union([t.z.string(),t.z.array(t.z.string())]),Mr={payout:t.z.object({id:t.z.string().min(1),statusCode:t.z.string().optional(),statusCodeText:Rr,normalizedStatus:t.z.unknown().optional().transform(sr),normalizedStatusCode:t.z.unknown().optional().transform(or),statusDescription:t.z.string(),countryCode:t.z.string(),serviceCode:Lr,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),walletId:t.z.string().optional(),msisdn:t.z.string().min(1),narration:t.z.string(),currencyCode:t.z.string(),recipientNames:t.z.string().optional(),transactionRef:t.z.string(),transactionDate:t.z.iso.datetime(),externalId:t.z.string().nullable().optional(),cbaReferenceNo:t.z.string().optional(),beepTransactionId:t.z.string().optional(),receiptNumber:t.z.string().optional(),createdAt:t.z.iso.datetime(),reversedTransactionId:t.z.string().nullable().optional(),transactionId:t.z.string(),serviceFeeTransactionId:t.z.string().optional(),isReconciled:t.z.number().optional(),requestId:t.z.string().optional(),notes:t.z.string().optional(),updatedAt:t.z.iso.datetime().optional()}),payoutFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.iso.datetime().optional(),endDate:t.z.iso.datetime().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),ref:t.z.string().optional(),refIn:t.z.array(t.z.string()).optional(),channelRef:t.z.string().optional(),channelRefIn:t.z.array(t.z.string()).optional(),channel:Lr.optional(),channelIn:t.z.array(Lr).optional(),status:Rr.optional(),statusIn:t.z.array(Rr).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),payoutURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:zr.transform(Ur).optional(),ref:t.z.string().optional(),refIn:zr.transform(Ur).optional(),channelRef:t.z.string().optional(),channelRefIn:zr.transform(Ur).optional(),channel:t.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),channelIn:zr.transform(Ur).pipe(t.z.array(Lr)).optional(),status:t.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),statusIn:zr.transform(Ur).pipe(t.z.array(Rr)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),payoutStatus:Rr,payoutChannel:Lr,mobileChannel:Dr,bankChannel:Pr,walletSummary:t.z.object({balance:t.z.number(),currency:t.z.string(),lastUpdated:t.z.iso.datetime()}),transactionSummary:t.z.object({yesterday:t.z.number(),today:t.z.number(),thisMonth:t.z.number(),lastMonth:t.z.number()}),pagination:t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),totalPages:t.z.number(),hasNext:t.z.boolean(),hasPrev:t.z.boolean()})},kr=_t().router({getPayouts:{method:"GET",path:"",query:Mr.payoutURLQueryParams,responses:{200:t.z.object({results:t.z.array(Mr.payout),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:Mr.payout,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),Fr={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.PROVIDER_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"},[exports.PAYOUT_STATUS.INVALID_NUMBER]:{label:"Invalid Number",description:"The number used is either barred or invalid",category:"failed",color:"error",userFriendlyMessage:"Recipient’s number is invalid, inactive, or temporarily blocked."}},Zr={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:cr.AIRTEL,[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:cr.VODACOM,[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:cr.TIGO,[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:cr.HALOTEL,[exports.MOBILE_PAYOUT_CHANNEL.SAFARICOM]:cr.SAFARICOM};function jr(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function Br(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class Vr{id;serviceCode;msisdn;amount;transactionDate;statusDescription;statusCodeText;transactionId;transactionRef;recipientNames;narration;serviceFee;notes;swiftCode;createdAt;updatedAt;statusCode;normalizedStatus;normalizedStatusCode;countryCode;postedAmount;walletId;currencyCode;externalId;cbaReferenceNo;beepTransactionId;receiptNumber;reversedTransactionId;serviceFeeTransactionId;isReconciled;requestId;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.transactionDate=new Date(e.transactionDate),this.statusDescription=e.statusDescription,this.statusCodeText=e.statusCodeText,this.transactionId=e.transactionId,this.transactionRef=e.transactionRef,this.recipientNames=e.recipientNames,this.narration=e.narration,this.serviceFee=void 0===e.serviceFee?void 0:r.Amount.from(e.serviceFee,t)??r.Amount.from(0,t),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=e.updatedAt?new Date(e.updatedAt):void 0,this.statusCode=e.statusCode,this.normalizedStatus=sr(e.normalizedStatus),this.normalizedStatusCode=or(e.normalizedStatusCode),this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t):void 0,this.walletId=e.walletId,this.currencyCode=e.currencyCode,this.externalId=e.externalId,this.cbaReferenceNo=e.cbaReferenceNo,this.beepTransactionId=e.beepTransactionId,this.receiptNumber=e.receiptNumber,this.reversedTransactionId=e.reversedTransactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.isReconciled=e.isReconciled,this.requestId=e.requestId}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Fr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return Fr[this.statusCodeText]}getDisplayStatus(){return ir({status:this.statusCodeText,statusInfo:Fr[this.statusCodeText],statusCode:ar(this.statusCode),normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode})}getChannelInfo(){if(jr(this.serviceCode))return Zr[this.serviceCode];if(Br(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankHelpers.validateSwiftCode(e)){if(r.BankHelpers.getCountryFromSwiftCode(e))try{return r.BankRegistry.getInstance().detectBank(e)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankHelpers.getCountryFromSwiftCode(this.swiftCode)){if(r.BankHelpers.getCountryFromSwiftCode(this.swiftCode))try{return r.BankRegistry.getInstance().detectBank(this.swiftCode)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getAccountNumber(){try{if(jr(this.serviceCode))return this.msisdn;if(Br(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch{console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return jr(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Vr(t):void console.error("Missing required Payout fields:",e)}catch(e){return void console.error("Error creating Payout:",e)}}static createMany(e){const t=[];for(const r of e){const e=Vr.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Payout JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,s;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);s=t.numericValue.toString()}const a={id:e.id,serviceCode:e.serviceCode,msisdn:e.msisdn,amount:t.numericValue,transactionDate:e.transactionDate,statusDescription:e.statusDescription,statusCodeText:e.statusCodeText,transactionId:e.transactionId,transactionRef:e.transactionRef,recipientNames:e.recipientNames,narration:e.narration,serviceFee:n,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,normalizedStatus:e.normalizedStatus,normalizedStatusCode:e.normalizedStatusCode,countryCode:e.countryCode,postedAmount:s,walletId:e.walletId,currencyCode:e.currencyCode,externalId:e.externalId,cbaReferenceNo:e.cbaReferenceNo,beepTransactionId:e.beepTransactionId,receiptNumber:e.receiptNumber,reversedTransactionId:e.reversedTransactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,isReconciled:e.isReconciled,requestId:e.requestId};return new Vr(a)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJSON(e){const t=[];for(const r of e){const e=Vr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJSON(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:this.serviceFee?.toJSON(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt?.toISOString(),statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode,countryCode:this.countryCode,postedAmount:this.postedAmount?.toJSON(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}const $r=["status","channel","id","ref","channelRef"],Jr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class Yr extends Xt{static create(){return new Yr}static fromFilters(e){return(new Yr).applyFilters(e)}static fromUrlParams(e){try{const t=Mr.payoutURLQueryParams.parse(Yr.normalizeUrlParams(e)),r=Mr.payoutFilters.parse(t);return Yr.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Yr.fromUrlParams(Yr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Yr.fromSearchParams(t)}static from(e){return null==e?new Yr:Xt.is(e)?new Yr(e.options):e instanceof URLSearchParams?Yr.fromSearchParams(e):Yr.isUrlParamsRecord(e)?Yr.fromUrlParams(e):Yr.fromFilters(e)}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of $r){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,o=`${e}In[]`,i=t[r],c=Ur([t[n],t[s],t[a],t[o],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[s],delete t[a],delete t[o]}return t}whereStatus(e){return this.where("statusCodeText",e)}whereStatusIn(e){return this.whereInValues("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}whereChannelIn(e){return this.whereInValues("serviceCode",e)}whereIdIn(e){return this.whereInValues("id",e)}whereRefIn(e){return this.whereInValues("transactionRef",e)}whereChannelRef(e){return this.whereContains("channelReference",e)}whereChannelRefIn(e){return this.whereInValues("channelReference",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.refIn?.length?this.whereRefIn(e.refIn):e.ref&&this.whereReference(e.ref),e.channelRefIn?.length?this.whereChannelRefIn(e.channelRefIn):e.channelRef&&this.whereChannelRef(e.channelRef),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,accountNo:e.accountNo,walletId:e.walletId,id:e.id,idIn:e.idIn,ref:e.transactionRef,refIn:e.refIn,channelRef:e.channelReference,channelRefIn:e.channelRefIn,channel:this.isValidChannel(e.serviceCode)?e.serviceCode:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.statusCodeText)?e.statusCodeText:void 0,statusIn:this.getValidStatuses(e.statusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.accountNo||e.walletId||e.id||e.idIn?.length||e.ref||e.refIn?.length||e.channelRef||e.channelRefIn?.length||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Recipient: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.refIn?.length?e.push(`Reference: ${t.refIn.join(", ")}`):t.ref&&e.push(`Reference: ${t.ref}`),t.channelRefIn?.length?e.push(`Channel Ref: ${t.channelRefIn.join(", ")}`):t.channelRef&&e.push(`Channel Ref: ${t.channelRef}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=Ur(t.value);if(0===r.length)continue;e[`${Jr[t.field]??t.field}In`]=r;continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"accountNo":case"walletId":case"transactionRef":case"channelReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=Ur(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Ur(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Ur(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).some(t=>t===e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).some(t=>t===e)}}var qr,Wr,Gr,Hr;exports.SETTLEMENT_STATUS=void 0,(qr=exports.SETTLEMENT_STATUS||(exports.SETTLEMENT_STATUS={})).PENDING="PENDING",qr.APPROVED="APPROVED",qr.PROCESSING="PROCESSING",qr.PROCESSED="PROCESSED",qr.REJECTED="REJECTED",exports.SETTLEMENT_ACTION=void 0,(Wr=exports.SETTLEMENT_ACTION||(exports.SETTLEMENT_ACTION={})).APPROVED="APPROVED",Wr.REJECTED="REJECTED",exports.CREATE_SETTLEMENT_STATUS=void 0,(Gr=exports.CREATE_SETTLEMENT_STATUS||(exports.CREATE_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",Gr.WALLET_NOT_FOUND="WALLET_NOT_FOUND",Gr.INITIATOR_NOT_AUTHORIZED="INITIATOR_NOT_AUTHORIZED",Gr.MISSING_BANK_DETAILS="MISSING_BANK_DETAILS",Gr.UNSUPPORTED_BANK_CODE="UNSUPPORTED_BANK_CODE",Gr.FAILED="FAILED",exports.ACTION_SETTLEMENT_STATUS=void 0,(Hr=exports.ACTION_SETTLEMENT_STATUS||(exports.ACTION_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",Hr.SETTLEMENT_NOT_FOUND="SETTLEMENT_NOT_FOUND",Hr.ACTIONER_NOT_AUTHORIZED="ACTIONER_NOT_AUTHORIZED",Hr.SELF_ACTION_NOT_ALLOWED="SELF_ACTION_NOT_ALLOWED",Hr.INVALID_STATE="INVALID_STATE",Hr.FAILED="FAILED";const Kr=t.z.enum(exports.SETTLEMENT_STATUS),Qr=t.z.enum(exports.SETTLEMENT_ACTION),Xr=t.z.enum(exports.CREATE_SETTLEMENT_STATUS),en=t.z.enum(exports.ACTION_SETTLEMENT_STATUS),tn=t.z.object({id:t.z.string().min(1),date:t.z.string(),initiatedAt:t.z.string().nullish(),initiatedById:t.z.string().nullish(),actionedAt:t.z.string().nullish(),actionedById:t.z.string().nullish(),vendorId:t.z.string(),walletId:t.z.string(),accountNo:t.z.string(),status:Kr,statusCode:t.z.string().nullish(),description:t.z.string(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),amount:t.z.number(),payoutId:t.z.string().nullish(),transactionId:t.z.string().nullish(),createdAt:t.z.string(),updatedAt:t.z.string()}),rn=t.z.object({status:Kr.optional(),amount:t.z.number().optional(),accountNo:t.z.string().optional()}),nn=t.z.object({status:Kr.optional(),amount:t.z.coerce.number().optional(),accountNo:t.z.string().optional()}),sn=t.z.object({accountNo:t.z.string().min(1,"Account number is required"),description:t.z.string().min(1,"Description is required"),amount:t.z.number().refine(e=>0!==e,"Amount must not be 0")}),an=t.z.object({status:Xr,data:tn.optional()}),on=t.z.object({status:Qr}),cn=t.z.object({status:en,data:tn.optional()}),un={settlement:tn,settlementStatus:Kr,settlementAction:Qr,settlementFilters:rn,settlementURLQueryParams:nn,createSettlementRequest:sn,createSettlementStatus:Xr,createSettlementResponse:an,actionSettlementRequest:on,actionSettlementStatus:en,actionSettlementResponse:cn},dn=_t().router({getSettlements:{method:"GET",path:"",query:un.settlementFilters,responses:{200:t.z.array(un.settlement),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List settlements",description:"Retrieve settlements belonging to your vendor, with optional filtering and sorting via query params"},getSettlement:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:un.settlement,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get settlement details",description:"Retrieve detailed information about a specific settlement"},createSettlement:{method:"POST",path:"",body:un.createSettlementRequest,responses:{201:un.createSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Create settlement",description:"Create a new settlement request initiated by the authenticated user. Expected failures (e.g. WALLET_NOT_FOUND) are reported via the body `status` field, not HTTP errors"},actionSettlement:{method:"POST",path:"/:id/action",pathParams:t.z.object({id:t.z.string()}),body:un.actionSettlementRequest,responses:{201:un.actionSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Action settlement",description:"Approve or reject a PENDING settlement as the authenticated user. Expected failures (e.g. INVALID_STATE) are reported via the body `status` field, not HTTP errors"}}),ln={[exports.SETTLEMENT_STATUS.PENDING]:{label:"Pending",description:"Pending approval or rejection",category:"pending",color:"warning",userFriendlyMessage:"Settlement is awaiting approval"},[exports.SETTLEMENT_STATUS.APPROVED]:{label:"Approved",description:"Approved by an admin or approver",category:"success",color:"success",userFriendlyMessage:"Settlement was approved"},[exports.SETTLEMENT_STATUS.PROCESSING]:{label:"Processing",description:"Approved and being processed to the settlement bank account",category:"processing",color:"info",userFriendlyMessage:"Settlement is being processed to your bank account"},[exports.SETTLEMENT_STATUS.PROCESSED]:{label:"Processed",description:"Approved and processed successfully",category:"success",color:"success",userFriendlyMessage:"Settlement was processed successfully"},[exports.SETTLEMENT_STATUS.REJECTED]:{label:"Rejected",description:"Rejected by an admin or approver",category:"failed",color:"error",userFriendlyMessage:"Settlement was rejected"}};function hn(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}class mn{id;date;initiatedAt;initiatedById;actionedAt;actionedById;vendorId;walletId;accountNo;status;statusCode;description;bankAccountNo;bankAccountName;bankCode;amount;payoutId;transactionId;createdAt;updatedAt;_originalData;constructor(e){this._originalData={...e},this.id=e.id,this.date=new Date(e.date),this.initiatedAt=hn(e.initiatedAt),this.initiatedById=e.initiatedById,this.actionedAt=hn(e.actionedAt),this.actionedById=e.actionedById,this.vendorId=e.vendorId,this.walletId=e.walletId,this.accountNo=e.accountNo,this.status=e.status,this.statusCode=e.statusCode,this.description=e.description,this.bankAccountNo=e.bankAccountNo,this.bankAccountName=e.bankAccountName,this.bankCode=e.bankCode,this.amount=r.Amount.from(e.amount,"TZS")??r.Amount.from(0,"TZS"),this.payoutId=e.payoutId,this.transactionId=e.transactionId,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}isPending(){return this.status===exports.SETTLEMENT_STATUS.PENDING}isApproved(){return this.status===exports.SETTLEMENT_STATUS.APPROVED}isProcessing(){return this.status===exports.SETTLEMENT_STATUS.PROCESSING}isProcessed(){return this.status===exports.SETTLEMENT_STATUS.PROCESSED}isRejected(){return this.status===exports.SETTLEMENT_STATUS.REJECTED}canBeActioned(){return this.isPending()}getStatusInfo(){return ln[this.status]}static from(e){try{const t=e;return t?.id&&t?.accountNo&&void 0!==t?.amount?new mn(t):void console.error("Missing required Settlement fields:",e)}catch(e){return void console.error("Error creating Settlement:",e)}}static createMany(e){const t=[];for(const r of e){const e=mn.from(r);e&&t.push(e)}return t}static fromJSON(e){return mn.from(e)}toJSON(){return{...this._originalData}}}class pn{filters;constructor(e={}){this.filters={...e}}static create(){return new pn}static fromFilters(e){return new pn(un.settlementFilters.parse(e))}static fromUrlParams(e){try{const t=pn.flattenParams(e),r=un.settlementURLQueryParams.parse(t);return new pn(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return pn.fromUrlParams(pn.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return pn.fromSearchParams(t)}static from(e){try{return null==e?new pn:pn.is(e)?e.clone():e instanceof URLSearchParams?pn.fromSearchParams(e):pn.isUrlParamsRecord(e)?pn.fromUrlParams(e):pn.fromFilters(e)}catch(e){throw console.log(e),new Error("Invalid input! Could not create a SettlementQuery instance.")}}static is(e){return e instanceof pn}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static flattenParams(e){const t=["status","amount","accountNo"],r={};for(const n of t){const t=e[n],s=(Array.isArray(t)?t[0]:t)?.trim();s&&(r[n]=s)}return r}whereStatus(e){return this.filters.status=e,this}whereAmount(e){return this.filters.amount=e,this}whereAccountNo(e){return this.filters.accountNo=e,this}wherePending(){return this.whereStatus(exports.SETTLEMENT_STATUS.PENDING)}whereApproved(){return this.whereStatus(exports.SETTLEMENT_STATUS.APPROVED)}whereProcessing(){return this.whereStatus(exports.SETTLEMENT_STATUS.PROCESSING)}whereProcessed(){return this.whereStatus(exports.SETTLEMENT_STATUS.PROCESSED)}whereRejected(){return this.whereStatus(exports.SETTLEMENT_STATUS.REJECTED)}clone(){return new pn(this.filters)}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withAmount(e){const t=this.clone();return void 0!==e&&t.whereAmount(e),t}withAccountNo(e){const t=this.clone();return e&&t.whereAccountNo(e),t}toFilters(){const e={};return void 0!==this.filters.status&&(e.status=this.filters.status),void 0!==this.filters.amount&&(e.amount=this.filters.amount),void 0!==this.filters.accountNo&&(e.accountNo=this.filters.accountNo),e}build(){return this.toFilters()}toUrlParams(){const e=this.toFilters(),t={};for(const[r,n]of Object.entries(e))null!=n&&(t[r]=String(n));return t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}hasFilters(){const e=this.toFilters();return void 0!==e.status||void 0!==e.amount||void 0!==e.accountNo}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),void 0!==t.amount&&e.push(`Amount: ${t.amount}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),e}}const fn={localTransferRequest:t.z.object({amount:t.z.number().int().positive(),from:t.z.string().min(1),to:t.z.string().min(1),description:t.z.string().min(1)}),localTransferResponse:t.z.object({transactionId:t.z.string(),from:t.z.string(),to:t.z.string(),transactionDate:t.z.string(),narration:t.z.string(),amount:t.z.number(),transactionRef:t.z.string()})},yn=_t().router({localTransfer:{method:"POST",path:"/local-transfer",body:fn.localTransferRequest,responses:{201:fn.localTransferResponse,400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});const gn={vendor:t.z.object({businessName:t.z.string(),tradeName:t.z.string(),enableCollections:t.z.number(),enablePayouts:t.z.number(),enableRemittance:t.z.number(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),enableAutoSettlement:t.z.number(),disablePaymentApproval:t.z.number()})},An=_t().router({getMe:{method:"GET",path:"/me",responses:{200:gn.vendor,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get vendor profile",description:"Retrieve the vendor profile of the authenticated user, including feature flags and bank details"}});class Tn{businessName;tradeName;canCollect;canPayout;canRemit;automatedSettlements;disabledPaymentApproval;settlementAccount;constructor(e){this.businessName=e.businessName,this.tradeName=e.tradeName,this.canCollect=e.canCollect,this.canPayout=e.canPayout,this.canRemit=e.canRemit,this.automatedSettlements=e.automatedSettlements,this.disabledPaymentApproval=e.disabledPaymentApproval,this.settlementAccount=e.settlementAccount}hasSettlementAccount(){return null!==this.settlementAccount}getDisplayName(){return this.tradeName||this.businessName}static from(e){try{const t=e;if(!t?.businessName)return void console.error("Missing required Vendor fields:",e);const n=t,s=n.bankCode?r.Bank.fromBIC(n.bankCode):void 0,a=s&&n.bankAccountName&&n.bankAccountNo?{accountName:n.bankAccountName,accountNo:n.bankAccountNo,bank:s}:null;return new Tn({businessName:n.businessName,tradeName:n.tradeName,canCollect:1===n.enableCollections,canPayout:1===n.enablePayouts,canRemit:1===n.enableRemittance,automatedSettlements:1===n.enableAutoSettlement,disabledPaymentApproval:1===n.disablePaymentApproval,settlementAccount:a})}catch(e){return void console.error("Error creating Vendor:",e)}}static fromJSON(e){let t=null;if(e.settlementAccount){const n=r.Bank.fromJSON(e.settlementAccount.bank);n&&(t={accountName:e.settlementAccount.accountName,accountNo:e.settlementAccount.accountNo,bank:n})}return new Tn({...e,settlementAccount:t})}toJSON(){return{businessName:this.businessName,tradeName:this.tradeName,canCollect:this.canCollect,canPayout:this.canPayout,canRemit:this.canRemit,automatedSettlements:this.automatedSettlements,disabledPaymentApproval:this.disabledPaymentApproval,settlementAccount:this.settlementAccount?{accountName:this.settlementAccount.accountName,accountNo:this.settlementAccount.accountNo,bank:this.settlementAccount.bank.toJSON()}:null}}}var vn;function En(e){switch(e){case"DEFAULT COLLECTION":case exports.WALLET_TYPE.COLLECTION:return exports.WALLET_TYPE.COLLECTION;case"Vendor":case"DEFAULT DISBURSEMENT":case exports.WALLET_TYPE.DISBURSEMENT:return exports.WALLET_TYPE.DISBURSEMENT;default:throw new TypeError(`Unsupported wallet type: ${String(e)}`)}}exports.WALLET_TYPE=void 0,(vn=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).COLLECTION="COLLECTION",vn.DISBURSEMENT="DISBURSEMENT";const _n=t.z.enum(exports.WALLET_TYPE),Sn=t.z.enum(["Vendor","DEFAULT DISBURSEMENT","DEFAULT COLLECTION","COLLECTION","DISBURSEMENT"]).transform(En),Nn=t.z.object({id:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1),shadowAccountNo:t.z.string().nullish(),externalId:t.z.string().nullish(),reference:t.z.string().nullish(),type:Sn,vendorId:t.z.string().nullish(),balance:t.z.number(),minBalance:t.z.union([t.z.number(),t.z.string()]),approvalLimit:t.z.union([t.z.number(),t.z.string()]),currency:t.z.string().min(1),countryCode:t.z.string().min(1),createdAt:t.z.string().min(1),updatedAt:t.z.string().min(1)}),In=t.z.object({availableBalance:t.z.number(),currentBalance:t.z.number(),accountStatus:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1)}),Cn={wallet:Nn,walletType:_n,walletPathParams:t.z.object({accountNo:t.z.string().min(1)}),walletBalance:In,walletStatementQuery:t.z.object({startDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},bn=_t().router({listWallets:{method:"GET",path:"",responses:{200:t.z.array(Cn.wallet),401:Jt.unauthorizedError,500:Jt.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:t.z.object({accountNo:t.z.string().min(1)}),responses:{200:Cn.wallet,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Get wallet info",description:"Retrieve wallet metadata including balance, currency, and type for a specific wallet."},getWalletBalance:{method:"GET",path:"/:accountNo/balance",pathParams:Cn.walletPathParams,responses:{200:Cn.walletBalance,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet balance",description:"Retrieve the current and available balance for a specific wallet account number."},getWalletStatement:{method:"GET",path:"/:accountNo/statement",pathParams:Cn.walletPathParams,query:Cn.walletStatementQuery,responses:{200:t.z.array(Jt.statementEntry),400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class On{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){const t=En(e.type);this._originalData={...e,type:t};let n="TZS";r.CurrencyHelpers.isCode(e.currency)?n=e.currency:"KSH"===e.currency&&(n="KES"),this.id=e.id,this.accountNo=e.accountNo,this.accountName=e.accountName,this.shadowAccountNo=e.shadowAccountNo,this.externalId=e.externalId,this.reference=e.reference,this.type=t,this.vendorId=e.vendorId,this.balance=r.Amount.from(e.balance,n)??r.Amount.from(0,n),this.minBalance=r.Amount.from(this.parseAmountValue(e.minBalance),n)??r.Amount.from(0,n),this.approvalLimit=r.Amount.from(this.parseAmountValue(e.approvalLimit),n)??r.Amount.from(0,n),this.currency=n,this.countryCode=e.countryCode,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}parseAmountValue(e){if("number"==typeof e)return e;const t=parseFloat(e);return Number.isNaN(t)?0:t}isCollectionWallet(){return this.type===exports.WALLET_TYPE.COLLECTION}isDisbursementWallet(){return this.type===exports.WALLET_TYPE.DISBURSEMENT}isDefaultWallet(){return!1}static from(e){return new On(e)}static createMany(e){const t=[];for(const r of e)try{t.push(On.from(r))}catch(e){console.warn("Skipping unsupported wallet:",e)}return t}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.minBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=r.Amount.fromJSON(e.balance),n=r.Amount.fromJSON(e.minBalance),s=r.Amount.fromJSON(e.approvalLimit);return t&&n&&s?new On({id:e.id,accountNo:e.accountNo,accountName:e.accountName,shadowAccountNo:e.shadowAccountNo,externalId:e.externalId,reference:e.reference,type:e.type,vendorId:e.vendorId,balance:t.numericValue,minBalance:n.numericValue,approvalLimit:s.numericValue,currency:e.currency,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt}):void console.error("Failed to reconstruct balance Amount from JSON:",e)}catch(e){return void console.error("Error creating Wallet from JSON:",e)}}}exports.APIError=Pt,exports.AuthDTOSchemas=lr,exports.AuthRepository=class extends Yt{constructor(e){super("auth",hr,e)}async login(e){const t=o.default.object({email:o.default.email().trim().toLowerCase(),password:o.default.string().min(1)}).safeParse(e);if(!t.success)throw new Pt({message:"Invalid email or password",statusCode:400});const{email:r,password:n}=t.data,s=await this.client.login({body:{identity:r,password:n}});if(400===s.status||401===s.status)throw new Pt({message:"Invalid email or password",statusCode:s.status});const{token:a,...i}=this.handleResponse(s,201);if(!a)throw new Pt({message:"Authentication token missing from server response",statusCode:500});const c=mr.from(i);if(!c)throw new Pt({message:"Invalid user data received from server",statusCode:500});return{user:c,token:a}}async updatePassword(e){const t=await this.client.updatePassword({body:e});if(201!==t.status){if(400===t.status)throw new Error("Validation error");if(401===t.status)throw new Error("Unauthorized");throw new Error("Failed to update password")}return!0}},exports.BaseRepository=Yt,exports.COLLECTION_STATUS_CODE=exports.NORMALIZED_STATUS_CODE,exports.COLLECTION_STATUS_CODE_INFO=nr,exports.COLLECTION_STATUS_INFO=Sr,exports.Collection=Cr,exports.CollectionDTOSchemas=Er,exports.CollectionQuery=Or,exports.CollectionRepository=class extends Yt{constructor(e){super("collection",_r,e)}async getCollections(e){try{const t=Or.from(e),r=t.build(),n=await this.client.getCollections({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),o={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},i=Cr.createMany(s.results);if(!i)throw new Error("Invalid collection data received from server");return{collections:i,pagination:o}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=Or.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=Cr.from(r);if(!n)throw new Error("Invalid collection data received from server");return n}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=Wt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.CommonSchemas=Jt,exports.MobileChannels=cr,exports.NORMALIZED_STATUS_CODE_INFO=nr,exports.NORMALIZED_STATUS_INFO=rr,exports.PAYOUT_STATUS_INFO=Fr,exports.Payout=Vr,exports.PayoutDTOSchemas=Mr,exports.PayoutQuery=Yr,exports.PayoutRepository=class extends Yt{constructor(e){super("payout",kr,e)}async getPayouts(e){try{const t=Yr.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),o={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},i=Vr.createMany(s.results);if(!i)throw new Error("Invalid payout data received from server");return{payouts:i,pagination:o}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Yr.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Vr.from(r);if(!n)throw new Error("Invalid payout data received from server");return n}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=Wt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.QUERY_BUILDER_TYPE=Qt,exports.QueryBuilder=Xt,exports.SETTLEMENT_STATUS_INFO=ln,exports.Settlement=mn,exports.SettlementDTOSchemas=un,exports.SettlementQuery=pn,exports.SettlementRepository=class extends Yt{constructor(e){super("settlement",dn,e)}async getSettlements(e){const t=pn.from(e),r=await this.client.getSettlements({query:t.build()}),n=this.handleResponse(r,200);return mn.createMany(n)}async getSettlementsFromRequest(e){return this.getSettlements(pn.fromRequest(e))}async getSettlement(e){const t=await this.client.getSettlement({params:{id:e}}),r=this.handleResponse(t,200),n=mn.from(r);if(!n)throw new Error("Invalid settlement data received from server");return n}async createSettlement(e){const t=await this.client.createSettlement({body:e}),r=this.handleResponse(t,201);return{status:r.status,settlement:r.data?mn.from(r.data):void 0}}async actionSettlement(e,t){const r=await this.client.actionSettlement({params:{id:e},body:{status:t}}),n=this.handleResponse(r,201);return{status:n.status,settlement:n.data?mn.from(n.data):void 0}}async approveSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.APPROVED)}async rejectSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.REJECTED)}},exports.StatementEntry=qt,exports.TransactionDTOSchemas=fn,exports.TransactionRepository=class extends Yt{constructor(e){super("transaction",yn,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=Wt,exports.User=mr,exports.Vendor=Tn,exports.VendorDTOSchemas=gn,exports.VendorRepository=class extends Yt{constructor(e){super("vendor",An,e)}async getMe(){const e=await this.client.getMe(),t=this.handleResponse(e,200),r=Tn.from(t);if(!r)throw new Error("Invalid vendor data received from server");return r}},exports.Wallet=On,exports.WalletDTOSchemas=Cn,exports.WalletInfo=Gt,exports.WalletRepository=class extends Yt{constructor(e){super("wallet",bn,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=On.createMany(t);if(!r)throw new Error("Invalid wallet data received from server");return r}async getWalletInfo(e){const t=await this.client.getWalletInfo({params:{accountNo:e}}),r=this.handleResponse(t,200);return On.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return Gt.from(r)}async getWalletStatement(e){const t=await this.client.getWalletStatement({params:{accountNo:e.accountNo},query:{startDate:this.formatStatementDate(e.startDate),endDate:this.formatStatementDate(e.endDate)}}),r=this.handleResponse(t,200),n=qt.createMany(r);if(!n)throw new Error("Invalid statement entry data received from server");return n}formatStatementDate(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Error("Invalid statement date provided.");return e.toISOString().slice(0,10)}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;const t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error(`Invalid statement date: ${e}`);return t.toISOString().slice(0,10)}},exports.asNormalizedStatus=sr,exports.asNormalizedStatusCode=ar,exports.authContract=hr,exports.collectionContract=_r,exports.collectionToStringArray=Tr,exports.getCollectionStatusesByCategory=Ir,exports.normalizeWalletType=En,exports.payoutContract=kr,exports.payoutToStringArray=Ur,exports.resolveDisplayStatus=ir,exports.settlementContract=dn,exports.statementEntrySchema=$t,exports.toCollectionStatusCode=or,exports.toNormalizedStatusCode=or,exports.transactionContract=yn,exports.vendorContract=An,exports.walletContract=bn;
2
2
  //# sourceMappingURL=index.cjs.js.map