@temboplus/tembo-dashboard 0.2.9 → 0.3.0-rc.2
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 +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/modules/auth/auth.api-contract.d.ts +2 -1
- package/dist/modules/auth/auth.api-contract.d.ts.map +1 -1
- package/dist/modules/auth/auth.dtos.d.ts +12 -1
- package/dist/modules/auth/auth.dtos.d.ts.map +1 -1
- package/dist/modules/auth/user.model.d.ts +10 -2
- package/dist/modules/auth/user.model.d.ts.map +1 -1
- package/dist/modules/collection/collection.api-contract.d.ts +8 -8
- package/dist/modules/collection/collection.types.d.ts +6 -6
- package/dist/modules/payout/payout.api-contract.d.ts +6 -6
- package/dist/modules/payout/payout.types.d.ts +6 -6
- package/dist/modules/settlement/index.d.ts +5 -0
- package/dist/modules/settlement/index.d.ts.map +1 -0
- package/dist/modules/settlement/settlement.api-contract.d.ts +255 -0
- package/dist/modules/settlement/settlement.api-contract.d.ts.map +1 -0
- package/dist/modules/settlement/settlement.model.d.ts +106 -0
- package/dist/modules/settlement/settlement.model.d.ts.map +1 -0
- package/dist/modules/settlement/settlement.repository.d.ts +75 -0
- package/dist/modules/settlement/settlement.repository.d.ts.map +1 -0
- package/dist/modules/settlement/settlement.types.d.ts +140 -0
- package/dist/modules/settlement/settlement.types.d.ts.map +1 -0
- package/dist/modules/vendor/index.d.ts +5 -0
- package/dist/modules/vendor/index.d.ts.map +1 -0
- package/dist/modules/vendor/vendor.api-contract.d.ts +45 -0
- package/dist/modules/vendor/vendor.api-contract.d.ts.map +1 -0
- package/dist/modules/vendor/vendor.model.d.ts +76 -0
- package/dist/modules/vendor/vendor.model.d.ts.map +1 -0
- package/dist/modules/vendor/vendor.repository.d.ts +17 -0
- package/dist/modules/vendor/vendor.repository.d.ts.map +1 -0
- package/dist/modules/vendor/vendor.types.d.ts +17 -0
- package/dist/modules/vendor/vendor.types.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.api-contract.d.ts +14 -2
- package/dist/modules/wallet/wallet.api-contract.d.ts.map +1 -1
- package/dist/modules/wallet/wallet.model.d.ts +14 -10
- package/dist/modules/wallet/wallet.model.d.ts.map +1 -1
- package/dist/modules/wallet/wallet.types.d.ts +9 -4
- package/dist/modules/wallet/wallet.types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{v4 as e}from"uuid";import t,{z as r}from"zod";import{CurrencyHelpers as n,Amount as a,AmountFactory as s,BankHelpers as i,BankRegistry as o,Bank as c}from"@temboplus/frontend-core";var u,d;!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}(u||(u={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(d||(d={}));const l=u.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),h=e=>{switch(typeof e){case"undefined":return l.undefined;case"string":return l.string;case"number":return isNaN(e)?l.nan:l.number;case"boolean":return l.boolean;case"function":return l.function;case"bigint":return l.bigint;case"symbol":return l.symbol;case"object":return Array.isArray(e)?l.array:null===e?l.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?l.promise:"undefined"!=typeof Map&&e instanceof Map?l.map:"undefined"!=typeof Set&&e instanceof Set?l.set:"undefined"!=typeof Date&&e instanceof Date?l.date:l.object;default:return l.unknown}},m=u.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 p 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 a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,n=0;for(;n<a.path.length;){const r=a.path[n];n===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,u.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()}}p.create=e=>new p(e);const f=(e,t)=>{let r;switch(e.code){case m.invalid_type:r=e.received===l.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,u.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:r=`Unrecognized key(s) in object: ${u.joinValues(e.keys,", ")}`;break;case m.invalid_union:r="Invalid input";break;case m.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${u.joinValues(e.options)}`;break;case m.invalid_enum_value:r=`Invalid enum value. Expected ${u.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:r="Invalid function arguments";break;case m.invalid_return_type:r="Invalid function return type";break;case m.invalid_date:r="Invalid date";break;case m.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}"`:u.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case m.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 m.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 m.custom:r="Invalid input";break;case m.invalid_intersection_types:r="Intersection results could not be merged";break;case m.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:r="Number must be finite";break;default:r=t.defaultError,u.assertNever(e)}return{message:r}};let y=f;function g(){return y}const v=e=>{const{data:t,path:r,errorMaps:n,issueData:a}=e,s=[...r,...a.path||[]],i={...a,path:s};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...a,path:s,message:a.message||o}};function _(e,t){const r=v({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,g(),f].filter(e=>!!e)});e.common.issues.push(r)}class b{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 w;"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 b.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:a}=n;if("aborted"===t.status)return w;if("aborted"===a.status)return w;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"===t.value||void 0===a.value&&!n.alwaysSet||(r[t.value]=a.value)}return{status:e.value,value:r}}}const w=Object.freeze({status:"aborted"}),I=e=>({status:"dirty",value:e}),N=e=>({status:"valid",value:e}),A=e=>"aborted"===e.status,E=e=>"dirty"===e.status,C=e=>"valid"===e.status,S=e=>"undefined"!=typeof Promise&&e instanceof Promise;var T;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(T||(T={}));class O{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 R=(e,t)=>{if(C(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 p(e.common.issues);return this._error=t,this._error}}};function x(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=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:a};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:a}}class D{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 h(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:h(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new b,ctx:{common:e.parent.common,data:e.data,parsedType:h(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:h(e)},a=this._parseSync({data:e,path:n.path,parent:n});return R(n,a)}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:h(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(S(n)?n:Promise.resolve(n));return R(r,a)}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 a=e(t),s=()=>n.addIssue({code:m.custom,...r(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(e=>!!e||(s(),!1)):!!a||(s(),!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 we({schema:this,typeName:ke.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Ie.create(this,this._def)}nullable(){return Ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this,this._def)}promise(){return be.create(this,this._def)}or(e){return se.create([this,e],this._def)}and(e){return ue.create(this,e,this._def)}transform(e){return new we({...x(this._def),schema:this,typeName:ke.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...x(this._def),innerType:this,defaultValue:t,typeName:ke.ZodDefault})}brand(){return new Te({typeName:ke.ZodBranded,type:this,...x(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ee({...x(this._def),innerType:this,catchValue:t,typeName:ke.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Oe.create(this,e)}readonly(){return Re.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const k=/^c[^\s-]{8,}$/i,P=/^[a-z][a-z0-9]*$/,F=/[0-9A-HJKMNP-TV-Z]{26}/,j=/^[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,L=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,M=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,Z=/^(((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}))$/,B=/^(([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})))$/,$=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 U(e,t){return!("v4"!==t&&t||!Z.test(e))||!("v6"!==t&&t||!B.test(e))}class V extends D{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:m.invalid_string,...T.errToObj(r)}),this.nonempty=e=>this.min(1,T.errToObj(e)),this.trim=()=>new V({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new V({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new V({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==l.string){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.string,received:t.parsedType}),w}const t=new b;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),_(r,{code:m.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),_(r,{code:m.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const a=e.data.length>n.value,s=e.data.length<n.value;(a||s)&&(r=this._getOrReturnCtx(e,r),a?_(r,{code:m.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):s&&_(r,{code:m.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)L.test(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{validation:"email",code:m.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)M.test(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{validation:"emoji",code:m.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)j.test(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{validation:"uuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)k.test(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{validation:"cuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{validation:"cuid2",code:m.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)F.test(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{validation:"ulid",code:m.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(a){r=this._getOrReturnCtx(e,r),_(r,{validation:"url",code:m.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),_(r,{validation:"regex",code:m.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),_(r,{code:m.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),_(r,{code:m.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),_(r,{code:m.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){$(n).test(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{code:m.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else"ip"===n.kind?U(e.data,n.version)||(r=this._getOrReturnCtx(e,r),_(r,{validation:"ip",code:m.invalid_string,message:n.message}),t.dirty()):u.assertNever(n);return{status:t.value,value:e.data}}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...T.errToObj(e)})}url(e){return this._addCheck({kind:"url",...T.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...T.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...T.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...T.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...T.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...T.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,...T.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...T.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...T.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...T.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...T.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...T.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...T.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...T.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,a=r>n?r:n;return parseInt(e.toFixed(a).replace(".",""))%parseInt(t.toFixed(a).replace(".",""))/Math.pow(10,a)}V.create=e=>{var t;return new V({checks:[],typeName:ke.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class q extends D{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)!==l.number){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.number,received:t.parsedType}),w}let t;const r=new b;for(const n of this._def.checks)if("int"===n.kind)u.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),_(t,{code:m.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),_(t,{code:m.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),_(t,{code:m.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),_(t,{code:m.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),_(t,{code:m.not_finite,message:n.message}),r.dirty()):u.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,T.toString(t))}gt(e,t){return this.setLimit("min",e,!1,T.toString(t))}lte(e,t){return this.setLimit("max",e,!0,T.toString(t))}lt(e,t){return this.setLimit("max",e,!1,T.toString(t))}setLimit(e,t,r,n){return new q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:T.toString(n)}]})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:T.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:T.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.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&&u.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)}}q.create=e=>new q({checks:[],typeName:ke.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class W extends D{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)!==l.bigint){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.bigint,received:t.parsedType}),w}let t;const r=new b;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),_(t,{code:m.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),_(t,{code:m.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),_(t,{code:m.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):u.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,T.toString(t))}gt(e,t){return this.setLimit("min",e,!1,T.toString(t))}lte(e,t){return this.setLimit("max",e,!0,T.toString(t))}lt(e,t){return this.setLimit("max",e,!1,T.toString(t))}setLimit(e,t,r,n){return new W({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:T.toString(n)}]})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:T.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}}W.create=e=>{var t;return new W({checks:[],typeName:ke.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class G extends D{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==l.boolean){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.boolean,received:t.parsedType}),w}return N(e.data)}}G.create=e=>new G({typeName:ke.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class z extends D{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==l.date){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.date,received:t.parsedType}),w}if(isNaN(e.data.getTime())){return _(this._getOrReturnCtx(e),{code:m.invalid_date}),w}const t=new b;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),_(r,{code:m.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),_(r,{code:m.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):u.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:T.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:T.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}}z.create=e=>new z({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ke.ZodDate,...x(e)});class K extends D{_parse(e){if(this._getType(e)!==l.symbol){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.symbol,received:t.parsedType}),w}return N(e.data)}}K.create=e=>new K({typeName:ke.ZodSymbol,...x(e)});class H extends D{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.undefined,received:t.parsedType}),w}return N(e.data)}}H.create=e=>new H({typeName:ke.ZodUndefined,...x(e)});class Y extends D{_parse(e){if(this._getType(e)!==l.null){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.null,received:t.parsedType}),w}return N(e.data)}}Y.create=e=>new Y({typeName:ke.ZodNull,...x(e)});class Q extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return N(e.data)}}Q.create=e=>new Q({typeName:ke.ZodAny,...x(e)});class X extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return N(e.data)}}X.create=e=>new X({typeName:ke.ZodUnknown,...x(e)});class ee extends D{_parse(e){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.never,received:t.parsedType}),w}}ee.create=e=>new ee({typeName:ke.ZodNever,...x(e)});class te extends D{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.void,received:t.parsedType}),w}return N(e.data)}}te.create=e=>new te({typeName:ke.ZodVoid,...x(e)});class re extends D{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==l.array)return _(t,{code:m.invalid_type,expected:l.array,received:t.parsedType}),w;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(e||a)&&(_(t,{code:e?m.too_big:m.too_small,minimum:a?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&&(_(t,{code:m.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&&(_(t,{code:m.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 O(t,e,t.path,r)))).then(e=>b.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new O(t,e,t.path,r)));return b.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new re({...this._def,minLength:{value:e,message:T.toString(t)}})}max(e,t){return new re({...this._def,maxLength:{value:e,message:T.toString(t)}})}length(e,t){return new re({...this._def,exactLength:{value:e,message:T.toString(t)}})}nonempty(e){return this.min(1,e)}}function ne(e){if(e instanceof ae){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ie.create(ne(n))}return new ae({...e._def,shape:()=>t})}return e instanceof re?new re({...e._def,type:ne(e.element)}):e instanceof Ie?Ie.create(ne(e.unwrap())):e instanceof Ne?Ne.create(ne(e.unwrap())):e instanceof de?de.create(e.items.map(e=>ne(e))):e}re.create=(e,t)=>new re({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ke.ZodArray,...x(t)});class ae extends D{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=u.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==l.object){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),w}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof ee&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||s.push(e);const i=[];for(const e of a){const t=n[e],a=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new O(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ee){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(_(r,{code:m.unrecognized_keys,keys:s}),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 s){const n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new O(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>b.mergeObjectSync(t,e)):b.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return T.errToObj,new ae({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,a,s,i;const o=null!==(s=null===(a=(n=this._def).errorMap)||void 0===a?void 0:a.call(n,t,r).message)&&void 0!==s?s:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=T.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new ae({...this._def,unknownKeys:"strip"})}passthrough(){return new ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ke.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ae({...this._def,catchall:e})}pick(e){const t={};return u.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ae({...this._def,shape:()=>t})}omit(e){const t={};return u.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ae({...this._def,shape:()=>t})}deepPartial(){return ne(this)}partial(e){const t={};return u.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new ae({...this._def,shape:()=>t})}required(e){const t={};return u.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ie;)e=e._def.innerType;t[r]=e}}),new ae({...this._def,shape:()=>t})}keyof(){return ge(u.objectKeys(this.shape))}}ae.create=(e,t)=>new ae({shape:()=>e,unknownKeys:"strip",catchall:ee.create(),typeName:ke.ZodObject,...x(t)}),ae.strictCreate=(e,t)=>new ae({shape:()=>e,unknownKeys:"strict",catchall:ee.create(),typeName:ke.ZodObject,...x(t)}),ae.lazycreate=(e,t)=>new ae({shape:e,unknownKeys:"strip",catchall:ee.create(),typeName:ke.ZodObject,...x(t)});class se extends D{_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 p(e.ctx.common.issues));return _(t,{code:m.invalid_union,unionErrors:r}),w});{let e;const n=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,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 a=n.map(e=>new p(e));return _(t,{code:m.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}}se.create=(e,t)=>new se({options:e,typeName:ke.ZodUnion,...x(t)});const ie=e=>e instanceof fe?ie(e.schema):e instanceof we?ie(e.innerType()):e instanceof ye?[e.value]:e instanceof ve?e.options:e instanceof _e?Object.keys(e.enum):e instanceof Ae?ie(e._def.innerType):e instanceof H?[void 0]:e instanceof Y?[null]:null;class oe extends D{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.object)return _(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),w;const r=this.discriminator,n=t.data[r],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(_(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),w)}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=ie(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of t){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,r)}}return new oe({typeName:ke.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...x(r)})}}function ce(e,t){const r=h(e),n=h(t);if(e===t)return{valid:!0,data:e};if(r===l.object&&n===l.object){const r=u.objectKeys(t),n=u.objectKeys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=ce(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===l.array&&n===l.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const a=ce(e[n],t[n]);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}return r===l.date&&n===l.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ue extends D{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(A(e)||A(n))return w;const a=ce(e.value,n.value);return a.valid?((E(e)||E(n))&&t.dirty(),{status:t.value,value:a.data}):(_(r,{code:m.invalid_intersection_types}),w)};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}))}}ue.create=(e,t,r)=>new ue({left:e,right:t,typeName:ke.ZodIntersection,...x(r)});class de extends D{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.array)return _(r,{code:m.invalid_type,expected:l.array,received:r.parsedType}),w;if(r.data.length<this._def.items.length)return _(r,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:m.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 O(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>b.mergeArray(t,e)):b.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new de({...this._def,rest:e})}}de.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new de({items:e,typeName:ke.ZodTuple,rest:null,...x(t)})};class le extends D{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!==l.object)return _(r,{code:m.invalid_type,expected:l.object,received:r.parsedType}),w;const n=[],a=this._def.keyType,s=this._def.valueType;for(const e in r.data)n.push({key:a._parse(new O(r,e,r.path,e)),value:s._parse(new O(r,r.data[e],r.path,e))});return r.common.async?b.mergeObjectAsync(t,n):b.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new le(t instanceof D?{keyType:e,valueType:t,typeName:ke.ZodRecord,...x(r)}:{keyType:V.create(),valueType:e,typeName:ke.ZodRecord,...x(t)})}}class he extends D{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!==l.map)return _(r,{code:m.invalid_type,expected:l.map,received:r.parsedType}),w;const n=this._def.keyType,a=this._def.valueType,s=[...r.data.entries()].map(([e,t],s)=>({key:n._parse(new O(r,e,r.path,[s,"key"])),value:a._parse(new O(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const n=await r.key,a=await r.value;if("aborted"===n.status||"aborted"===a.status)return w;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const n=r.key,a=r.value;if("aborted"===n.status||"aborted"===a.status)return w;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}}}}he.create=(e,t,r)=>new he({valueType:t,keyType:e,typeName:ke.ZodMap,...x(r)});class me extends D{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.set)return _(r,{code:m.invalid_type,expected:l.set,received:r.parsedType}),w;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(_(r,{code:m.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&&(_(r,{code:m.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function s(e){const r=new Set;for(const n of e){if("aborted"===n.status)return w;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>a._parse(new O(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>s(e)):s(i)}min(e,t){return new me({...this._def,minSize:{value:e,message:T.toString(t)}})}max(e,t){return new me({...this._def,maxSize:{value:e,message:T.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}me.create=(e,t)=>new me({valueType:e,minSize:null,maxSize:null,typeName:ke.ZodSet,...x(t)});class pe extends D{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.function)return _(t,{code:m.invalid_type,expected:l.function,received:t.parsedType}),w;function r(e,r){return v({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g(),f].filter(e=>!!e),issueData:{code:m.invalid_arguments,argumentsError:r}})}function n(e,r){return v({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g(),f].filter(e=>!!e),issueData:{code:m.invalid_return_type,returnTypeError:r}})}const a={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof be){const e=this;return N(async function(...t){const i=new p([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(s,this,o);return await e._def.returns._def.type.parseAsync(c,a).catch(e=>{throw i.addIssue(n(c,e)),i})})}{const e=this;return N(function(...t){const i=e._def.args.safeParse(t,a);if(!i.success)throw new p([r(t,i.error)]);const o=Reflect.apply(s,this,i.data),c=e._def.returns.safeParse(o,a);if(!c.success)throw new p([n(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new pe({...this._def,args:de.create(e).rest(X.create())})}returns(e){return new pe({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new pe({args:e||de.create([]).rest(X.create()),returns:t||X.create(),typeName:ke.ZodFunction,...x(r)})}}class fe extends D{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})}}fe.create=(e,t)=>new fe({getter:e,typeName:ke.ZodLazy,...x(t)});class ye extends D{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return _(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ge(e,t){return new ve({values:e,typeName:ke.ZodEnum,...x(t)})}ye.create=(e,t)=>new ye({value:e,typeName:ke.ZodLiteral,...x(t)});class ve extends D{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return _(t,{expected:u.joinValues(r),received:t.parsedType,code:m.invalid_type}),w}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return _(t,{received:t.data,code:m.invalid_enum_value,options:r}),w}return N(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 ve.create(e)}exclude(e){return ve.create(this.options.filter(t=>!e.includes(t)))}}ve.create=ge;class _e extends D{_parse(e){const t=u.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==l.string&&r.parsedType!==l.number){const e=u.objectValues(t);return _(r,{expected:u.joinValues(e),received:r.parsedType,code:m.invalid_type}),w}if(-1===t.indexOf(e.data)){const e=u.objectValues(t);return _(r,{received:r.data,code:m.invalid_enum_value,options:e}),w}return N(e.data)}get enum(){return this._def.values}}_e.create=(e,t)=>new _e({values:e,typeName:ke.ZodNativeEnum,...x(t)});class be extends D{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.promise&&!1===t.common.async)return _(t,{code:m.invalid_type,expected:l.promise,received:t.parsedType}),w;const r=t.parsedType===l.promise?t.data:Promise.resolve(t.data);return N(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}be.create=(e,t)=>new be({type:e,typeName:ke.ZodPromise,...x(t)});class we extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ke.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=>{_(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?w:("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?w:("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(!C(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=>C(e)?Promise.resolve(n.transform(e.value,a)).then(e=>({status:t.value,value:e})):e)}u.assertNever(n)}}we.create=(e,t,r)=>new we({schema:e,typeName:ke.ZodEffects,effect:t,...x(r)}),we.createWithPreprocess=(e,t,r)=>new we({schema:t,effect:{type:"preprocess",transform:e},typeName:ke.ZodEffects,...x(r)});class Ie extends D{_parse(e){return this._getType(e)===l.undefined?N(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:ke.ZodOptional,...x(t)});class Ne extends D{_parse(e){return this._getType(e)===l.null?N(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:ke.ZodNullable,...x(t)});class Ae extends D{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===l.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:ke.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...x(t)});class Ee extends D{_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 p(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new p(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:ke.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...x(t)});class Ce extends D{_parse(e){if(this._getType(e)!==l.nan){const t=this._getOrReturnCtx(e);return _(t,{code:m.invalid_type,expected:l.nan,received:t.parsedType}),w}return{status:"valid",value:e.data}}}Ce.create=e=>new Ce({typeName:ke.ZodNaN,...x(e)});const Se=Symbol("zod_brand");class Te extends D{_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 Oe extends D{_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?w:"dirty"===e.status?(t.dirty(),I(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?w:"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 Oe({in:e,out:t,typeName:ke.ZodPipeline})}}class Re extends D{_parse(e){const t=this._def.innerType._parse(e);return C(t)&&(t.value=Object.freeze(t.value)),t}}Re.create=(e,t)=>new Re({innerType:e,typeName:ke.ZodReadonly,...x(t)});const xe=(e,t={},r)=>e?Q.create().superRefine((n,a)=>{var s,i;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(i=null!==(s=e.fatal)&&void 0!==s?s:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;a.addIssue({code:"custom",...c,fatal:o})}}):Q.create(),De={object:ae.lazycreate};var ke;!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"}(ke||(ke={}));const Pe=V.create,Fe=q.create,je=Ce.create,Le=W.create,Me=G.create,Ze=z.create,Be=K.create,$e=H.create,Ue=Y.create,Ve=Q.create,Je=X.create,qe=ee.create,We=te.create,Ge=re.create,ze=ae.create,Ke=ae.strictCreate,He=se.create,Ye=oe.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=me.create,nt=pe.create,at=fe.create,st=ye.create,it=ve.create,ot=_e.create,ct=be.create,ut=we.create,dt=Ie.create,lt=Ne.create,ht=we.createWithPreprocess,mt=Oe.create,pt={string:e=>V.create({...e,coerce:!0}),number:e=>q.create({...e,coerce:!0}),boolean:e=>G.create({...e,coerce:!0}),bigint:e=>W.create({...e,coerce:!0}),date:e=>z.create({...e,coerce:!0})},ft=w;var yt=Object.freeze({__proto__:null,defaultErrorMap:f,setErrorMap:function(e){y=e},getErrorMap:g,makeIssue:v,EMPTY_PATH:[],addIssueToContext:_,ParseStatus:b,INVALID:w,DIRTY:I,OK:N,isAborted:A,isDirty:E,isValid:C,isAsync:S,get util(){return u},get objectUtil(){return d},ZodParsedType:l,getParsedType:h,ZodType:D,ZodString:V,ZodNumber:q,ZodBigInt:W,ZodBoolean:G,ZodDate:z,ZodSymbol:K,ZodUndefined:H,ZodNull:Y,ZodAny:Q,ZodUnknown:X,ZodNever:ee,ZodVoid:te,ZodArray:re,ZodObject:ae,ZodUnion:se,ZodDiscriminatedUnion:oe,ZodIntersection:ue,ZodTuple:de,ZodRecord:le,ZodMap:he,ZodSet:me,ZodFunction:pe,ZodLazy:fe,ZodLiteral:ye,ZodEnum:ve,ZodNativeEnum:_e,ZodPromise:be,ZodEffects:we,ZodTransformer:we,ZodOptional:Ie,ZodNullable:Ne,ZodDefault:Ae,ZodCatch:Ee,ZodNaN:Ce,BRAND:Se,ZodBranded:Te,ZodPipeline:Oe,ZodReadonly:Re,custom:xe,Schema:D,ZodSchema:D,late:De,get ZodFirstPartyTypeKind(){return ke},coerce:pt,any:Ve,array:Ge,bigint:Le,boolean:Me,date:Ze,discriminatedUnion:Ye,effect:ut,enum:it,function:nt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>xe(t=>t instanceof e,t),intersection:Qe,lazy:at,literal:st,map:tt,nan:je,nativeEnum:ot,never:qe,null:Ue,nullable:lt,number:Fe,object:ze,oboolean:()=>Me().optional(),onumber:()=>Fe().optional(),optional:dt,ostring:()=>Pe().optional(),pipeline:mt,preprocess:ht,promise:ct,record:et,set:rt,strictObject:Ke,string:Pe,symbol:Be,transformer:ut,tuple:Xe,undefined:$e,union:He,unknown:Je,void:We,NEVER:ft,ZodIssueCode:m,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:p});const gt=e=>"function"==typeof(null==e?void 0:e.passthrough),vt=yt.object({name:yt.literal("ZodError"),issues:yt.array(yt.object({path:yt.array(yt.union([yt.string(),yt.number()])),message:yt.string().optional(),code:yt.nativeEnum(yt.ZodIssueCode)}).catchall(yt.any()))});class _t 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}}yt.object({message:yt.literal("Request validation failed"),pathParameterErrors:vt.nullable(),headerErrors:vt.nullable(),queryParameterErrors:vt.nullable(),bodyErrors:vt.nullable()}),yt.object({pathParameterErrors:vt.nullable(),headerErrors:vt.nullable(),queryParameterErrors:vt.nullable(),bodyErrors:vt.nullable()}),yt.object({paramsResult:vt.nullable(),headersResult:vt.nullable(),queryResult:vt.nullable(),bodyResult:vt.nullable()});const bt="zod-ts-rest-polyfill",wt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof ae&&t instanceof ae){return n=t,gt(r=e)?gt(n)?r.merge(n):r:gt(n)?n:Object.assign({},r,n)}var r,n;return{...e,...t}},It=Symbol("ContractNoBody"),Nt=e=>"method"in e&&"path"in e,At=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s;return Nt(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:wt(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!==(a=r.validateResponseOnClient)&&void 0!==a?a: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!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,At(r,t)]})),Et=Symbol("ContractPlainType"),Ct=()=>({router:(e,t)=>At(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:()=>It}),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("&"):"",Tt=e=>e?Object.keys(e).flatMap(t=>Ot(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",Ot=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>Ot(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>Ot(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Rt extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const xt=async({route:e,path:t,method:r,headers:n,body:a,validateResponse:s,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:n,body:a}),c=o.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t=e.responses[o.status],r={status:o.status,body:t===It?void 0:await o.json(),headers:o.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:bt,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!=s?s: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===bt?{error:new p(n.issues)}:{error:new _t(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:o.status,body:await o.text(),headers:o.headers}:{status:o.status,body:await o.blob(),headers:o.headers}},Dt=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},kt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Pt=(e,t,r,n,a)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?St(e):Tt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return t.endsWith("/")&&s.startsWith("/")?`${t}${s.substring(1)}${i}`:`${t}${s}${i}`},Ft=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:s,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof a?Object.fromEntries(Object.entries(a).map(([e,t])=>[e,String(t)])):{};return{path:Pt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:s,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...o,...i}}})(e,t,n),s=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:s,extraInputArgs:i,headers:o,fetchOptions:c}=e,u=r.api||xt,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&kt(d),...kt(o)};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:a,rawQuery:s,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:a instanceof FormData?a:Dt(a)}:"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 a?a:new URLSearchParams(a)}:null!=a&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(a)})),u({...h,...i})})(a);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new Rt(s,r)}},jt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>Nt(r)?[e,Ft(r,t)]:[e,jt(r,t)]));class Lt 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 Lt.schema.safeParse(e).success}static unknown(e){return new Lt({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return r.object({message:r.string(),statusCode:r.number().int(),error:r.string().optional(),details:r.object({}).optional()})}}const Mt=t.object({statusCode:t.number().int(),reason:t.string().optional(),error:t.string().optional(),details:t.record(t.string(),t.unknown()).optional(),message:t.string().optional()}),Zt=Mt.extend({statusCode:t.literal(400)}),Bt=Mt.extend({statusCode:t.literal(401)}),$t=Mt.extend({statusCode:t.literal(403)}),Ut=Mt.extend({statusCode:t.literal(404)}),Vt=Mt.extend({statusCode:t.literal(500)}),Jt=t.object({page:t.number().int().positive(),limit:t.number().int().positive(),total:t.number().int().min(0),totalPages:t.number().int().min(0),hasNext:t.boolean(),hasPrev:t.boolean()}),qt=t.object({balance:t.number(),availableBalance:t.number(),accountNumber:t.string(),accountName:t.string()}),Wt=t.object({yesterday:t.number(),today:t.number(),thisMonth:t.number(),lastMonth:t.number()});const Gt=t.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"}`)}}),zt=t.object({accountNo:t.string().nullish(),debitOrCredit:t.enum(["CR","DR"],{error:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:t.string().nullish(),cbaRefNo:t.string().nullish(),narration:t.string().nullish(),txnDate:Gt,valueDate:Gt,amountCredited:t.union([t.number().min(0,"Credited amount cannot be negative"),t.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:t.union([t.number().min(0,"Debited amount cannot be negative"),t.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:t.number({error:e=>void 0===e.input?"Balance is required":"Balance must be a number"})}),Kt={apiError:Mt,validationError:Zt,unauthorizedError:Bt,forbiddenError:$t,notFoundError:Ut,serverError:Vt,pagination:Jt,transactionSummary:Wt,walletSummary:qt,statementEntry:zt};class Ht{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(/^\/+/,""):"",a=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,s={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e()},i={baseUrl:a,baseHeaders:t?{...s,...t}:s};return jt(this.contract,i)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=Kt.apiError.safeParse(e.body),n=r.success?r.data:void 0,a=(t,r)=>new Lt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw a("Bad request","BAD_REQUEST");if(401===e.status)throw a("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw a("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw a("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw a("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw a("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class Yt{accountNo;debitOrCredit;tranRefNo;cbaRefNo;narration;txnDate;valueDate;amountCredited;amountDebited;balance;currency;constructor(e,t="TZS"){let r="TZS";n.isCode(t)&&(r=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=r;const s=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===s?null:s>0?a.from(s,r)??a.from(0,r):null;const i=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===i?null:i>0?a.from(i,r)??a.from(0,r):null,this.balance=a.from(e.balance,r)??a.from(0,r)}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 Kt.statementEntry.safeParse(e).success?new Yt(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=Yt.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(!s.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!s.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!s.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=a.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let r=0;if(e.amountCredited){const t=a.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);r=t.numericValue}let n=0;if(e.amountDebited){const t=a.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);n=t.numericValue}const i={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:r,amountDebited:n,balance:t.numericValue};return new Yt(i,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=Yt.fromJSON(r);if(!e)return;t.push(e)}return t}static getTotalCredits(e){const t=e.length>0?e[0].currency:"TZS",r=e.reduce((e,t)=>t.isCredit()&&t.amountCredited?e+t.amountCredited.numericValue:e,0);return a.from(r,t)??a.from(0,t)}static getTotalDebits(e){const t=e.length>0?e[0].currency:"TZS",r=e.reduce((e,t)=>t.isDebit()&&t.amountDebited?e+t.amountDebited.numericValue:e,0);return a.from(r,t)??a.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",r=Yt.getTotalCredits(e).numericValue,n=Yt.getTotalDebits(e).numericValue;return a.from(r-n,t)??a.from(0,t)}}class Qt{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=a.from(e.yesterday,t)??a.from(0,t),this.today=a.from(e.today,t)??a.from(0,t),this.thisMonth=a.from(e.thisMonth,t)??a.from(0,t),this.lastMonth=a.from(e.lastMonth,t)??a.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 a.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new Qt(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(!(s.getInstance().isAmountJSON(e.yesterday)&&s.getInstance().isAmountJSON(e.today)&&s.getInstance().isAmountJSON(e.thisMonth)&&s.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=a.fromJSON(e.yesterday),r=a.fromJSON(e.today),n=a.fromJSON(e.thisMonth),i=a.fromJSON(e.lastMonth);if(!(t&&r&&n&&i))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const o={yesterday:t.numericValue,today:r.numericValue,thisMonth:n.numericValue,lastMonth:i.numericValue};return new Qt(o,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class Xt{accountName;accountNo;accountNumber;availableBalance;currentBalance;actualBalance;accountStatus;type;currencyCode;countryCode;currency;constructor(e){let t="TZS";e.currencyCode&&n.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=a.from(e.availableBalance,t)??a.from(0,t),this.currentBalance=a.from(e.currentBalance,t)??a.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 Xt(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(!s.getInstance().isAmountJSON(e.availableBalance)||!s.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=a.fromJSON(e.availableBalance),r=e.currentBalance??e.actualBalance;if(!s.getInstance().isAmountJSON(r))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const n=a.fromJSON(r);if(!t||!n)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const i=e.accountNo||e.accountNumber;if(!i)return void console.error("Missing account number in WalletInfo JSON:",e);const o={accountName:e.accountName,accountNo:i,availableBalance:t.numericValue,currentBalance:n.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new Xt(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=Xt.fromJSON(r);if(!e)return;t.push(e)}return t}}var er,tr;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(er||(er={})),function(e){e.ASC="asc",e.DESC="desc"}(tr||(tr={}));const rr=Symbol("query-builder-type");class nr{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}}[rr]="query-builder";static is(e){return null!==e&&"object"==typeof e&&rr in e&&"query-builder"===e[rr]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:er.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:er.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:er.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:er.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:er.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:er.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:er.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:er.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:er.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:er.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=tr.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,tr.ASC)}orderByDesc(e){return this.orderBy(e,tr.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 er.IS_NULL:e[`${t.field}:isNull`]=1;break;case er.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case er.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case er.LIKE:e[`${t.field}:like`]=t.value;break;case er.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case er.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case er.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===tr.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 nr(e)}}const ar={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"}},sr={user:r.object({token:r.string(),identity:r.string(),name:r.string()}),loginRequest:r.object({identity:r.string().email(),password:r.string()}),updatePassword:r.object({currentPassword:r.string(),newPassword:r.string()})},ir=Ct().router({login:{method:"POST",path:"/login",body:sr.loginRequest,responses:{201:sr.user,400:Kt.validationError,401:Kt.unauthorizedError,500:Kt.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:sr.updatePassword,responses:{201:t.object({}),400:Kt.validationError,401:Kt.unauthorizedError,500:Kt.serverError},summary:"Update password",description:"Update user password"}});class or{identity;name;constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new or(e)}static fromJson(e){return or.from(e)}toJson(){return{identity:this.identity,name:this.name}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}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}}class cr extends Ht{constructor(e){super("auth",ir,e)}async login(e){const t={identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),a=or.from(n);if(!a)throw new Error("Invalid user data received from server");return{user:a,token:n.token}}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}}var ur,dr;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING_ACK="PENDING_ACK",e.PROVIDER_FAILED="PROVIDER_FAILED"}(ur||(ur={})),function(e){e.AIRTEL="TZ-AIRTEL-C2B",e.TIGO="TZ-TIGO-C2B",e.HALOTEL="TZ-HALOTEL-C2B",e.SAFARICOM="KE-SAFARICOM-C2B",e.VODACOM="TZ-VODACOM-C2B"}(dr||(dr={}));const lr=r.nativeEnum(ur),hr=r.nativeEnum(dr),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=r.union([r.string(),r.array(r.string())]),fr={collection:r.object({id:r.string().min(1),status:lr,statusMessage:r.string(),accountNo:r.string().min(1),walletId:r.string(),transactionDate:r.string().datetime(),narration:r.string(),msisdn:r.string().min(1),channel:hr,amount:r.number().min(0),serviceFee:r.string().optional(),postedAmount:r.string().optional(),reference:r.string(),partnerReference:r.string().nullable().optional(),payerName:r.string().nullable().optional(),payerReference:r.string().nullable().optional(),merchantName:r.string().nullable().optional(),merchantReference:r.string().nullable().optional(),transactionId:r.string().nullable().optional(),serviceFeeTransactionId:r.string().nullable().optional(),requestId:r.string().nullable().optional(),completedAt:r.string().datetime().nullable().optional(),createdAt:r.string().datetime(),updatedAt:r.string().datetime(),notes:r.string().optional(),currencyCode:r.string().default("TZS")}),collectionFilters:r.object({page:r.number().int().positive().default(1),limit:r.number().int().positive().max(5e4).default(20),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().datetime().optional(),endDate:r.string().datetime().optional(),msisdn:r.string().optional(),id:r.string().optional(),idIn:r.array(r.string()).optional(),reference:r.string().optional(),referenceIn:r.array(r.string()).optional(),accountNo:r.string().optional(),walletId:r.string().optional(),partnerReference:r.string().optional(),channel:hr.optional(),channelIn:r.array(hr).optional(),status:lr.optional(),statusIn:r.array(lr).optional(),minAmount:r.number().min(0).optional(),maxAmount:r.number().min(0).optional(),search:r.string().optional()}),collectionURLQueryParams:r.object({page:r.string().transform(e=>parseInt(e)||1).optional(),limit:r.string().transform(e=>parseInt(e)||20).optional(),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().optional(),endDate:r.string().optional(),msisdn:r.string().optional(),id:r.string().optional(),idIn:pr.transform(mr).optional(),reference:r.string().optional(),referenceIn:pr.transform(mr).optional(),accountNo:r.string().optional(),walletId:r.string().optional(),partnerReference:r.string().optional(),channel:r.string().refine(e=>Object.values(dr).includes(e)).transform(e=>e).optional(),channelIn:pr.transform(mr).pipe(r.array(hr)).optional(),status:r.string().refine(e=>Object.values(ur).includes(e)).transform(e=>e).optional(),statusIn:pr.transform(mr).pipe(r.array(lr)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),paymentStatus:lr,paymentChannel:hr},yr=Ct().router({getCollections:{method:"GET",path:"/",query:fr.collectionURLQueryParams,responses:{200:r.object({results:r.array(fr.collection),total:r.number()}),401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:r.object({id:r.string()}),responses:{200:fr.collection,401:Kt.unauthorizedError,403:Kt.forbiddenError,404:Kt.notFoundError,500:Kt.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:Kt.transactionSummary,401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),gr={[ur.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[ur.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[ur.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"},[ur.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"},[ur.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"},[ur.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"}},vr={[dr.AIRTEL]:ar.AIRTEL,[dr.TIGO]:ar.TIGO,[dr.HALOTEL]:ar.HALOTEL,[dr.VODACOM]:ar.VODACOM,[dr.SAFARICOM]:ar.SAFARICOM};class _r{id;status;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";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,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=a.from(e.amount,t)??a.from(0,t),this.serviceFee=e.serviceFee?a.from(parseFloat(e.serviceFee),t)??a.from(0,t):void 0,this.postedAmount=e.postedAmount?a.from(parseFloat(e.postedAmount),t)??a.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 this.status===ur.PENDING_ACK}isSuccessful(){return this.status===ur.PAYMENT_ACCEPTED}isFailed(){return Object.entries(gr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return gr[this.status]}getChannelInfo(){return vr[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,Object.values(dr).includes(e);var e}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new _r(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=_r.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(!s.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!s.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!s.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=a.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,n;if(e.serviceFee){const t=a.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue.toString()}if(e.postedAmount){const t=a.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const i={id:e.id,status:e.status,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:r,postedAmount:n,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 _r(i)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=_r.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,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"];class wr extends nr{static create(){return new wr}static fromFilters(e){return(new wr).applyFilters(e)}static fromUrlParams(e){try{const t=fr.collectionURLQueryParams.parse(wr.normalizeUrlParams(e)),r=fr.collectionFilters.parse(t);return wr.fromFilters(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return wr.fromUrlParams(wr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return wr.fromSearchParams(t)}static from(e){try{return null==e?new wr:nr.is(e)?new wr(e.options):e instanceof URLSearchParams?wr.fromSearchParams(e):wr.isUrlParamsRecord(e)?wr.fromUrlParams(e):wr.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`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=mr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",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.whereStatus(ur.PENDING_ACK)}whereSuccessful(){return this.whereStatus(ur.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[ur.PAYMENT_REJECTED,ur.GENERIC_FAILURE,ur.INSUFFICIENT_FUNDS,ur.PROVIDER_FAILED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("reference",e)}wherePartnerReference(e){return this.whereContains("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.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),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.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(`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}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(dr).some(t=>t===e)}isValidStatus(e){return Object.values(ur).some(t=>t===e)}}class Ir extends Ht{constructor(e){super("collection",yr,e)}async getCollections(e){try{const t=wr.from(e),r=t.build(),n=await this.client.getCollections({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=_r.createMany(a.results);if(!o)throw new Error("Invalid collection data received from server");return{collections:o,pagination:i}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=wr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=_r.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=Qt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}}var Nr,Ar,Er;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.WALLET_DEBITED="WALLET_DEBITED",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING="PENDING",e.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",e.PENDING_ACK="PENDING_ACK",e.REVERSED="REVERSED",e.INVALID_SERVICE="INVALID_SERVICE",e.INVALID_NUMBER="INVALID_NUMBER",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.THIRDPARTY_FAILED="THIRDPARTY_FAILED",e.PROVIDER_FAILED="PROVIDER_FAILED"}(Nr||(Nr={})),function(e){e.AIRTEL="TZ-AIRTEL-B2C",e.VODACOM="TZ-VODACOM-B2C",e.TIGO="TZ-TIGO-B2C",e.HALOTEL="TZ-HALOTEL-B2C",e.SAFARICOM="TZ-SAFARICOM-B2C"}(Ar||(Ar={})),function(e){e.BANK="TZ-BANK-B2C"}(Er||(Er={}));const Cr=r.nativeEnum(Nr),Sr=r.nativeEnum(Ar),Tr=r.nativeEnum(Er),Or=r.union([Sr,Tr]),Rr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Rr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},xr=r.union([r.string(),r.array(r.string())]),Dr={payout:r.object({id:r.string().min(1),statusCode:r.string(),statusCodeText:Cr,statusDescription:r.string(),countryCode:r.string(),serviceCode:Or,amount:r.number().min(0),serviceFee:r.string().optional(),postedAmount:r.string().optional(),walletId:r.string().optional(),msisdn:r.string().min(1),narration:r.string(),currencyCode:r.string(),recipientNames:r.string().optional(),transactionRef:r.string(),transactionDate:r.string().datetime(),externalId:r.string().nullable().optional(),cbaReferenceNo:r.string().optional(),beepTransactionId:r.string().optional(),receiptNumber:r.string().optional(),createdAt:r.string().datetime(),reversedTransactionId:r.string().nullable().optional(),transactionId:r.string(),serviceFeeTransactionId:r.string().optional(),isReconciled:r.number().optional(),requestId:r.string().optional(),notes:r.string().optional(),updatedAt:r.string().datetime().optional()}),payoutFilters:r.object({page:r.number().int().positive().default(1),limit:r.number().int().positive().max(5e4).default(20),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().datetime().optional(),endDate:r.string().datetime().optional(),msisdn:r.string().optional(),accountNo:r.string().optional(),walletId:r.string().optional(),id:r.string().optional(),idIn:r.array(r.string()).optional(),ref:r.string().optional(),refIn:r.array(r.string()).optional(),channelRef:r.string().optional(),channelRefIn:r.array(r.string()).optional(),channel:Or.optional(),channelIn:r.array(Or).optional(),status:Cr.optional(),statusIn:r.array(Cr).optional(),minAmount:r.number().min(0).optional(),maxAmount:r.number().min(0).optional(),search:r.string().optional()}),payoutURLQueryParams:r.object({page:r.string().transform(e=>parseInt(e)||1).optional(),limit:r.string().transform(e=>parseInt(e)||20).optional(),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().optional(),endDate:r.string().optional(),msisdn:r.string().optional(),accountNo:r.string().optional(),walletId:r.string().optional(),id:r.string().optional(),idIn:xr.transform(Rr).optional(),ref:r.string().optional(),refIn:xr.transform(Rr).optional(),channelRef:r.string().optional(),channelRefIn:xr.transform(Rr).optional(),channel:r.string().refine(e=>Object.values(Ar).includes(e)||e===Er.BANK).transform(e=>e).optional(),channelIn:xr.transform(Rr).pipe(r.array(Or)).optional(),status:r.string().refine(e=>Object.values(Nr).includes(e)).transform(e=>e).optional(),statusIn:xr.transform(Rr).pipe(r.array(Cr)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),payoutStatus:Cr,payoutChannel:Or,mobileChannel:Sr,bankChannel:Tr,walletSummary:r.object({balance:r.number(),currency:r.string(),lastUpdated:r.string().datetime()}),transactionSummary:r.object({yesterday:r.number(),today:r.number(),thisMonth:r.number(),lastMonth:r.number()}),pagination:r.object({page:r.number(),limit:r.number(),total:r.number(),totalPages:r.number(),hasNext:r.boolean(),hasPrev:r.boolean()})},kr=Ct().router({getPayouts:{method:"GET",path:"",query:Dr.payoutURLQueryParams,responses:{200:r.object({results:r.array(Dr.payout),total:r.number()}),401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:r.object({id:r.string()}),responses:{200:Dr.payout,401:Kt.unauthorizedError,403:Kt.forbiddenError,404:Kt.notFoundError,500:Kt.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:Kt.transactionSummary,401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),Pr={[Nr.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[Nr.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[Nr.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[Nr.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"},[Nr.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[Nr.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"},[Nr.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"},[Nr.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"},[Nr.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"},[Nr.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"},[Nr.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"},[Nr.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"},[Nr.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."}},Fr={[Ar.AIRTEL]:ar.AIRTEL,[Ar.VODACOM]:ar.VODACOM,[Ar.TIGO]:ar.TIGO,[Ar.HALOTEL]:ar.HALOTEL,[Ar.SAFARICOM]:ar.SAFARICOM};function jr(e){return Object.values(Ar).includes(e)}function Lr(e){return e===Er.BANK}class Mr{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";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=a.from(e.amount,t)??a.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:a.from(e.serviceFee,t)??a.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?a.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[Nr.PENDING,Nr.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===Nr.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Pr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return Pr[this.statusCodeText]}getChannelInfo(){if(jr(this.serviceCode))return Fr[this.serviceCode];if(Lr(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&i.validateSwiftCode(e)){if(i.getCountryFromSwiftCode(e))try{return o.getInstance().detectBank(e)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&i.getCountryFromSwiftCode(this.swiftCode)){if(i.getCountryFromSwiftCode(this.swiftCode))try{return o.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(Lr(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:c.is(e)?e.shortName:"Bank Transfer"}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Mr(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=Mr.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(!s.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!s.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!s.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=a.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,n;if(e.serviceFee){const t=a.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue}if(e.postedAmount){const t=a.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const i={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:r,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:n,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 Mr(i)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=Mr.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 Zr=["status","channel","id","ref","channelRef"],Br=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class $r extends nr{static create(){return new $r}static fromFilters(e){return(new $r).applyFilters(e)}static fromUrlParams(e){try{const t=Dr.payoutURLQueryParams.parse($r.normalizeUrlParams(e)),r=Dr.payoutFilters.parse(t);return $r.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return $r.fromUrlParams($r.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return $r.fromSearchParams(t)}static from(e){return null==e?new $r:nr.is(e)?new $r(e.options):e instanceof URLSearchParams?$r.fromSearchParams(e):$r.isUrlParamsRecord(e)?$r.fromUrlParams(e):$r.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 Zr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Rr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}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",[Nr.PENDING,Nr.PENDING_ACK])}whereSuccessful(){return this.whereStatus(Nr.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[Nr.PAYMENT_REJECTED,Nr.GENERIC_FAILURE,Nr.AMOUNT_EXCEED_MAXIMUM,Nr.INVALID_SERVICE,Nr.INSUFFICIENT_BALANCE,Nr.THIRDPARTY_FAILED,Nr.WALLET_DEBITED,Nr.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(Ar))}whereBank(){return this.whereChannel(Er.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=Rr(t.value);if(0===r.length)continue;e[`${Br[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=Rr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Rr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Rr(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(Ar).some(t=>t===e)||e===Er.BANK}isValidStatus(e){return Object.values(Nr).some(t=>t===e)}}class Ur extends Ht{constructor(e){super("payout",kr,e)}async getPayouts(e){try{const t=$r.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=Mr.createMany(a.results);if(!o)throw new Error("Invalid payout data received from server");return{payouts:o,pagination:i}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=$r.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Mr.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=Qt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}}const Vr={localTransferRequest:r.object({amount:r.number().int().positive(),from:r.string().min(1),to:r.string().min(1),description:r.string().min(1)}),localTransferResponse:r.object({transactionId:r.string(),from:r.string(),to:r.string(),transactionDate:r.string(),narration:r.string(),amount:r.number(),transactionRef:r.string()})},Jr=Ct().router({localTransfer:{method:"POST",path:"/local-transfer",body:Vr.localTransferRequest,responses:{201:Vr.localTransferResponse,400:Kt.validationError,401:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});class qr extends Ht{constructor(e){super("transaction",Jr,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}}var Wr;!function(e){e.VENDOR="Vendor",e.DEFAULT_DISBURSEMENT="DEFAULT DISBURSEMENT",e.DEFAULT_COLLECTION="DEFAULT COLLECTION",e.COLLECTION="COLLECTION",e.DISBURSEMENT="DISBURSEMENT"}(Wr||(Wr={}));const Gr=r.nativeEnum(Wr),zr=r.object({id:r.string().min(1),accountNo:r.string().min(1),accountName:r.string().min(1),shadowAccountNo:r.string().nullish(),externalId:r.string().nullish(),reference:r.string().nullish(),type:r.string().min(1),vendorId:r.string().nullish(),balance:r.number(),minBalance:r.union([r.number(),r.string()]),approvalLimit:r.union([r.number(),r.string()]),currency:r.string().min(1),countryCode:r.string().min(1),createdAt:r.string().min(1),updatedAt:r.string().min(1)}),Kr=r.object({availableBalance:r.number(),currentBalance:r.number(),accountStatus:r.string().min(1),accountNo:r.string().min(1),accountName:r.string().min(1)}),Hr={wallet:zr,walletType:Gr,walletPathParams:r.object({accountNo:r.string().min(1)}),walletBalance:Kr,walletStatementQuery:r.object({startDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},Yr=Ct().router({listWallets:{method:"GET",path:"",responses:{200:r.array(Hr.wallet),401:Kt.unauthorizedError,500:Kt.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:r.object({accountNo:r.string().min(1)}),responses:{200:Hr.wallet,401:Kt.unauthorizedError,500:Kt.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:Hr.walletPathParams,responses:{200:Hr.walletBalance,401:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.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:Hr.walletPathParams,query:Hr.walletStatementQuery,responses:{200:r.array(Kt.statementEntry),400:Kt.validationError,401:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class Qr{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){this._originalData={...e};let t="TZS";n.isCode(e.currency)?t=e.currency:"KSH"===e.currency&&(t="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=e.type,this.vendorId=e.vendorId,this.balance=a.from(e.balance,t)??a.from(0,t),this.minBalance=a.from(this.parseAmountValue(e.minBalance),t)??a.from(0,t),this.approvalLimit=a.from(this.parseAmountValue(e.approvalLimit),t)??a.from(0,t),this.currency=t,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.includes("COLLECTION")}isDisbursementWallet(){return this.type.includes("DISBURSEMENT")}isDefaultWallet(){return this.type.startsWith("DEFAULT")}static from(e){return new Qr(e)}static createMany(e){const t=[];try{for(const r of e)t.push(Qr.from(r));return t}catch(e){return void console.error("Error creating Wallets:",e)}}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(!s.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!s.getInstance().isAmountJSON(e.minBalance)||!s.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=a.fromJSON(e.balance),r=a.fromJSON(e.minBalance),n=a.fromJSON(e.approvalLimit);return t&&r&&n?new Qr({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:r.numericValue,approvalLimit:n.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)}}}class Xr extends Ht{constructor(e){super("wallet",Yr,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=Qr.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 Qr.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return Xt.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=Yt.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)}}export{Lt as APIError,sr as AuthDTOSchemas,cr as AuthRepository,Er as BANK_PAYOUT_CHANNEL,Ht as BaseRepository,dr as COLLECTION_CHANNEL,ur as COLLECTION_STATUS,gr as COLLECTION_STATUS_INFO,_r as Collection,fr as CollectionDTOSchemas,wr as CollectionQuery,Ir as CollectionRepository,Kt as CommonSchemas,er as FilterOperator,Ar as MOBILE_PAYOUT_CHANNEL,ar as MobileChannels,Nr as PAYOUT_STATUS,Pr as PAYOUT_STATUS_INFO,Mr as Payout,Dr as PayoutDTOSchemas,$r as PayoutQuery,Ur as PayoutRepository,rr as QUERY_BUILDER_TYPE,nr as QueryBuilder,tr as SortDirection,Yt as StatementEntry,Vr as TransactionDTOSchemas,qr as TransactionRepository,Qt as TransactionSummary,or as User,Wr as WALLET_TYPE,Qr as Wallet,Hr as WalletDTOSchemas,Xt as WalletInfo,Xr as WalletRepository,ir as authContract,yr as collectionContract,mr as collectionToStringArray,kr as payoutContract,Rr as payoutToStringArray,zt as statementEntrySchema,Jr as transactionContract,Yr as walletContract};
|
|
1
|
+
import{v4 as e}from"uuid";import t,{z as r}from"zod";import{CurrencyHelpers as n,Amount as a,AmountFactory as s,BankHelpers as i,BankRegistry as o,Bank as c}from"@temboplus/frontend-core";var u,d;!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}(u||(u={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(d||(d={}));const l=u.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),h=e=>{switch(typeof e){case"undefined":return l.undefined;case"string":return l.string;case"number":return isNaN(e)?l.nan:l.number;case"boolean":return l.boolean;case"function":return l.function;case"bigint":return l.bigint;case"symbol":return l.symbol;case"object":return Array.isArray(e)?l.array:null===e?l.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?l.promise:"undefined"!=typeof Map&&e instanceof Map?l.map:"undefined"!=typeof Set&&e instanceof Set?l.set:"undefined"!=typeof Date&&e instanceof Date?l.date:l.object;default:return l.unknown}},m=u.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 p 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 a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,n=0;for(;n<a.path.length;){const r=a.path[n];n===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,u.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()}}p.create=e=>new p(e);const f=(e,t)=>{let r;switch(e.code){case m.invalid_type:r=e.received===l.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,u.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:r=`Unrecognized key(s) in object: ${u.joinValues(e.keys,", ")}`;break;case m.invalid_union:r="Invalid input";break;case m.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${u.joinValues(e.options)}`;break;case m.invalid_enum_value:r=`Invalid enum value. Expected ${u.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:r="Invalid function arguments";break;case m.invalid_return_type:r="Invalid function return type";break;case m.invalid_date:r="Invalid date";break;case m.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}"`:u.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case m.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 m.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 m.custom:r="Invalid input";break;case m.invalid_intersection_types:r="Intersection results could not be merged";break;case m.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:r="Number must be finite";break;default:r=t.defaultError,u.assertNever(e)}return{message:r}};let y=f;function g(){return y}const v=e=>{const{data:t,path:r,errorMaps:n,issueData:a}=e,s=[...r,...a.path||[]],i={...a,path:s};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...a,path:s,message:a.message||o}};function b(e,t){const r=v({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,g(),f].filter(e=>!!e)});e.common.issues.push(r)}class _{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 w;"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 _.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:a}=n;if("aborted"===t.status)return w;if("aborted"===a.status)return w;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"===t.value||void 0===a.value&&!n.alwaysSet||(r[t.value]=a.value)}return{status:e.value,value:r}}}const w=Object.freeze({status:"aborted"}),I=e=>({status:"dirty",value:e}),N=e=>({status:"valid",value:e}),A=e=>"aborted"===e.status,E=e=>"dirty"===e.status,S=e=>"valid"===e.status,C=e=>"undefined"!=typeof Promise&&e instanceof Promise;var T;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(T||(T={}));class O{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 R=(e,t)=>{if(S(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 p(e.common.issues);return this._error=t,this._error}}};function x(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=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:a};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:a}}class D{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 h(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:h(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _,ctx:{common:e.parent.common,data:e.data,parsedType:h(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(C(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:h(e)},a=this._parseSync({data:e,path:n.path,parent:n});return R(n,a)}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:h(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(C(n)?n:Promise.resolve(n));return R(r,a)}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 a=e(t),s=()=>n.addIssue({code:m.custom,...r(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(e=>!!e||(s(),!1)):!!a||(s(),!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 we({schema:this,typeName:ke.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Ie.create(this,this._def)}nullable(){return Ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this,this._def)}promise(){return _e.create(this,this._def)}or(e){return se.create([this,e],this._def)}and(e){return ue.create(this,e,this._def)}transform(e){return new we({...x(this._def),schema:this,typeName:ke.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...x(this._def),innerType:this,defaultValue:t,typeName:ke.ZodDefault})}brand(){return new Te({typeName:ke.ZodBranded,type:this,...x(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ee({...x(this._def),innerType:this,catchValue:t,typeName:ke.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Oe.create(this,e)}readonly(){return Re.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const k=/^c[^\s-]{8,}$/i,P=/^[a-z][a-z0-9]*$/,F=/[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,j=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,M=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,Z=/^(((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}))$/,B=/^(([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})))$/,U=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 V(e,t){return!("v4"!==t&&t||!Z.test(e))||!("v6"!==t&&t||!B.test(e))}class $ extends D{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:m.invalid_string,...T.errToObj(r)}),this.nonempty=e=>this.min(1,T.errToObj(e)),this.trim=()=>new $({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new $({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new $({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==l.string){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.string,received:t.parsedType}),w}const t=new _;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),b(r,{code:m.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),b(r,{code:m.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const a=e.data.length>n.value,s=e.data.length<n.value;(a||s)&&(r=this._getOrReturnCtx(e,r),a?b(r,{code:m.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):s&&b(r,{code:m.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)j.test(e.data)||(r=this._getOrReturnCtx(e,r),b(r,{validation:"email",code:m.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)M.test(e.data)||(r=this._getOrReturnCtx(e,r),b(r,{validation:"emoji",code:m.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)L.test(e.data)||(r=this._getOrReturnCtx(e,r),b(r,{validation:"uuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)k.test(e.data)||(r=this._getOrReturnCtx(e,r),b(r,{validation:"cuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),b(r,{validation:"cuid2",code:m.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)F.test(e.data)||(r=this._getOrReturnCtx(e,r),b(r,{validation:"ulid",code:m.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(a){r=this._getOrReturnCtx(e,r),b(r,{validation:"url",code:m.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),b(r,{validation:"regex",code:m.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),b(r,{code:m.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),b(r,{code:m.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),b(r,{code:m.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){U(n).test(e.data)||(r=this._getOrReturnCtx(e,r),b(r,{code:m.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else"ip"===n.kind?V(e.data,n.version)||(r=this._getOrReturnCtx(e,r),b(r,{validation:"ip",code:m.invalid_string,message:n.message}),t.dirty()):u.assertNever(n);return{status:t.value,value:e.data}}_addCheck(e){return new $({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...T.errToObj(e)})}url(e){return this._addCheck({kind:"url",...T.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...T.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...T.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...T.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...T.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...T.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,...T.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...T.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...T.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...T.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...T.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...T.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...T.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...T.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,a=r>n?r:n;return parseInt(e.toFixed(a).replace(".",""))%parseInt(t.toFixed(a).replace(".",""))/Math.pow(10,a)}$.create=e=>{var t;return new $({checks:[],typeName:ke.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class q extends D{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)!==l.number){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.number,received:t.parsedType}),w}let t;const r=new _;for(const n of this._def.checks)if("int"===n.kind)u.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),b(t,{code:m.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),b(t,{code:m.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),b(t,{code:m.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),b(t,{code:m.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),b(t,{code:m.not_finite,message:n.message}),r.dirty()):u.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,T.toString(t))}gt(e,t){return this.setLimit("min",e,!1,T.toString(t))}lte(e,t){return this.setLimit("max",e,!0,T.toString(t))}lt(e,t){return this.setLimit("max",e,!1,T.toString(t))}setLimit(e,t,r,n){return new q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:T.toString(n)}]})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:T.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:T.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.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&&u.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)}}q.create=e=>new q({checks:[],typeName:ke.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class G extends D{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)!==l.bigint){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.bigint,received:t.parsedType}),w}let t;const r=new _;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),b(t,{code:m.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),b(t,{code:m.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),b(t,{code:m.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):u.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,T.toString(t))}gt(e,t){return this.setLimit("min",e,!1,T.toString(t))}lte(e,t){return this.setLimit("max",e,!0,T.toString(t))}lt(e,t){return this.setLimit("max",e,!1,T.toString(t))}setLimit(e,t,r,n){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:T.toString(n)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:T.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}}G.create=e=>{var t;return new G({checks:[],typeName:ke.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class W extends D{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==l.boolean){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.boolean,received:t.parsedType}),w}return N(e.data)}}W.create=e=>new W({typeName:ke.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class z extends D{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==l.date){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.date,received:t.parsedType}),w}if(isNaN(e.data.getTime())){return b(this._getOrReturnCtx(e),{code:m.invalid_date}),w}const t=new _;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),b(r,{code:m.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),b(r,{code:m.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):u.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:T.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:T.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}}z.create=e=>new z({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ke.ZodDate,...x(e)});class K extends D{_parse(e){if(this._getType(e)!==l.symbol){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.symbol,received:t.parsedType}),w}return N(e.data)}}K.create=e=>new K({typeName:ke.ZodSymbol,...x(e)});class H extends D{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.undefined,received:t.parsedType}),w}return N(e.data)}}H.create=e=>new H({typeName:ke.ZodUndefined,...x(e)});class Y extends D{_parse(e){if(this._getType(e)!==l.null){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.null,received:t.parsedType}),w}return N(e.data)}}Y.create=e=>new Y({typeName:ke.ZodNull,...x(e)});class Q extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return N(e.data)}}Q.create=e=>new Q({typeName:ke.ZodAny,...x(e)});class X extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return N(e.data)}}X.create=e=>new X({typeName:ke.ZodUnknown,...x(e)});class ee extends D{_parse(e){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.never,received:t.parsedType}),w}}ee.create=e=>new ee({typeName:ke.ZodNever,...x(e)});class te extends D{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.void,received:t.parsedType}),w}return N(e.data)}}te.create=e=>new te({typeName:ke.ZodVoid,...x(e)});class re extends D{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==l.array)return b(t,{code:m.invalid_type,expected:l.array,received:t.parsedType}),w;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(e||a)&&(b(t,{code:e?m.too_big:m.too_small,minimum:a?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&&(b(t,{code:m.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&&(b(t,{code:m.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 O(t,e,t.path,r)))).then(e=>_.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new O(t,e,t.path,r)));return _.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new re({...this._def,minLength:{value:e,message:T.toString(t)}})}max(e,t){return new re({...this._def,maxLength:{value:e,message:T.toString(t)}})}length(e,t){return new re({...this._def,exactLength:{value:e,message:T.toString(t)}})}nonempty(e){return this.min(1,e)}}function ne(e){if(e instanceof ae){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ie.create(ne(n))}return new ae({...e._def,shape:()=>t})}return e instanceof re?new re({...e._def,type:ne(e.element)}):e instanceof Ie?Ie.create(ne(e.unwrap())):e instanceof Ne?Ne.create(ne(e.unwrap())):e instanceof de?de.create(e.items.map(e=>ne(e))):e}re.create=(e,t)=>new re({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ke.ZodArray,...x(t)});class ae extends D{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=u.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==l.object){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),w}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof ee&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||s.push(e);const i=[];for(const e of a){const t=n[e],a=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new O(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ee){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(b(r,{code:m.unrecognized_keys,keys:s}),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 s){const n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new O(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>_.mergeObjectSync(t,e)):_.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return T.errToObj,new ae({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,a,s,i;const o=null!==(s=null===(a=(n=this._def).errorMap)||void 0===a?void 0:a.call(n,t,r).message)&&void 0!==s?s:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=T.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new ae({...this._def,unknownKeys:"strip"})}passthrough(){return new ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ke.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ae({...this._def,catchall:e})}pick(e){const t={};return u.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ae({...this._def,shape:()=>t})}omit(e){const t={};return u.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ae({...this._def,shape:()=>t})}deepPartial(){return ne(this)}partial(e){const t={};return u.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new ae({...this._def,shape:()=>t})}required(e){const t={};return u.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ie;)e=e._def.innerType;t[r]=e}}),new ae({...this._def,shape:()=>t})}keyof(){return ge(u.objectKeys(this.shape))}}ae.create=(e,t)=>new ae({shape:()=>e,unknownKeys:"strip",catchall:ee.create(),typeName:ke.ZodObject,...x(t)}),ae.strictCreate=(e,t)=>new ae({shape:()=>e,unknownKeys:"strict",catchall:ee.create(),typeName:ke.ZodObject,...x(t)}),ae.lazycreate=(e,t)=>new ae({shape:e,unknownKeys:"strip",catchall:ee.create(),typeName:ke.ZodObject,...x(t)});class se extends D{_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 p(e.ctx.common.issues));return b(t,{code:m.invalid_union,unionErrors:r}),w});{let e;const n=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,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 a=n.map(e=>new p(e));return b(t,{code:m.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}}se.create=(e,t)=>new se({options:e,typeName:ke.ZodUnion,...x(t)});const ie=e=>e instanceof fe?ie(e.schema):e instanceof we?ie(e.innerType()):e instanceof ye?[e.value]:e instanceof ve?e.options:e instanceof be?Object.keys(e.enum):e instanceof Ae?ie(e._def.innerType):e instanceof H?[void 0]:e instanceof Y?[null]:null;class oe extends D{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.object)return b(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),w;const r=this.discriminator,n=t.data[r],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(b(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),w)}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=ie(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of t){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,r)}}return new oe({typeName:ke.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...x(r)})}}function ce(e,t){const r=h(e),n=h(t);if(e===t)return{valid:!0,data:e};if(r===l.object&&n===l.object){const r=u.objectKeys(t),n=u.objectKeys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=ce(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===l.array&&n===l.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const a=ce(e[n],t[n]);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}return r===l.date&&n===l.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ue extends D{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(A(e)||A(n))return w;const a=ce(e.value,n.value);return a.valid?((E(e)||E(n))&&t.dirty(),{status:t.value,value:a.data}):(b(r,{code:m.invalid_intersection_types}),w)};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}))}}ue.create=(e,t,r)=>new ue({left:e,right:t,typeName:ke.ZodIntersection,...x(r)});class de extends D{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.array)return b(r,{code:m.invalid_type,expected:l.array,received:r.parsedType}),w;if(r.data.length<this._def.items.length)return b(r,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&r.data.length>this._def.items.length&&(b(r,{code:m.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 O(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>_.mergeArray(t,e)):_.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new de({...this._def,rest:e})}}de.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new de({items:e,typeName:ke.ZodTuple,rest:null,...x(t)})};class le extends D{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!==l.object)return b(r,{code:m.invalid_type,expected:l.object,received:r.parsedType}),w;const n=[],a=this._def.keyType,s=this._def.valueType;for(const e in r.data)n.push({key:a._parse(new O(r,e,r.path,e)),value:s._parse(new O(r,r.data[e],r.path,e))});return r.common.async?_.mergeObjectAsync(t,n):_.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new le(t instanceof D?{keyType:e,valueType:t,typeName:ke.ZodRecord,...x(r)}:{keyType:$.create(),valueType:e,typeName:ke.ZodRecord,...x(t)})}}class he extends D{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!==l.map)return b(r,{code:m.invalid_type,expected:l.map,received:r.parsedType}),w;const n=this._def.keyType,a=this._def.valueType,s=[...r.data.entries()].map(([e,t],s)=>({key:n._parse(new O(r,e,r.path,[s,"key"])),value:a._parse(new O(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const n=await r.key,a=await r.value;if("aborted"===n.status||"aborted"===a.status)return w;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const n=r.key,a=r.value;if("aborted"===n.status||"aborted"===a.status)return w;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}}}}he.create=(e,t,r)=>new he({valueType:t,keyType:e,typeName:ke.ZodMap,...x(r)});class me extends D{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.set)return b(r,{code:m.invalid_type,expected:l.set,received:r.parsedType}),w;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(b(r,{code:m.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&&(b(r,{code:m.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function s(e){const r=new Set;for(const n of e){if("aborted"===n.status)return w;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>a._parse(new O(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>s(e)):s(i)}min(e,t){return new me({...this._def,minSize:{value:e,message:T.toString(t)}})}max(e,t){return new me({...this._def,maxSize:{value:e,message:T.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}me.create=(e,t)=>new me({valueType:e,minSize:null,maxSize:null,typeName:ke.ZodSet,...x(t)});class pe extends D{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.function)return b(t,{code:m.invalid_type,expected:l.function,received:t.parsedType}),w;function r(e,r){return v({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g(),f].filter(e=>!!e),issueData:{code:m.invalid_arguments,argumentsError:r}})}function n(e,r){return v({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g(),f].filter(e=>!!e),issueData:{code:m.invalid_return_type,returnTypeError:r}})}const a={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof _e){const e=this;return N(async function(...t){const i=new p([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(s,this,o);return await e._def.returns._def.type.parseAsync(c,a).catch(e=>{throw i.addIssue(n(c,e)),i})})}{const e=this;return N(function(...t){const i=e._def.args.safeParse(t,a);if(!i.success)throw new p([r(t,i.error)]);const o=Reflect.apply(s,this,i.data),c=e._def.returns.safeParse(o,a);if(!c.success)throw new p([n(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new pe({...this._def,args:de.create(e).rest(X.create())})}returns(e){return new pe({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new pe({args:e||de.create([]).rest(X.create()),returns:t||X.create(),typeName:ke.ZodFunction,...x(r)})}}class fe extends D{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})}}fe.create=(e,t)=>new fe({getter:e,typeName:ke.ZodLazy,...x(t)});class ye extends D{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return b(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ge(e,t){return new ve({values:e,typeName:ke.ZodEnum,...x(t)})}ye.create=(e,t)=>new ye({value:e,typeName:ke.ZodLiteral,...x(t)});class ve extends D{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return b(t,{expected:u.joinValues(r),received:t.parsedType,code:m.invalid_type}),w}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return b(t,{received:t.data,code:m.invalid_enum_value,options:r}),w}return N(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 ve.create(e)}exclude(e){return ve.create(this.options.filter(t=>!e.includes(t)))}}ve.create=ge;class be extends D{_parse(e){const t=u.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==l.string&&r.parsedType!==l.number){const e=u.objectValues(t);return b(r,{expected:u.joinValues(e),received:r.parsedType,code:m.invalid_type}),w}if(-1===t.indexOf(e.data)){const e=u.objectValues(t);return b(r,{received:r.data,code:m.invalid_enum_value,options:e}),w}return N(e.data)}get enum(){return this._def.values}}be.create=(e,t)=>new be({values:e,typeName:ke.ZodNativeEnum,...x(t)});class _e extends D{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.promise&&!1===t.common.async)return b(t,{code:m.invalid_type,expected:l.promise,received:t.parsedType}),w;const r=t.parsedType===l.promise?t.data:Promise.resolve(t.data);return N(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}_e.create=(e,t)=>new _e({type:e,typeName:ke.ZodPromise,...x(t)});class we extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ke.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=>{b(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?w:("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?w:("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(!S(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=>S(e)?Promise.resolve(n.transform(e.value,a)).then(e=>({status:t.value,value:e})):e)}u.assertNever(n)}}we.create=(e,t,r)=>new we({schema:e,typeName:ke.ZodEffects,effect:t,...x(r)}),we.createWithPreprocess=(e,t,r)=>new we({schema:t,effect:{type:"preprocess",transform:e},typeName:ke.ZodEffects,...x(r)});class Ie extends D{_parse(e){return this._getType(e)===l.undefined?N(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:ke.ZodOptional,...x(t)});class Ne extends D{_parse(e){return this._getType(e)===l.null?N(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:ke.ZodNullable,...x(t)});class Ae extends D{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===l.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:ke.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...x(t)});class Ee extends D{_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 C(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new p(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new p(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:ke.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...x(t)});class Se extends D{_parse(e){if(this._getType(e)!==l.nan){const t=this._getOrReturnCtx(e);return b(t,{code:m.invalid_type,expected:l.nan,received:t.parsedType}),w}return{status:"valid",value:e.data}}}Se.create=e=>new Se({typeName:ke.ZodNaN,...x(e)});const Ce=Symbol("zod_brand");class Te extends D{_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 Oe extends D{_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?w:"dirty"===e.status?(t.dirty(),I(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?w:"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 Oe({in:e,out:t,typeName:ke.ZodPipeline})}}class Re extends D{_parse(e){const t=this._def.innerType._parse(e);return S(t)&&(t.value=Object.freeze(t.value)),t}}Re.create=(e,t)=>new Re({innerType:e,typeName:ke.ZodReadonly,...x(t)});const xe=(e,t={},r)=>e?Q.create().superRefine((n,a)=>{var s,i;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(i=null!==(s=e.fatal)&&void 0!==s?s:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;a.addIssue({code:"custom",...c,fatal:o})}}):Q.create(),De={object:ae.lazycreate};var ke;!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"}(ke||(ke={}));const Pe=$.create,Fe=q.create,Le=Se.create,je=G.create,Me=W.create,Ze=z.create,Be=K.create,Ue=H.create,Ve=Y.create,$e=Q.create,Je=X.create,qe=ee.create,Ge=te.create,We=re.create,ze=ae.create,Ke=ae.strictCreate,He=se.create,Ye=oe.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=me.create,nt=pe.create,at=fe.create,st=ye.create,it=ve.create,ot=be.create,ct=_e.create,ut=we.create,dt=Ie.create,lt=Ne.create,ht=we.createWithPreprocess,mt=Oe.create,pt={string:e=>$.create({...e,coerce:!0}),number:e=>q.create({...e,coerce:!0}),boolean:e=>W.create({...e,coerce:!0}),bigint:e=>G.create({...e,coerce:!0}),date:e=>z.create({...e,coerce:!0})},ft=w;var yt=Object.freeze({__proto__:null,defaultErrorMap:f,setErrorMap:function(e){y=e},getErrorMap:g,makeIssue:v,EMPTY_PATH:[],addIssueToContext:b,ParseStatus:_,INVALID:w,DIRTY:I,OK:N,isAborted:A,isDirty:E,isValid:S,isAsync:C,get util(){return u},get objectUtil(){return d},ZodParsedType:l,getParsedType:h,ZodType:D,ZodString:$,ZodNumber:q,ZodBigInt:G,ZodBoolean:W,ZodDate:z,ZodSymbol:K,ZodUndefined:H,ZodNull:Y,ZodAny:Q,ZodUnknown:X,ZodNever:ee,ZodVoid:te,ZodArray:re,ZodObject:ae,ZodUnion:se,ZodDiscriminatedUnion:oe,ZodIntersection:ue,ZodTuple:de,ZodRecord:le,ZodMap:he,ZodSet:me,ZodFunction:pe,ZodLazy:fe,ZodLiteral:ye,ZodEnum:ve,ZodNativeEnum:be,ZodPromise:_e,ZodEffects:we,ZodTransformer:we,ZodOptional:Ie,ZodNullable:Ne,ZodDefault:Ae,ZodCatch:Ee,ZodNaN:Se,BRAND:Ce,ZodBranded:Te,ZodPipeline:Oe,ZodReadonly:Re,custom:xe,Schema:D,ZodSchema:D,late:De,get ZodFirstPartyTypeKind(){return ke},coerce:pt,any:$e,array:We,bigint:je,boolean:Me,date:Ze,discriminatedUnion:Ye,effect:ut,enum:it,function:nt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>xe(t=>t instanceof e,t),intersection:Qe,lazy:at,literal:st,map:tt,nan:Le,nativeEnum:ot,never:qe,null:Ve,nullable:lt,number:Fe,object:ze,oboolean:()=>Me().optional(),onumber:()=>Fe().optional(),optional:dt,ostring:()=>Pe().optional(),pipeline:mt,preprocess:ht,promise:ct,record:et,set:rt,strictObject:Ke,string:Pe,symbol:Be,transformer:ut,tuple:Xe,undefined:Ue,union:He,unknown:Je,void:Ge,NEVER:ft,ZodIssueCode:m,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:p});const gt=e=>"function"==typeof(null==e?void 0:e.passthrough),vt=yt.object({name:yt.literal("ZodError"),issues:yt.array(yt.object({path:yt.array(yt.union([yt.string(),yt.number()])),message:yt.string().optional(),code:yt.nativeEnum(yt.ZodIssueCode)}).catchall(yt.any()))});class bt 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}}yt.object({message:yt.literal("Request validation failed"),pathParameterErrors:vt.nullable(),headerErrors:vt.nullable(),queryParameterErrors:vt.nullable(),bodyErrors:vt.nullable()}),yt.object({pathParameterErrors:vt.nullable(),headerErrors:vt.nullable(),queryParameterErrors:vt.nullable(),bodyErrors:vt.nullable()}),yt.object({paramsResult:vt.nullable(),headersResult:vt.nullable(),queryResult:vt.nullable(),bodyResult:vt.nullable()});const _t="zod-ts-rest-polyfill",wt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof ae&&t instanceof ae){return n=t,gt(r=e)?gt(n)?r.merge(n):r:gt(n)?n:Object.assign({},r,n)}var r,n;return{...e,...t}},It=Symbol("ContractNoBody"),Nt=e=>"method"in e&&"path"in e,At=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s;return Nt(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:wt(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!==(a=r.validateResponseOnClient)&&void 0!==a?a: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!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,At(r,t)]})),Et=Symbol("ContractPlainType"),St=()=>({router:(e,t)=>At(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:()=>It}),Ct=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("&"):"",Tt=e=>e?Object.keys(e).flatMap(t=>Ot(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",Ot=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>Ot(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>Ot(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Rt extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const xt=async({route:e,path:t,method:r,headers:n,body:a,validateResponse:s,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:n,body:a}),c=o.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t=e.responses[o.status],r={status:o.status,body:t===It?void 0:await o.json(),headers:o.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:_t,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!=s?s: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===_t?{error:new p(n.issues)}:{error:new bt(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:o.status,body:await o.text(),headers:o.headers}:{status:o.status,body:await o.blob(),headers:o.headers}},Dt=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},kt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Pt=(e,t,r,n,a)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?Ct(e):Tt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return t.endsWith("/")&&s.startsWith("/")?`${t}${s.substring(1)}${i}`:`${t}${s}${i}`},Ft=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:s,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof a?Object.fromEntries(Object.entries(a).map(([e,t])=>[e,String(t)])):{};return{path:Pt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:s,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...o,...i}}})(e,t,n),s=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:s,extraInputArgs:i,headers:o,fetchOptions:c}=e,u=r.api||xt,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&kt(d),...kt(o)};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:a,rawQuery:s,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:a instanceof FormData?a:Dt(a)}:"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 a?a:new URLSearchParams(a)}:null!=a&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(a)})),u({...h,...i})})(a);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new Rt(s,r)}},Lt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>Nt(r)?[e,Ft(r,t)]:[e,Lt(r,t)]));class jt 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 jt.schema.safeParse(e).success}static unknown(e){return new jt({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return r.object({message:r.string(),statusCode:r.number().int(),error:r.string().optional(),details:r.object({}).optional()})}}const Mt=t.object({statusCode:t.number().int(),reason:t.string().optional(),error:t.string().optional(),details:t.record(t.string(),t.unknown()).optional(),message:t.string().optional()}),Zt=Mt.extend({statusCode:t.literal(400)}),Bt=Mt.extend({statusCode:t.literal(401)}),Ut=Mt.extend({statusCode:t.literal(403)}),Vt=Mt.extend({statusCode:t.literal(404)}),$t=Mt.extend({statusCode:t.literal(500)}),Jt=t.object({page:t.number().int().positive(),limit:t.number().int().positive(),total:t.number().int().min(0),totalPages:t.number().int().min(0),hasNext:t.boolean(),hasPrev:t.boolean()}),qt=t.object({balance:t.number(),availableBalance:t.number(),accountNumber:t.string(),accountName:t.string()}),Gt=t.object({yesterday:t.number(),today:t.number(),thisMonth:t.number(),lastMonth:t.number()});const Wt=t.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"}`)}}),zt=t.object({accountNo:t.string().nullish(),debitOrCredit:t.enum(["CR","DR"],{error:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:t.string().nullish(),cbaRefNo:t.string().nullish(),narration:t.string().nullish(),txnDate:Wt,valueDate:Wt,amountCredited:t.union([t.number().min(0,"Credited amount cannot be negative"),t.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:t.union([t.number().min(0,"Debited amount cannot be negative"),t.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:t.number({error:e=>void 0===e.input?"Balance is required":"Balance must be a number"})}),Kt={apiError:Mt,validationError:Zt,unauthorizedError:Bt,forbiddenError:Ut,notFoundError:Vt,serverError:$t,pagination:Jt,transactionSummary:Gt,walletSummary:qt,statementEntry:zt};class Ht{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(/^\/+/,""):"",a=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,s={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e()},i={baseUrl:a,baseHeaders:t?{...s,...t}:s};return Lt(this.contract,i)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=Kt.apiError.safeParse(e.body),n=r.success?r.data:void 0,a=(t,r)=>new jt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw a("Bad request","BAD_REQUEST");if(401===e.status)throw a("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw a("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw a("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw a("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw a("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class Yt{accountNo;debitOrCredit;tranRefNo;cbaRefNo;narration;txnDate;valueDate;amountCredited;amountDebited;balance;currency;constructor(e,t="TZS"){let r="TZS";n.isCode(t)&&(r=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=r;const s=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===s?null:s>0?a.from(s,r)??a.from(0,r):null;const i=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===i?null:i>0?a.from(i,r)??a.from(0,r):null,this.balance=a.from(e.balance,r)??a.from(0,r)}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 Kt.statementEntry.safeParse(e).success?new Yt(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=Yt.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(!s.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!s.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!s.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=a.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let r=0;if(e.amountCredited){const t=a.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);r=t.numericValue}let n=0;if(e.amountDebited){const t=a.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);n=t.numericValue}const i={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:r,amountDebited:n,balance:t.numericValue};return new Yt(i,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=Yt.fromJSON(r);if(!e)return;t.push(e)}return t}static getTotalCredits(e){const t=e.length>0?e[0].currency:"TZS",r=e.reduce((e,t)=>t.isCredit()&&t.amountCredited?e+t.amountCredited.numericValue:e,0);return a.from(r,t)??a.from(0,t)}static getTotalDebits(e){const t=e.length>0?e[0].currency:"TZS",r=e.reduce((e,t)=>t.isDebit()&&t.amountDebited?e+t.amountDebited.numericValue:e,0);return a.from(r,t)??a.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",r=Yt.getTotalCredits(e).numericValue,n=Yt.getTotalDebits(e).numericValue;return a.from(r-n,t)??a.from(0,t)}}class Qt{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=a.from(e.yesterday,t)??a.from(0,t),this.today=a.from(e.today,t)??a.from(0,t),this.thisMonth=a.from(e.thisMonth,t)??a.from(0,t),this.lastMonth=a.from(e.lastMonth,t)??a.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 a.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new Qt(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(!(s.getInstance().isAmountJSON(e.yesterday)&&s.getInstance().isAmountJSON(e.today)&&s.getInstance().isAmountJSON(e.thisMonth)&&s.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=a.fromJSON(e.yesterday),r=a.fromJSON(e.today),n=a.fromJSON(e.thisMonth),i=a.fromJSON(e.lastMonth);if(!(t&&r&&n&&i))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const o={yesterday:t.numericValue,today:r.numericValue,thisMonth:n.numericValue,lastMonth:i.numericValue};return new Qt(o,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class Xt{accountName;accountNo;accountNumber;availableBalance;currentBalance;actualBalance;accountStatus;type;currencyCode;countryCode;currency;constructor(e){let t="TZS";e.currencyCode&&n.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=a.from(e.availableBalance,t)??a.from(0,t),this.currentBalance=a.from(e.currentBalance,t)??a.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 Xt(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(!s.getInstance().isAmountJSON(e.availableBalance)||!s.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=a.fromJSON(e.availableBalance),r=e.currentBalance??e.actualBalance;if(!s.getInstance().isAmountJSON(r))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const n=a.fromJSON(r);if(!t||!n)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const i=e.accountNo||e.accountNumber;if(!i)return void console.error("Missing account number in WalletInfo JSON:",e);const o={accountName:e.accountName,accountNo:i,availableBalance:t.numericValue,currentBalance:n.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new Xt(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=Xt.fromJSON(r);if(!e)return;t.push(e)}return t}}var er,tr;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(er||(er={})),function(e){e.ASC="asc",e.DESC="desc"}(tr||(tr={}));const rr=Symbol("query-builder-type");class nr{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}}[rr]="query-builder";static is(e){return null!==e&&"object"==typeof e&&rr in e&&"query-builder"===e[rr]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:er.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:er.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:er.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:er.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:er.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:er.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:er.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:er.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:er.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:er.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:er.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=tr.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,tr.ASC)}orderByDesc(e){return this.orderBy(e,tr.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 er.IS_NULL:e[`${t.field}:isNull`]=1;break;case er.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case er.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case er.LIKE:e[`${t.field}:like`]=t.value;break;case er.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case er.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case er.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===tr.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 nr(e)}}const ar={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 sr;!function(e){e.READ_ONLY="ReadOnly",e.ADMIN="Admin",e.INITIATOR="Initiator",e.APPROVER="Approver"}(sr||(sr={}));const ir=r.enum(sr),or={user:r.object({token:r.string(),identity:r.string(),name:r.string(),role:ir}),userRole:ir,loginRequest:r.object({identity:r.email(),password:r.string()}),updatePassword:r.object({currentPassword:r.string(),newPassword:r.string()})},cr=St().router({login:{method:"POST",path:"/login",body:or.loginRequest,responses:{201:or.user,400:Kt.validationError,401:Kt.unauthorizedError,500:Kt.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:or.updatePassword,responses:{201:t.object({}),400:Kt.validationError,401:Kt.unauthorizedError,500:Kt.serverError},summary:"Update password",description:"Update user password"}});class ur{identity;name;role;constructor(e){this.identity=e.identity,this.name=e.name,this.role=e.role}static from(e){return new ur(e)}static fromJson(e){return ur.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}}class dr extends Ht{constructor(e){super("auth",cr,e)}async login(e){const t={identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),a=ur.from(n);if(!a)throw new Error("Invalid user data received from server");return{user:a,token:n.token}}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}}var lr,hr;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING_ACK="PENDING_ACK",e.PROVIDER_FAILED="PROVIDER_FAILED"}(lr||(lr={})),function(e){e.AIRTEL="TZ-AIRTEL-C2B",e.TIGO="TZ-TIGO-C2B",e.HALOTEL="TZ-HALOTEL-C2B",e.SAFARICOM="KE-SAFARICOM-C2B",e.VODACOM="TZ-VODACOM-C2B"}(hr||(hr={}));const mr=r.enum(lr),pr=r.enum(hr),fr=e=>{const t=Array.isArray(e)?e.flatMap(e=>fr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},yr=r.union([r.string(),r.array(r.string())]),gr={collection:r.object({id:r.string().min(1),status:mr,statusMessage:r.string(),accountNo:r.string().min(1),walletId:r.string(),transactionDate:r.iso.datetime(),narration:r.string(),msisdn:r.string().min(1),channel:pr,amount:r.number().min(0),serviceFee:r.string().optional(),postedAmount:r.string().optional(),reference:r.string(),partnerReference:r.string().nullable().optional(),payerName:r.string().nullable().optional(),payerReference:r.string().nullable().optional(),merchantName:r.string().nullable().optional(),merchantReference:r.string().nullable().optional(),transactionId:r.string().nullable().optional(),serviceFeeTransactionId:r.string().nullable().optional(),requestId:r.string().nullable().optional(),completedAt:r.iso.datetime().nullable().optional(),createdAt:r.iso.datetime(),updatedAt:r.iso.datetime(),notes:r.string().optional(),currencyCode:r.string().default("TZS")}),collectionFilters:r.object({page:r.number().int().positive().default(1),limit:r.number().int().positive().max(5e4).default(20),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.iso.datetime().optional(),endDate:r.iso.datetime().optional(),msisdn:r.string().optional(),id:r.string().optional(),idIn:r.array(r.string()).optional(),reference:r.string().optional(),referenceIn:r.array(r.string()).optional(),accountNo:r.string().optional(),walletId:r.string().optional(),partnerReference:r.string().optional(),channel:pr.optional(),channelIn:r.array(pr).optional(),status:mr.optional(),statusIn:r.array(mr).optional(),minAmount:r.number().min(0).optional(),maxAmount:r.number().min(0).optional(),search:r.string().optional()}),collectionURLQueryParams:r.object({page:r.string().transform(e=>parseInt(e)||1).optional(),limit:r.string().transform(e=>parseInt(e)||20).optional(),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().optional(),endDate:r.string().optional(),msisdn:r.string().optional(),id:r.string().optional(),idIn:yr.transform(fr).optional(),reference:r.string().optional(),referenceIn:yr.transform(fr).optional(),accountNo:r.string().optional(),walletId:r.string().optional(),partnerReference:r.string().optional(),channel:r.string().refine(e=>Object.values(hr).includes(e)).transform(e=>e).optional(),channelIn:yr.transform(fr).pipe(r.array(pr)).optional(),status:r.string().refine(e=>Object.values(lr).includes(e)).transform(e=>e).optional(),statusIn:yr.transform(fr).pipe(r.array(mr)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),paymentStatus:mr,paymentChannel:pr},vr=St().router({getCollections:{method:"GET",path:"/",query:gr.collectionURLQueryParams,responses:{200:r.object({results:r.array(gr.collection),total:r.number()}),401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:r.object({id:r.string()}),responses:{200:gr.collection,401:Kt.unauthorizedError,403:Kt.forbiddenError,404:Kt.notFoundError,500:Kt.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:Kt.transactionSummary,401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),br={[lr.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[lr.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[lr.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"},[lr.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"},[lr.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"},[lr.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"}},_r={[hr.AIRTEL]:ar.AIRTEL,[hr.TIGO]:ar.TIGO,[hr.HALOTEL]:ar.HALOTEL,[hr.VODACOM]:ar.VODACOM,[hr.SAFARICOM]:ar.SAFARICOM};class wr{id;status;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";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,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=a.from(e.amount,t)??a.from(0,t),this.serviceFee=e.serviceFee?a.from(parseFloat(e.serviceFee),t)??a.from(0,t):void 0,this.postedAmount=e.postedAmount?a.from(parseFloat(e.postedAmount),t)??a.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 this.status===lr.PENDING_ACK}isSuccessful(){return this.status===lr.PAYMENT_ACCEPTED}isFailed(){return Object.entries(br).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return br[this.status]}getChannelInfo(){return _r[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,Object.values(hr).includes(e);var e}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new wr(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=wr.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(!s.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!s.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!s.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=a.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,n;if(e.serviceFee){const t=a.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue.toString()}if(e.postedAmount){const t=a.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const i={id:e.id,status:e.status,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:r,postedAmount:n,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 wr(i)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=wr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,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 Ir=["id","reference","channel","status"];class Nr extends nr{static create(){return new Nr}static fromFilters(e){return(new Nr).applyFilters(e)}static fromUrlParams(e){try{const t=gr.collectionURLQueryParams.parse(Nr.normalizeUrlParams(e)),r=gr.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:nr.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 Ir){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=fr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",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.whereStatus(lr.PENDING_ACK)}whereSuccessful(){return this.whereStatus(lr.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[lr.PAYMENT_REJECTED,lr.GENERIC_FAILURE,lr.INSUFFICIENT_FUNDS,lr.PROVIDER_FAILED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("reference",e)}wherePartnerReference(e){return this.whereContains("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.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),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.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(`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=fr(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=fr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=fr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=fr(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(hr).some(t=>t===e)}isValidStatus(e){return Object.values(lr).some(t=>t===e)}}class Ar extends Ht{constructor(e){super("collection",vr,e)}async getCollections(e){try{const t=Nr.from(e),r=t.build(),n=await this.client.getCollections({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=wr.createMany(a.results);if(!o)throw new Error("Invalid collection data received from server");return{collections:o,pagination:i}}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=wr.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=Qt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}}var Er,Sr,Cr;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.WALLET_DEBITED="WALLET_DEBITED",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING="PENDING",e.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",e.PENDING_ACK="PENDING_ACK",e.REVERSED="REVERSED",e.INVALID_SERVICE="INVALID_SERVICE",e.INVALID_NUMBER="INVALID_NUMBER",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.THIRDPARTY_FAILED="THIRDPARTY_FAILED",e.PROVIDER_FAILED="PROVIDER_FAILED"}(Er||(Er={})),function(e){e.AIRTEL="TZ-AIRTEL-B2C",e.VODACOM="TZ-VODACOM-B2C",e.TIGO="TZ-TIGO-B2C",e.HALOTEL="TZ-HALOTEL-B2C",e.SAFARICOM="TZ-SAFARICOM-B2C"}(Sr||(Sr={})),function(e){e.BANK="TZ-BANK-B2C"}(Cr||(Cr={}));const Tr=r.enum(Er),Or=r.enum(Sr),Rr=r.enum(Cr),xr=r.union([Or,Rr]),Dr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Dr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},kr=r.union([r.string(),r.array(r.string())]),Pr={payout:r.object({id:r.string().min(1),statusCode:r.string(),statusCodeText:Tr,statusDescription:r.string(),countryCode:r.string(),serviceCode:xr,amount:r.number().min(0),serviceFee:r.string().optional(),postedAmount:r.string().optional(),walletId:r.string().optional(),msisdn:r.string().min(1),narration:r.string(),currencyCode:r.string(),recipientNames:r.string().optional(),transactionRef:r.string(),transactionDate:r.iso.datetime(),externalId:r.string().nullable().optional(),cbaReferenceNo:r.string().optional(),beepTransactionId:r.string().optional(),receiptNumber:r.string().optional(),createdAt:r.iso.datetime(),reversedTransactionId:r.string().nullable().optional(),transactionId:r.string(),serviceFeeTransactionId:r.string().optional(),isReconciled:r.number().optional(),requestId:r.string().optional(),notes:r.string().optional(),updatedAt:r.iso.datetime().optional()}),payoutFilters:r.object({page:r.number().int().positive().default(1),limit:r.number().int().positive().max(5e4).default(20),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.iso.datetime().optional(),endDate:r.iso.datetime().optional(),msisdn:r.string().optional(),accountNo:r.string().optional(),walletId:r.string().optional(),id:r.string().optional(),idIn:r.array(r.string()).optional(),ref:r.string().optional(),refIn:r.array(r.string()).optional(),channelRef:r.string().optional(),channelRefIn:r.array(r.string()).optional(),channel:xr.optional(),channelIn:r.array(xr).optional(),status:Tr.optional(),statusIn:r.array(Tr).optional(),minAmount:r.number().min(0).optional(),maxAmount:r.number().min(0).optional(),search:r.string().optional()}),payoutURLQueryParams:r.object({page:r.string().transform(e=>parseInt(e)||1).optional(),limit:r.string().transform(e=>parseInt(e)||20).optional(),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().optional(),endDate:r.string().optional(),msisdn:r.string().optional(),accountNo:r.string().optional(),walletId:r.string().optional(),id:r.string().optional(),idIn:kr.transform(Dr).optional(),ref:r.string().optional(),refIn:kr.transform(Dr).optional(),channelRef:r.string().optional(),channelRefIn:kr.transform(Dr).optional(),channel:r.string().refine(e=>Object.values(Sr).includes(e)||e===Cr.BANK).transform(e=>e).optional(),channelIn:kr.transform(Dr).pipe(r.array(xr)).optional(),status:r.string().refine(e=>Object.values(Er).includes(e)).transform(e=>e).optional(),statusIn:kr.transform(Dr).pipe(r.array(Tr)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),payoutStatus:Tr,payoutChannel:xr,mobileChannel:Or,bankChannel:Rr,walletSummary:r.object({balance:r.number(),currency:r.string(),lastUpdated:r.iso.datetime()}),transactionSummary:r.object({yesterday:r.number(),today:r.number(),thisMonth:r.number(),lastMonth:r.number()}),pagination:r.object({page:r.number(),limit:r.number(),total:r.number(),totalPages:r.number(),hasNext:r.boolean(),hasPrev:r.boolean()})},Fr=St().router({getPayouts:{method:"GET",path:"",query:Pr.payoutURLQueryParams,responses:{200:r.object({results:r.array(Pr.payout),total:r.number()}),401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:r.object({id:r.string()}),responses:{200:Pr.payout,401:Kt.unauthorizedError,403:Kt.forbiddenError,404:Kt.notFoundError,500:Kt.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:Kt.transactionSummary,401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),Lr={[Er.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[Er.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[Er.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[Er.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"},[Er.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[Er.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"},[Er.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"},[Er.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"},[Er.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"},[Er.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"},[Er.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"},[Er.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"},[Er.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."}},jr={[Sr.AIRTEL]:ar.AIRTEL,[Sr.VODACOM]:ar.VODACOM,[Sr.TIGO]:ar.TIGO,[Sr.HALOTEL]:ar.HALOTEL,[Sr.SAFARICOM]:ar.SAFARICOM};function Mr(e){return Object.values(Sr).includes(e)}function Zr(e){return e===Cr.BANK}class Br{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";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=a.from(e.amount,t)??a.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:a.from(e.serviceFee,t)??a.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?a.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[Er.PENDING,Er.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===Er.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Lr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return Lr[this.statusCodeText]}getChannelInfo(){if(Mr(this.serviceCode))return jr[this.serviceCode];if(Zr(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&i.validateSwiftCode(e)){if(i.getCountryFromSwiftCode(e))try{return o.getInstance().detectBank(e)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&i.getCountryFromSwiftCode(this.swiftCode)){if(i.getCountryFromSwiftCode(this.swiftCode))try{return o.getInstance().detectBank(this.swiftCode)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getAccountNumber(){try{if(Mr(this.serviceCode))return this.msisdn;if(Zr(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 Mr(this.serviceCode)&&e?e.networkOperator:c.is(e)?e.shortName:"Bank Transfer"}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Br(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=Br.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(!s.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!s.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!s.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=a.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let r,n;if(e.serviceFee){const t=a.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);r=t.numericValue}if(e.postedAmount){const t=a.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);n=t.numericValue.toString()}const i={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:r,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:n,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 Br(i)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=Br.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 Ur=["status","channel","id","ref","channelRef"],Vr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class $r extends nr{static create(){return new $r}static fromFilters(e){return(new $r).applyFilters(e)}static fromUrlParams(e){try{const t=Pr.payoutURLQueryParams.parse($r.normalizeUrlParams(e)),r=Pr.payoutFilters.parse(t);return $r.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return $r.fromUrlParams($r.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return $r.fromSearchParams(t)}static from(e){return null==e?new $r:nr.is(e)?new $r(e.options):e instanceof URLSearchParams?$r.fromSearchParams(e):$r.isUrlParamsRecord(e)?$r.fromUrlParams(e):$r.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 Ur){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Dr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}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",[Er.PENDING,Er.PENDING_ACK])}whereSuccessful(){return this.whereStatus(Er.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[Er.PAYMENT_REJECTED,Er.GENERIC_FAILURE,Er.AMOUNT_EXCEED_MAXIMUM,Er.INVALID_SERVICE,Er.INSUFFICIENT_BALANCE,Er.THIRDPARTY_FAILED,Er.WALLET_DEBITED,Er.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(Sr))}whereBank(){return this.whereChannel(Cr.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=Dr(t.value);if(0===r.length)continue;e[`${Vr[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=Dr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Dr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Dr(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(Sr).some(t=>t===e)||e===Cr.BANK}isValidStatus(e){return Object.values(Er).some(t=>t===e)}}class Jr extends Ht{constructor(e){super("payout",Fr,e)}async getPayouts(e){try{const t=$r.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=Br.createMany(a.results);if(!o)throw new Error("Invalid payout data received from server");return{payouts:o,pagination:i}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=$r.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Br.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=Qt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}}var qr,Gr,Wr,zr;!function(e){e.PENDING="PENDING",e.APPROVED="APPROVED",e.REJECTED="REJECTED"}(qr||(qr={})),function(e){e.APPROVED="APPROVED",e.REJECTED="REJECTED"}(Gr||(Gr={})),function(e){e.SUCCESS="SUCCESS",e.WALLET_NOT_FOUND="WALLET_NOT_FOUND",e.INITIATOR_NOT_AUTHORIZED="INITIATOR_NOT_AUTHORIZED",e.MISSING_BANK_DETAILS="MISSING_BANK_DETAILS",e.UNSUPPORTED_BANK_CODE="UNSUPPORTED_BANK_CODE",e.FAILED="FAILED"}(Wr||(Wr={})),function(e){e.SUCCESS="SUCCESS",e.SETTLEMENT_NOT_FOUND="SETTLEMENT_NOT_FOUND",e.ACTIONER_NOT_AUTHORIZED="ACTIONER_NOT_AUTHORIZED",e.SELF_ACTION_NOT_ALLOWED="SELF_ACTION_NOT_ALLOWED",e.INVALID_STATE="INVALID_STATE",e.FAILED="FAILED"}(zr||(zr={}));const Kr=r.enum(qr),Hr=r.enum(Gr),Yr=r.enum(Wr),Qr=r.enum(zr),Xr=r.object({id:r.string().min(1),date:r.string(),initiatedAt:r.string().nullish(),initiatedById:r.string().nullish(),actionedAt:r.string().nullish(),actionedById:r.string().nullish(),vendorId:r.string(),walletId:r.string(),accountNo:r.string(),status:Kr,statusCode:r.string().nullish(),description:r.string(),bankAccountNo:r.string().nullish(),bankAccountName:r.string().nullish(),bankCode:r.string().nullish(),amount:r.number(),payoutId:r.string().nullish(),transactionId:r.string().nullish(),createdAt:r.string(),updatedAt:r.string()}),en=r.object({status:Kr.optional(),accountNo:r.string().optional(),walletId:r.string().optional()}).catchall(r.union([r.string(),r.number()])),tn=r.object({accountNo:r.string().min(1,"Account number is required"),description:r.string().min(1,"Description is required"),amount:r.number().refine(e=>0!==e,"Amount must not be 0")}),rn=r.object({status:Yr,data:Xr.optional()}),nn=r.object({status:Hr}),an=r.object({status:Qr,data:Xr.optional()}),sn={settlement:Xr,settlementStatus:Kr,settlementAction:Hr,settlementFilters:en,createSettlementRequest:tn,createSettlementStatus:Yr,createSettlementResponse:rn,actionSettlementRequest:nn,actionSettlementStatus:Qr,actionSettlementResponse:an},on=St().router({getSettlements:{method:"GET",path:"",query:sn.settlementFilters,responses:{200:r.array(sn.settlement),401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.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:r.object({id:r.string()}),responses:{200:sn.settlement,401:Kt.unauthorizedError,403:Kt.forbiddenError,404:Kt.notFoundError,500:Kt.serverError},summary:"Get settlement details",description:"Retrieve detailed information about a specific settlement"},createSettlement:{method:"POST",path:"",body:sn.createSettlementRequest,responses:{201:sn.createSettlementResponse,400:Kt.validationError,401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.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:r.object({id:r.string()}),body:sn.actionSettlementRequest,responses:{201:sn.actionSettlementResponse,400:Kt.validationError,401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.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"}}),cn={[qr.PENDING]:{label:"Pending",description:"The settlement is awaiting approval",category:"pending",color:"warning",userFriendlyMessage:"Settlement is awaiting approval"},[qr.APPROVED]:{label:"Approved",description:"The settlement has been approved",category:"success",color:"success",userFriendlyMessage:"Settlement was approved"},[qr.REJECTED]:{label:"Rejected",description:"The settlement has been rejected",category:"failed",color:"error",userFriendlyMessage:"Settlement was rejected"}};function un(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}class dn{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=un(e.initiatedAt),this.initiatedById=e.initiatedById,this.actionedAt=un(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=a.from(e.amount,"TZS")??a.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===qr.PENDING}isApproved(){return this.status===qr.APPROVED}isRejected(){return this.status===qr.REJECTED}canBeActioned(){return this.isPending()}getStatusInfo(){return cn[this.status]}static from(e){try{const t=e;return t?.id&&t?.accountNo&&void 0!==t?.amount?new dn(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=dn.from(r);e&&t.push(e)}return t}static fromJSON(e){return dn.from(e)}toJSON(){return{...this._originalData}}}class ln extends Ht{constructor(e){super("settlement",on,e)}async getSettlements(e){const t=await this.client.getSettlements({query:e??{}}),r=this.handleResponse(t,200);return dn.createMany(r)}async getSettlement(e){const t=await this.client.getSettlement({params:{id:e}}),r=this.handleResponse(t,200),n=dn.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?dn.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?dn.from(n.data):void 0}}async approveSettlement(e){return this.actionSettlement(e,Gr.APPROVED)}async rejectSettlement(e){return this.actionSettlement(e,Gr.REJECTED)}}const hn={localTransferRequest:r.object({amount:r.number().int().positive(),from:r.string().min(1),to:r.string().min(1),description:r.string().min(1)}),localTransferResponse:r.object({transactionId:r.string(),from:r.string(),to:r.string(),transactionDate:r.string(),narration:r.string(),amount:r.number(),transactionRef:r.string()})},mn=St().router({localTransfer:{method:"POST",path:"/local-transfer",body:hn.localTransferRequest,responses:{201:hn.localTransferResponse,400:Kt.validationError,401:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});class pn extends Ht{constructor(e){super("transaction",mn,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}}const fn={vendor:r.object({businessName:r.string(),tradeName:r.string(),enableCollections:r.number(),enablePayouts:r.number(),enableRemittance:r.number(),bankAccountNo:r.string().nullish(),bankAccountName:r.string().nullish(),bankCode:r.string().nullish(),enableAutoSettlement:r.number(),disablePaymentApproval:r.number()})},yn=St().router({getMe:{method:"GET",path:"/me",responses:{200:fn.vendor,401:Kt.unauthorizedError,403:Kt.forbiddenError,500:Kt.serverError},summary:"Get vendor profile",description:"Retrieve the vendor profile of the authenticated user, including feature flags and bank details"}});class gn{businessName;tradeName;enableCollections;enablePayouts;enableRemittance;bankAccountNo;bankAccountName;bankCode;enableAutoSettlement;disablePaymentApproval;constructor(e){this.businessName=e.businessName,this.tradeName=e.tradeName,this.enableCollections=e.enableCollections,this.enablePayouts=e.enablePayouts,this.enableRemittance=e.enableRemittance,this.bankAccountNo=e.bankAccountNo,this.bankAccountName=e.bankAccountName,this.bankCode=e.bankCode,this.enableAutoSettlement=e.enableAutoSettlement,this.disablePaymentApproval=e.disablePaymentApproval}isCollectionsEnabled(){return 1===this.enableCollections}isPayoutsEnabled(){return 1===this.enablePayouts}isRemittanceEnabled(){return 1===this.enableRemittance}isAutoSettlementEnabled(){return 1===this.enableAutoSettlement}requiresPaymentApproval(){return 1!==this.disablePaymentApproval}hasBankDetails(){return Boolean(this.bankAccountNo&&this.bankCode)}getDisplayName(){return this.tradeName||this.businessName}static from(e){try{const t=e;return t?.businessName?new gn(t):void console.error("Missing required Vendor fields:",e)}catch(e){return void console.error("Error creating Vendor:",e)}}static fromJson(e){return new gn(e)}toJson(){return{businessName:this.businessName,tradeName:this.tradeName,enableCollections:this.enableCollections,enablePayouts:this.enablePayouts,enableRemittance:this.enableRemittance,bankAccountNo:this.bankAccountNo,bankAccountName:this.bankAccountName,bankCode:this.bankCode,enableAutoSettlement:this.enableAutoSettlement,disablePaymentApproval:this.disablePaymentApproval}}}class vn extends Ht{constructor(e){super("vendor",yn,e)}async getMe(){const e=await this.client.getMe(),t=this.handleResponse(e,200),r=gn.from(t);if(!r)throw new Error("Invalid vendor data received from server");return r}}var bn;function _n(e){switch(e){case"DEFAULT COLLECTION":case bn.COLLECTION:return bn.COLLECTION;case"Vendor":case"DEFAULT DISBURSEMENT":case bn.DISBURSEMENT:return bn.DISBURSEMENT;default:throw new TypeError(`Unsupported wallet type: ${String(e)}`)}}!function(e){e.COLLECTION="COLLECTION",e.DISBURSEMENT="DISBURSEMENT"}(bn||(bn={}));const wn=r.enum(bn),In=r.enum(["Vendor","DEFAULT DISBURSEMENT","DEFAULT COLLECTION","COLLECTION","DISBURSEMENT"]).transform(_n),Nn=r.object({id:r.string().min(1),accountNo:r.string().min(1),accountName:r.string().min(1),shadowAccountNo:r.string().nullish(),externalId:r.string().nullish(),reference:r.string().nullish(),type:In,vendorId:r.string().nullish(),balance:r.number(),minBalance:r.union([r.number(),r.string()]),approvalLimit:r.union([r.number(),r.string()]),currency:r.string().min(1),countryCode:r.string().min(1),createdAt:r.string().min(1),updatedAt:r.string().min(1)}),An=r.object({availableBalance:r.number(),currentBalance:r.number(),accountStatus:r.string().min(1),accountNo:r.string().min(1),accountName:r.string().min(1)}),En={wallet:Nn,walletType:wn,walletPathParams:r.object({accountNo:r.string().min(1)}),walletBalance:An,walletStatementQuery:r.object({startDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},Sn=St().router({listWallets:{method:"GET",path:"",responses:{200:r.array(En.wallet),401:Kt.unauthorizedError,500:Kt.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:r.object({accountNo:r.string().min(1)}),responses:{200:En.wallet,401:Kt.unauthorizedError,500:Kt.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:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.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:r.array(Kt.statementEntry),400:Kt.validationError,401:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class Cn{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){const t=_n(e.type);this._originalData={...e,type:t};let r="TZS";n.isCode(e.currency)?r=e.currency:"KSH"===e.currency&&(r="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=a.from(e.balance,r)??a.from(0,r),this.minBalance=a.from(this.parseAmountValue(e.minBalance),r)??a.from(0,r),this.approvalLimit=a.from(this.parseAmountValue(e.approvalLimit),r)??a.from(0,r),this.currency=r,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===bn.COLLECTION}isDisbursementWallet(){return this.type===bn.DISBURSEMENT}isDefaultWallet(){return!1}static from(e){return new Cn(e)}static createMany(e){const t=[];try{for(const r of e)t.push(Cn.from(r));return t}catch(e){return void console.error("Error creating Wallets:",e)}}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(!s.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!s.getInstance().isAmountJSON(e.minBalance)||!s.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=a.fromJSON(e.balance),r=a.fromJSON(e.minBalance),n=a.fromJSON(e.approvalLimit);return t&&r&&n?new Cn({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:r.numericValue,approvalLimit:n.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)}}}class Tn extends Ht{constructor(e){super("wallet",Sn,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=Cn.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 Cn.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return Xt.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=Yt.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)}}export{zr as ACTION_SETTLEMENT_STATUS,jt as APIError,or as AuthDTOSchemas,dr as AuthRepository,Cr as BANK_PAYOUT_CHANNEL,Ht as BaseRepository,hr as COLLECTION_CHANNEL,lr as COLLECTION_STATUS,br as COLLECTION_STATUS_INFO,Wr as CREATE_SETTLEMENT_STATUS,wr as Collection,gr as CollectionDTOSchemas,Nr as CollectionQuery,Ar as CollectionRepository,Kt as CommonSchemas,er as FilterOperator,Sr as MOBILE_PAYOUT_CHANNEL,ar as MobileChannels,Er as PAYOUT_STATUS,Lr as PAYOUT_STATUS_INFO,Br as Payout,Pr as PayoutDTOSchemas,$r as PayoutQuery,Jr as PayoutRepository,rr as QUERY_BUILDER_TYPE,nr as QueryBuilder,Gr as SETTLEMENT_ACTION,qr as SETTLEMENT_STATUS,cn as SETTLEMENT_STATUS_INFO,dn as Settlement,sn as SettlementDTOSchemas,ln as SettlementRepository,tr as SortDirection,Yt as StatementEntry,hn as TransactionDTOSchemas,pn as TransactionRepository,Qt as TransactionSummary,sr as USER_ROLE,ur as User,gn as Vendor,fn as VendorDTOSchemas,vn as VendorRepository,bn as WALLET_TYPE,Cn as Wallet,En as WalletDTOSchemas,Xt as WalletInfo,Tn as WalletRepository,cr as authContract,vr as collectionContract,fr as collectionToStringArray,_n as normalizeWalletType,Fr as payoutContract,Dr as payoutToStringArray,on as settlementContract,zt as statementEntrySchema,mn as transactionContract,yn as vendorContract,Sn as walletContract};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|