@temboplus/tembo-dashboard 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/lib/status.d.ts +2 -0
- package/dist/lib/status.d.ts.map +1 -1
- package/dist/modules/collection/collection.model.d.ts.map +1 -1
- package/dist/modules/collection/collection.types.d.ts +5 -4
- package/dist/modules/collection/collection.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 s,AmountFactory as a,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 s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,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:s}=e,a=[...r,...s.path||[]],i={...s,path:a};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...s,path:a,message:s.message||o}};function I(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 N{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 b;"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 N.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return b;if("aborted"===s.status)return b;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const b=Object.freeze({status:"aborted"}),E=e=>({status:"dirty",value:e}),_=e=>({status:"valid",value:e}),A=e=>"aborted"===e.status,w=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 R{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 O=(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 D(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=n?n:t.defaultError}:{message:null!=r?r:t.defaultError},description:s}}class P{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 N,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)},s=this._parseSync({data:e,path:n.path,parent:n});return O(n,s)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:h(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(C(n)?n:Promise.resolve(n));return O(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const s=e(t),a=()=>n.addIssue({code:m.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(a(),!1)):!!s||(a(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new be({schema:this,typeName:xe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Ee.create(this,this._def)}nullable(){return _e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this,this._def)}promise(){return Ne.create(this,this._def)}or(e){return ae.create([this,e],this._def)}and(e){return ue.create(this,e,this._def)}transform(e){return new be({...D(this._def),schema:this,typeName:xe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...D(this._def),innerType:this,defaultValue:t,typeName:xe.ZodDefault})}brand(){return new Te({typeName:xe.ZodBranded,type:this,...D(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new we({...D(this._def),innerType:this,catchValue:t,typeName:xe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Re.create(this,e)}readonly(){return Oe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const x=/^c[^\s-]{8,}$/i,k=/^[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,M=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,j=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,U=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,Z=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,B=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||!U.test(e))||!("v6"!==t&&t||!Z.test(e))}class $ extends P{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 I(t,{code:m.invalid_type,expected:l.string,received:t.parsedType}),b}const t=new N;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),I(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),I(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 s=e.data.length>n.value,a=e.data.length<n.value;(s||a)&&(r=this._getOrReturnCtx(e,r),s?I(r,{code:m.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):a&&I(r,{code:m.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)M.test(e.data)||(r=this._getOrReturnCtx(e,r),I(r,{validation:"email",code:m.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)j.test(e.data)||(r=this._getOrReturnCtx(e,r),I(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),I(r,{validation:"uuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),I(r,{validation:"cuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)k.test(e.data)||(r=this._getOrReturnCtx(e,r),I(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),I(r,{validation:"ulid",code:m.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(s){r=this._getOrReturnCtx(e,r),I(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),I(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),I(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),I(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),I(r,{code:m.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){B(n).test(e.data)||(r=this._getOrReturnCtx(e,r),I(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),I(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,s=r>n?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}$.create=e=>{var t;return new $({checks:[],typeName:xe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...D(e)})};class z extends P{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 I(t,{code:m.invalid_type,expected:l.number,received:t.parsedType}),b}let t;const r=new N;for(const n of this._def.checks)if("int"===n.kind)u.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),I(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),I(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),I(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),I(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),I(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 z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:T.toString(n)}]})}_addCheck(e){return new z({...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)}}z.create=e=>new z({checks:[],typeName:xe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...D(e)});class q extends P{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 I(t,{code:m.invalid_type,expected:l.bigint,received:t.parsedType}),b}let t;const r=new N;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),I(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),I(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),I(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 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]})}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}}q.create=e=>{var t;return new q({checks:[],typeName:xe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...D(e)})};class G extends P{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==l.boolean){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.boolean,received:t.parsedType}),b}return _(e.data)}}G.create=e=>new G({typeName:xe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...D(e)});class W extends P{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==l.date){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.date,received:t.parsedType}),b}if(isNaN(e.data.getTime())){return I(this._getOrReturnCtx(e),{code:m.invalid_date}),b}const t=new N;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),I(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),I(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 W({...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}}W.create=e=>new W({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:xe.ZodDate,...D(e)});class K extends P{_parse(e){if(this._getType(e)!==l.symbol){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.symbol,received:t.parsedType}),b}return _(e.data)}}K.create=e=>new K({typeName:xe.ZodSymbol,...D(e)});class Y extends P{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.undefined,received:t.parsedType}),b}return _(e.data)}}Y.create=e=>new Y({typeName:xe.ZodUndefined,...D(e)});class H extends P{_parse(e){if(this._getType(e)!==l.null){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.null,received:t.parsedType}),b}return _(e.data)}}H.create=e=>new H({typeName:xe.ZodNull,...D(e)});class Q extends P{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}}Q.create=e=>new Q({typeName:xe.ZodAny,...D(e)});class X extends P{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}}X.create=e=>new X({typeName:xe.ZodUnknown,...D(e)});class ee extends P{_parse(e){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.never,received:t.parsedType}),b}}ee.create=e=>new ee({typeName:xe.ZodNever,...D(e)});class te extends P{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.void,received:t.parsedType}),b}return _(e.data)}}te.create=e=>new te({typeName:xe.ZodVoid,...D(e)});class re extends P{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==l.array)return I(t,{code:m.invalid_type,expected:l.array,received:t.parsedType}),b;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(I(t,{code:e?m.too_big:m.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(I(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&&(I(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 R(t,e,t.path,r)))).then(e=>N.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new R(t,e,t.path,r)));return N.mergeArray(r,s)}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 se){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ee.create(ne(n))}return new se({...e._def,shape:()=>t})}return e instanceof re?new re({...e._def,type:ne(e.element)}):e instanceof Ee?Ee.create(ne(e.unwrap())):e instanceof _e?_e.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:xe.ZodArray,...D(t)});class se extends P{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 I(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),b}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ee&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||a.push(e);const i=[];for(const e of s){const t=n[e],s=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new R(r,s,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 a)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(I(r,{code:m.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new R(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=>N.mergeObjectSync(t,e)):N.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return T.errToObj,new se({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,a,i;const o=null!==(a=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=T.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new se({...this._def,unknownKeys:"strip"})}passthrough(){return new se({...this._def,unknownKeys:"passthrough"})}extend(e){return new se({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new se({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:xe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new se({...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 se({...this._def,shape:()=>t})}omit(e){const t={};return u.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new se({...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 se({...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 Ee;)e=e._def.innerType;t[r]=e}}),new se({...this._def,shape:()=>t})}keyof(){return ge(u.objectKeys(this.shape))}}se.create=(e,t)=>new se({shape:()=>e,unknownKeys:"strip",catchall:ee.create(),typeName:xe.ZodObject,...D(t)}),se.strictCreate=(e,t)=>new se({shape:()=>e,unknownKeys:"strict",catchall:ee.create(),typeName:xe.ZodObject,...D(t)}),se.lazycreate=(e,t)=>new se({shape:e,unknownKeys:"strip",catchall:ee.create(),typeName:xe.ZodObject,...D(t)});class ae extends P{_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 I(t,{code:m.invalid_union,unionErrors:r}),b});{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map(e=>new p(e));return I(t,{code:m.invalid_union,unionErrors:s}),b}}get options(){return this._def.options}}ae.create=(e,t)=>new ae({options:e,typeName:xe.ZodUnion,...D(t)});const ie=e=>e instanceof fe?ie(e.schema):e instanceof be?ie(e.innerType()):e instanceof ye?[e.value]:e instanceof ve?e.options:e instanceof Ie?Object.keys(e.enum):e instanceof Ae?ie(e._def.innerType):e instanceof Y?[void 0]:e instanceof H?[null]:null;class oe extends P{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.object)return I(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),b;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(I(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),b)}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 s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new oe({typeName:xe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...D(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)),s={...e,...t};for(const r of n){const n=ce(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}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 s=ce(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===l.date&&n===l.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ue extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(A(e)||A(n))return b;const s=ce(e.value,n.value);return s.valid?((w(e)||w(n))&&t.dirty(),{status:t.value,value:s.data}):(I(r,{code:m.invalid_intersection_types}),b)};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:xe.ZodIntersection,...D(r)});class de extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.array)return I(r,{code:m.invalid_type,expected:l.array,received:r.parsedType}),b;if(r.data.length<this._def.items.length)return I(r,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&r.data.length>this._def.items.length&&(I(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 R(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>N.mergeArray(t,e)):N.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:xe.ZodTuple,rest:null,...D(t)})};class le extends P{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 I(r,{code:m.invalid_type,expected:l.object,received:r.parsedType}),b;const n=[],s=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new R(r,e,r.path,e)),value:a._parse(new R(r,r.data[e],r.path,e))});return r.common.async?N.mergeObjectAsync(t,n):N.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new le(t instanceof P?{keyType:e,valueType:t,typeName:xe.ZodRecord,...D(r)}:{keyType:$.create(),valueType:e,typeName:xe.ZodRecord,...D(t)})}}class he extends P{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 I(r,{code:m.invalid_type,expected:l.map,received:r.parsedType}),b;const n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([e,t],a)=>({key:n._parse(new R(r,e,r.path,[a,"key"])),value:s._parse(new R(r,t,r.path,[a,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return b;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return b;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}he.create=(e,t,r)=>new he({valueType:t,keyType:e,typeName:xe.ZodMap,...D(r)});class me extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.set)return I(r,{code:m.invalid_type,expected:l.set,received:r.parsedType}),b;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(I(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&&(I(r,{code:m.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return b;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>s._parse(new R(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>a(e)):a(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:xe.ZodSet,...D(t)});class pe extends P{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.function)return I(t,{code:m.invalid_type,expected:l.function,received:t.parsedType}),b;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 s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Ne){const e=this;return _(async function(...t){const i=new p([]),o=await e._def.args.parseAsync(t,s).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(a,this,o);return await e._def.returns._def.type.parseAsync(c,s).catch(e=>{throw i.addIssue(n(c,e)),i})})}{const e=this;return _(function(...t){const i=e._def.args.safeParse(t,s);if(!i.success)throw new p([r(t,i.error)]);const o=Reflect.apply(a,this,i.data),c=e._def.returns.safeParse(o,s);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:xe.ZodFunction,...D(r)})}}class fe extends P{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:xe.ZodLazy,...D(t)});class ye extends P{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ge(e,t){return new ve({values:e,typeName:xe.ZodEnum,...D(t)})}ye.create=(e,t)=>new ye({value:e,typeName:xe.ZodLiteral,...D(t)});class ve extends P{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return I(t,{expected:u.joinValues(r),received:t.parsedType,code:m.invalid_type}),b}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return I(t,{received:t.data,code:m.invalid_enum_value,options:r}),b}return _(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 Ie extends P{_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 I(r,{expected:u.joinValues(e),received:r.parsedType,code:m.invalid_type}),b}if(-1===t.indexOf(e.data)){const e=u.objectValues(t);return I(r,{received:r.data,code:m.invalid_enum_value,options:e}),b}return _(e.data)}get enum(){return this._def.values}}Ie.create=(e,t)=>new Ie({values:e,typeName:xe.ZodNativeEnum,...D(t)});class Ne extends P{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.promise&&!1===t.common.async)return I(t,{code:m.invalid_type,expected:l.promise,received:t.parsedType}),b;const r=t.parsedType===l.promise?t.data:Promise.resolve(t.data);return _(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:xe.ZodPromise,...D(t)});class be extends P{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{I(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(r.data,s);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,s);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?b:("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?b:("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 a=n.transform(e.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>S(e)?Promise.resolve(n.transform(e.value,s)).then(e=>({status:t.value,value:e})):e)}u.assertNever(n)}}be.create=(e,t,r)=>new be({schema:e,typeName:xe.ZodEffects,effect:t,...D(r)}),be.createWithPreprocess=(e,t,r)=>new be({schema:t,effect:{type:"preprocess",transform:e},typeName:xe.ZodEffects,...D(r)});class Ee extends P{_parse(e){return this._getType(e)===l.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:xe.ZodOptional,...D(t)});class _e extends P{_parse(e){return this._getType(e)===l.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(e,t)=>new _e({innerType:e,typeName:xe.ZodNullable,...D(t)});class Ae extends P{_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:xe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...D(t)});class we extends P{_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}}we.create=(e,t)=>new we({innerType:e,typeName:xe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...D(t)});class Se extends P{_parse(e){if(this._getType(e)!==l.nan){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.nan,received:t.parsedType}),b}return{status:"valid",value:e.data}}}Se.create=e=>new Se({typeName:xe.ZodNaN,...D(e)});const Ce=Symbol("zod_brand");class Te extends P{_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 Re extends P{_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?b:"dirty"===e.status?(t.dirty(),E(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?b:"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 Re({in:e,out:t,typeName:xe.ZodPipeline})}}class Oe extends P{_parse(e){const t=this._def.innerType._parse(e);return S(t)&&(t.value=Object.freeze(t.value)),t}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:xe.ZodReadonly,...D(t)});const De=(e,t={},r)=>e?Q.create().superRefine((n,s)=>{var a,i;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(i=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;s.addIssue({code:"custom",...c,fatal:o})}}):Q.create(),Pe={object:se.lazycreate};var xe;!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"}(xe||(xe={}));const ke=$.create,Fe=z.create,Le=Se.create,Me=q.create,je=G.create,Ue=W.create,Ze=K.create,Be=Y.create,Ve=H.create,$e=Q.create,Je=X.create,ze=ee.create,qe=te.create,Ge=re.create,We=se.create,Ke=se.strictCreate,Ye=ae.create,He=oe.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=me.create,nt=pe.create,st=fe.create,at=ye.create,it=ve.create,ot=Ie.create,ct=Ne.create,ut=be.create,dt=Ee.create,lt=_e.create,ht=be.createWithPreprocess,mt=Re.create,pt={string:e=>$.create({...e,coerce:!0}),number:e=>z.create({...e,coerce:!0}),boolean:e=>G.create({...e,coerce:!0}),bigint:e=>q.create({...e,coerce:!0}),date:e=>W.create({...e,coerce:!0})},ft=b;var yt=Object.freeze({__proto__:null,defaultErrorMap:f,setErrorMap:function(e){y=e},getErrorMap:g,makeIssue:v,EMPTY_PATH:[],addIssueToContext:I,ParseStatus:N,INVALID:b,DIRTY:E,OK:_,isAborted:A,isDirty:w,isValid:S,isAsync:C,get util(){return u},get objectUtil(){return d},ZodParsedType:l,getParsedType:h,ZodType:P,ZodString:$,ZodNumber:z,ZodBigInt:q,ZodBoolean:G,ZodDate:W,ZodSymbol:K,ZodUndefined:Y,ZodNull:H,ZodAny:Q,ZodUnknown:X,ZodNever:ee,ZodVoid:te,ZodArray:re,ZodObject:se,ZodUnion:ae,ZodDiscriminatedUnion:oe,ZodIntersection:ue,ZodTuple:de,ZodRecord:le,ZodMap:he,ZodSet:me,ZodFunction:pe,ZodLazy:fe,ZodLiteral:ye,ZodEnum:ve,ZodNativeEnum:Ie,ZodPromise:Ne,ZodEffects:be,ZodTransformer:be,ZodOptional:Ee,ZodNullable:_e,ZodDefault:Ae,ZodCatch:we,ZodNaN:Se,BRAND:Ce,ZodBranded:Te,ZodPipeline:Re,ZodReadonly:Oe,custom:De,Schema:P,ZodSchema:P,late:Pe,get ZodFirstPartyTypeKind(){return xe},coerce:pt,any:$e,array:Ge,bigint:Me,boolean:je,date:Ue,discriminatedUnion:He,effect:ut,enum:it,function:nt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>De(t=>t instanceof e,t),intersection:Qe,lazy:st,literal:at,map:tt,nan:Le,nativeEnum:ot,never:ze,null:Ve,nullable:lt,number:Fe,object:We,oboolean:()=>je().optional(),onumber:()=>Fe().optional(),optional:dt,ostring:()=>ke().optional(),pipeline:mt,preprocess:ht,promise:ct,record:et,set:rt,strictObject:Ke,string:ke,symbol:Ze,transformer:ut,tuple:Xe,undefined:Be,union:Ye,unknown:Je,void:qe,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 It 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 Nt="zod-ts-rest-polyfill",bt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof se&&t instanceof se){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}},Et=Symbol("ContractNoBody"),_t=e=>"method"in e&&"path"in e,At=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,s,a;return _t(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:bt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(s=r.validateResponseOnClient)&&void 0!==s?s:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,At(r,t)]})),wt=Symbol("ContractPlainType"),St=()=>({router:(e,t)=>At(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>wt,body:()=>wt,type:()=>wt,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>Et}),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=>Rt(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",Rt=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>Rt(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>Rt(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Ot extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const Dt=async({route:e,path:t,method:r,headers:n,body:s,validateResponse:a,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:n,body:s}),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===Et?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:Nt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(n&&(null!=a?a:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const n=t["~standard"].validate(e);if(n instanceof Promise)throw new Error("Schema validation must be synchronous");return n.issues?t["~standard"].vendor===Nt?{error:new p(n.issues)}:{error:new It(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}},Pt=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},xt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),kt=(e,t,r,n,s)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?Ct(e):Tt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,s);return t.endsWith("/")&&a.startsWith("/")?`${t}${a.substring(1)}${i}`:`${t}${a}${i}`},Ft=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const s=((e,t,r)=>{const{query:n,params:s,body:a,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof s?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,String(t)])):{};return{path:kt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:a,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...o,...i}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:s,query:a,extraInputArgs:i,headers:o,fetchOptions:c}=e,u=r.api||Dt,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&xt(d),...xt(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:s,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:s instanceof FormData?s:Pt(s)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof s?s:new URLSearchParams(s)}:null!=s&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(s)})),u({...h,...i})})(s);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new Ot(a,r)}},Lt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>_t(r)?[e,Ft(r,t)]:[e,Lt(r,t)]));class Mt 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 Mt.schema.safeParse(e).success}static unknown(e){return new Mt({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 jt=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()}),Ut=jt.extend({statusCode:t.literal(400)}),Zt=jt.extend({statusCode:t.literal(401)}),Bt=jt.extend({statusCode:t.literal(403)}),Vt=jt.extend({statusCode:t.literal(404)}),$t=jt.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()}),zt=t.object({balance:t.number(),availableBalance:t.number(),accountNumber:t.string(),accountName:t.string()}),qt=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"}`)}}),Wt=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:jt,validationError:Ut,unauthorizedError:Zt,forbiddenError:Bt,notFoundError:Vt,serverError:$t,pagination:Jt,transactionSummary:qt,walletSummary:zt,statementEntry:Wt};class Yt{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){return this.getClientWithHeaders()}getClientWithHeaders(t){const r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",s=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,a={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e()},i={baseUrl:s,baseHeaders:t?{...a,...t}:a};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,s=(t,r)=>new Mt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw s("Bad request","BAD_REQUEST");if(401===e.status)throw s("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw s("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw s("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw s("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw s("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class Ht{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 a=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===a?null:a>0?s.from(a,r)??s.from(0,r):null;const i=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===i?null:i>0?s.from(i,r)??s.from(0,r):null,this.balance=s.from(e.balance,r)??s.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 Ht(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=Ht.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(!a.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!a.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!a.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=s.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=s.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=s.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 Ht(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=Ht.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 s.from(r,t)??s.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 s.from(r,t)??s.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",r=Ht.getTotalCredits(e).numericValue,n=Ht.getTotalDebits(e).numericValue;return s.from(r-n,t)??s.from(0,t)}}class Qt{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=s.from(e.yesterday,t)??s.from(0,t),this.today=s.from(e.today,t)??s.from(0,t),this.thisMonth=s.from(e.thisMonth,t)??s.from(0,t),this.lastMonth=s.from(e.lastMonth,t)??s.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 s.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(!(a.getInstance().isAmountJSON(e.yesterday)&&a.getInstance().isAmountJSON(e.today)&&a.getInstance().isAmountJSON(e.thisMonth)&&a.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=s.fromJSON(e.yesterday),r=s.fromJSON(e.today),n=s.fromJSON(e.thisMonth),i=s.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=s.from(e.availableBalance,t)??s.from(0,t),this.currentBalance=s.from(e.currentBalance,t)??s.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(!a.getInstance().isAmountJSON(e.availableBalance)||!a.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=s.fromJSON(e.availableBalance),r=e.currentBalance??e.actualBalance;if(!a.getInstance().isAmountJSON(r))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const n=s.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)}}var sr,ar;!function(e){e.PENDING_ACK="PENDING_ACK",e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.PAYMENT_FAILED="PAYMENT_FAILED",e.PAYMENT_EXPIRED="PAYMENT_EXPIRED"}(sr||(sr={})),function(e){e.AWAITING_USER="AWAITING_USER",e.PROVIDER_UNCERTAIN="PROVIDER_UNCERTAIN",e.SUCCESS="SUCCESS",e.USER_TIMEOUT="USER_TIMEOUT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.INVALID_NUMBER="INVALID_NUMBER",e.INVALID_PIN="INVALID_PIN",e.ACCOUNT_LOCKED="ACCOUNT_LOCKED",e.ACCOUNT_RESTRICTED="ACCOUNT_RESTRICTED",e.USER_CANCELLED="USER_CANCELLED",e.USER_BUSY="USER_BUSY",e.USER_UNREACHABLE="USER_UNREACHABLE",e.LIMIT_EXCEEDED="LIMIT_EXCEEDED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.PROVIDER_BUSY="PROVIDER_BUSY",e.PROVIDER_ERROR="PROVIDER_ERROR",e.UNKNOWN="UNKNOWN"}(ar||(ar={}));const ir={[sr.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[sr.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[sr.PAYMENT_FAILED]:{label:"Payment Failed",description:"The payment did not go through. See the status code for the reason",category:"failed",color:"error",userFriendlyMessage:"Payment failed. Please try again"},[sr.PAYMENT_EXPIRED]:{label:"Payment Expired",description:"The customer did not respond to the payment prompt in time",category:"failed",color:"error",userFriendlyMessage:"Payment request expired before it was approved"}},or={[ar.AWAITING_USER]:{label:"Awaiting Customer",description:"The prompt was sent and the customer has not responded yet",status:sr.PENDING_ACK,userFriendlyMessage:"Waiting for the customer to approve the payment"},[ar.PROVIDER_UNCERTAIN]:{label:"Outcome Unconfirmed",description:"The outcome is not yet known",status:sr.PENDING_ACK,userFriendlyMessage:"Payment is being confirmed with the provider"},[ar.SUCCESS]:{label:"Success",description:"Payment completed",status:sr.PAYMENT_ACCEPTED,userFriendlyMessage:"Payment received successfully"},[ar.USER_TIMEOUT]:{label:"Customer Timeout",description:"The prompt reached the customer but they did not answer in time",status:sr.PAYMENT_EXPIRED,userFriendlyMessage:"The customer did not approve the payment in time"},[ar.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Not enough money in the customer's wallet",status:sr.PAYMENT_FAILED,userFriendlyMessage:"Insufficient balance to complete the payment"},[ar.INVALID_NUMBER]:{label:"Invalid Number",description:"The phone number is wrong or not registered for mobile money",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The phone number is not registered for mobile money"},[ar.INVALID_PIN]:{label:"Invalid PIN",description:"The customer entered a wrong PIN",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer entered a wrong PIN"},[ar.ACCOUNT_LOCKED]:{label:"Account Locked",description:"Too many wrong PINs. The customer's wallet is locked",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is locked"},[ar.ACCOUNT_RESTRICTED]:{label:"Account Restricted",description:"The wallet is barred, blocked or not activated",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is restricted"},[ar.USER_CANCELLED]:{label:"Cancelled by Customer",description:"The customer declined or cancelled the prompt",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer cancelled the payment"},[ar.USER_BUSY]:{label:"Customer Busy",description:"The customer has another USSD session open",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone was busy with another session"},[ar.USER_UNREACHABLE]:{label:"Customer Unreachable",description:"The prompt could not be delivered (phone off, no network)",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone could not be reached"},[ar.LIMIT_EXCEEDED]:{label:"Limit Exceeded",description:"The customer hit a transaction, daily or wallet limit",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's transaction limit was exceeded"},[ar.INVALID_AMOUNT]:{label:"Invalid Amount",description:"The amount is below the minimum, above the maximum, or badly formatted",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The payment amount is not allowed"},[ar.PROVIDER_BUSY]:{label:"Provider Busy",description:"The mobile money provider is busy",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The mobile money provider is busy"},[ar.PROVIDER_ERROR]:{label:"Provider Error",description:"A system error on TemboPlus's side or the provider's side",status:sr.PAYMENT_FAILED,userFriendlyMessage:"Payment failed due to a system error"},[ar.UNKNOWN]:{label:"Unknown Reason",description:"The payment failed but the reason was not given",status:sr.PAYMENT_FAILED,userFriendlyMessage:"Payment failed for an unknown reason"}};function cr(e){return Object.values(sr).find(t=>t===e)}function ur(e){return Object.values(ar).find(t=>t===e)}function dr(e){if(null!=e&&""!==e)return ur(e)??ar.UNKNOWN}function lr(e){return e.status&&e.statusCode?{status:e.status,statusInfo:e.statusInfo,statusCode:e.statusCode,statusCodeInfo:or[e.statusCode],source:"native"}:e.normalizedStatus?{status:e.normalizedStatus,statusInfo:ir[e.normalizedStatus],statusCode:e.normalizedStatusCode,statusCodeInfo:e.normalizedStatusCode?or[e.normalizedStatusCode]:void 0,source:"normalized"}:{status:e.status,statusInfo:e.statusInfo,source:"legacy"}}const hr={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 mr;!function(e){e.READ_ONLY="ReadOnly",e.ADMIN="Admin",e.INITIATOR="Initiator",e.APPROVER="Approver"}(mr||(mr={}));const pr=r.enum(mr),fr={user:r.object({token:r.string(),identity:r.string(),name:r.string(),role:pr}),userRole:pr,loginRequest:r.object({identity:r.email(),password:r.string()}),updatePassword:r.object({currentPassword:r.string(),newPassword:r.string()})},yr=St().router({login:{method:"POST",path:"/login",body:fr.loginRequest,responses:{201:fr.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:fr.updatePassword,responses:{201:t.object({}),400:Kt.validationError,401:Kt.unauthorizedError,500:Kt.serverError},summary:"Update password",description:"Update user password"}});class gr{identity;name;role;constructor(e){this.identity=e.identity,this.name=e.name,this.role=e.role}static from(e){return new gr(e)}static fromJSON(e){return gr.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 vr extends Yt{constructor(e){super("auth",yr,e)}async login(e){const r=t.object({email:t.email().trim().toLowerCase(),password:t.string().min(1)}).safeParse(e);if(!r.success)throw new Mt({message:"Invalid email or password",statusCode:400});const{email:n,password:s}=r.data,a=await this.client.login({body:{identity:n,password:s}});if(400===a.status||401===a.status)throw new Mt({message:"Invalid email or password",statusCode:a.status});const{token:i,...o}=this.handleResponse(a,201);if(!i)throw new Mt({message:"Authentication token missing from server response",statusCode:500});const c=gr.from(o);if(!c)throw new Mt({message:"Invalid user data received from server",statusCode:500});return{user:c,token:i}}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 Ir,Nr;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.PENDING_ACK="PENDING_ACK",e.PAYMENT_FAILED="PAYMENT_FAILED",e.PAYMENT_EXPIRED="PAYMENT_EXPIRED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.INVALID_REFERENCE="INVALID_REFERENCE",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PENDING="PENDING",e.PROVIDER_FAILED="PROVIDER_FAILED"}(Ir||(Ir={})),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",e.CRDB="TZ-CRDB",e.ECOBANK="TZ-ECOBANK"}(Nr||(Nr={}));const br=r.enum(Ir),Er=r.enum(ar),_r=r.enum(Nr),Ar=e=>{const t=Array.isArray(e)?e.flatMap(e=>Ar(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},wr=r.union([r.string(),r.array(r.string())]),Sr={collection:r.object({id:r.string().min(1),status:br,statusCode:r.unknown().optional().transform(dr),normalizedStatus:r.unknown().optional().transform(cr),normalizedStatusCode:r.unknown().optional().transform(dr),statusMessage:r.string(),accountNo:r.string().min(1),walletId:r.string(),transactionDate:r.iso.datetime(),narration:r.string(),msisdn:r.string().min(1),channel:_r,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:_r.optional(),channelIn:r.array(_r).optional(),status:br.optional(),statusIn:r.array(br).optional(),statusCode:Er.optional(),statusCodeIn:r.array(Er).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:wr.transform(Ar).optional(),reference:r.string().optional(),referenceIn:wr.transform(Ar).optional(),accountNo:r.string().optional(),walletId:r.string().optional(),partnerReference:r.string().optional(),channel:r.string().refine(e=>Object.values(Nr).includes(e)).transform(e=>e).optional(),channelIn:wr.transform(Ar).pipe(r.array(_r)).optional(),status:r.string().refine(e=>Object.values(Ir).includes(e)).transform(e=>e).optional(),statusIn:wr.transform(Ar).pipe(r.array(br)).optional(),statusCode:Er.optional(),statusCodeIn:wr.transform(Ar).pipe(r.array(Er)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),paymentStatus:br,statusCode:Er,paymentChannel:_r},Cr=St().router({getCollections:{method:"GET",path:"/",query:Sr.collectionURLQueryParams,responses:{200:r.object({results:r.array(Sr.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:Sr.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"}}),Tr={...ir,[Ir.PENDING]:{label:"Pending",description:"The payment is pending",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[Ir.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"},[Ir.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"},[Ir.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"},[Ir.INVALID_REFERENCE]:{label:"Invalid Reference",description:"This collection was not found on the provider's side",category:"failed",color:"error",userFriendlyMessage:"Payment could not be found with the provider"},[Ir.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"}},Rr={[Nr.AIRTEL]:hr.AIRTEL,[Nr.TIGO]:hr.TIGO,[Nr.HALOTEL]:hr.HALOTEL,[Nr.VODACOM]:hr.VODACOM,[Nr.SAFARICOM]:hr.SAFARICOM};function Or(e){return Object.entries(Tr).filter(([t,r])=>r.category===e).map(([e])=>e)}class Dr{id;status;statusCode;normalizedStatus;normalizedStatusCode;statusMessage;accountNo;walletId;transactionDate;narration;msisdn;channel;amount;serviceFee;postedAmount;reference;partnerReference;payerName;payerReference;merchantName;merchantReference;transactionId;serviceFeeTransactionId;requestId;completedAt;createdAt;updatedAt;notes;currencyCode;_originalData;constructor(e){this._originalData={...e};let t="TZS";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,this.statusCode=dr(e.statusCode),this.normalizedStatus=cr(e.normalizedStatus),this.normalizedStatusCode=dr(e.normalizedStatusCode),this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=s.from(e.amount,t)??s.from(0,t),this.serviceFee=e.serviceFee?s.from(parseFloat(e.serviceFee),t)??s.from(0,t):void 0,this.postedAmount=e.postedAmount?s.from(parseFloat(e.postedAmount),t)??s.from(0,t):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.payerName=e.payerName,this.payerReference=e.payerReference,this.merchantName=e.merchantName,this.merchantReference=e.merchantReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return"pending"===Tr[this.status]?.category}isSuccessful(){return this.status===Ir.PAYMENT_ACCEPTED}isFailed(){return"failed"===Tr[this.status]?.category}isExpired(){return this.status===Ir.PAYMENT_EXPIRED}isFinal(){return this.isSuccessful()||this.isFailed()}getStatusInfo(){return Tr[this.status]}getStatusCode(){return this.statusCode}getStatusCodeInfo(){return this.statusCode?or[this.statusCode]:void 0}getDisplayStatus(){return lr({status:this.status,statusInfo:Tr[this.status],statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode})}getChannelInfo(){return Rr[this.channel]}getProviderName(){return this.getChannelInfo()?.networkOperator}getServiceName(){return this.getChannelInfo()?.serviceName}isMobileCollection(){return this.channel in Rr}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Dr(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=Dr.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(!a.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!a.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!a.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=s.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=s.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=s.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,statusCode:e.statusCode,normalizedStatus:e.normalizedStatus,normalizedStatusCode:e.normalizedStatusCode,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee: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 Dr(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=Dr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJSON(),serviceFee:this.serviceFee?.toJSON(),postedAmount:this.postedAmount?.toJSON(),reference:this.reference,partnerReference:this.partnerReference,payerName:this.payerName,payerReference:this.payerReference,merchantName:this.merchantName,merchantReference:this.merchantReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:this.completedAt?.toISOString()??null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}const Pr=["id","reference","channel","status","statusCode"];class xr extends nr{static create(){return new xr}static fromFilters(e){return(new xr).applyFilters(e)}static fromUrlParams(e){try{const t=Sr.collectionURLQueryParams.parse(xr.normalizeUrlParams(e)),r=Sr.collectionFilters.parse(t);return xr.fromFilters(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return xr.fromUrlParams(xr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return xr.fromSearchParams(t)}static from(e){try{return null==e?new xr:nr.is(e)?new xr(e.options):e instanceof URLSearchParams?xr.fromSearchParams(e):xr.isUrlParamsRecord(e)?xr.fromUrlParams(e):xr.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 Pr){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,i=`${e}In[]`,o=t[r],c=Ar([t[n],t[s],t[a],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[s],delete t[a],delete t[i]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereStatusCode(e){return this.where("statusCode",e)}whereStatusCodeIn(e){return this.whereInValues("statusCode",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}whereIdIn(e){return this.whereInValues("id",e)}whereReferenceIn(e){return this.whereInValues("reference",e)}wherePending(){return this.whereStatusIn(Or("pending"))}whereSuccessful(){return this.whereStatus(Ir.PAYMENT_ACCEPTED)}whereFailed(){return this.whereStatusIn(Or("failed"))}whereExpired(){return this.whereStatus(Ir.PAYMENT_EXPIRED)}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("reference",e)}wherePartnerReference(e){return this.where("partnerReference",e)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.statusCodeIn?.length?this.whereStatusCodeIn(e.statusCodeIn):e.statusCode&&this.whereStatusCode(e.statusCode),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.referenceIn?.length?this.whereReferenceIn(e.referenceIn):e.reference&&this.whereReference(e.reference),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,id:e.id,idIn:e.idIn,reference:e.reference,referenceIn:e.referenceIn,accountNo:e.accountNo,walletId:e.walletId,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),statusCode:this.isValidStatusCode(e.statusCode)?e.statusCode:void 0,statusCodeIn:this.getValidStatusCodes(e.statusCodeIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.idIn?.length||e.reference||e.referenceIn?.length||e.accountNo||e.walletId||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.statusCode||e.statusCodeIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.statusCodeIn?.length?e.push(`Reason: ${t.statusCodeIn.join(", ")}`):t.statusCode&&e.push(`Reason: ${t.statusCode}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.referenceIn?.length?e.push(`Reference: ${t.referenceIn.join(", ")}`):t.reference&&e.push(`Reference: ${t.reference}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=Ar(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=Ar(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Ar(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidStatusCodes(e){const t=Ar(e).filter(e=>this.isValidStatusCode(e));return t.length>0?t:void 0}getValidChannels(e){const t=Ar(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(Nr).some(t=>t===e)}isValidStatus(e){return Object.values(Ir).some(t=>t===e)}isValidStatusCode(e){return Object.values(ar).some(t=>t===e)}}class kr extends Yt{constructor(e){super("collection",Cr,e)}async getCollections(e){try{const t=xr.from(e),r=t.build(),n=await this.client.getCollections({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),i={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},o=Dr.createMany(s.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=xr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=Dr.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 Fr,Lr,Mr;!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"}(Fr||(Fr={})),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"}(Lr||(Lr={})),function(e){e.BANK="TZ-BANK-B2C"}(Mr||(Mr={}));const jr=r.enum(Fr),Ur=r.enum(Lr),Zr=r.enum(Mr),Br=r.union([Ur,Zr]),Vr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Vr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},$r=r.union([r.string(),r.array(r.string())]),Jr={payout:r.object({id:r.string().min(1),statusCode:r.string().optional(),statusCodeText:jr,normalizedStatus:r.unknown().optional().transform(cr),normalizedStatusCode:r.unknown().optional().transform(dr),statusDescription:r.string(),countryCode:r.string(),serviceCode:Br,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:Br.optional(),channelIn:r.array(Br).optional(),status:jr.optional(),statusIn:r.array(jr).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:$r.transform(Vr).optional(),ref:r.string().optional(),refIn:$r.transform(Vr).optional(),channelRef:r.string().optional(),channelRefIn:$r.transform(Vr).optional(),channel:r.string().refine(e=>Object.values(Lr).includes(e)||e===Mr.BANK).transform(e=>e).optional(),channelIn:$r.transform(Vr).pipe(r.array(Br)).optional(),status:r.string().refine(e=>Object.values(Fr).includes(e)).transform(e=>e).optional(),statusIn:$r.transform(Vr).pipe(r.array(jr)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),payoutStatus:jr,payoutChannel:Br,mobileChannel:Ur,bankChannel:Zr,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()})},zr=St().router({getPayouts:{method:"GET",path:"",query:Jr.payoutURLQueryParams,responses:{200:r.object({results:r.array(Jr.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:Jr.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"}}),qr={[Fr.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[Fr.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[Fr.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[Fr.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"},[Fr.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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."}},Gr={[Lr.AIRTEL]:hr.AIRTEL,[Lr.VODACOM]:hr.VODACOM,[Lr.TIGO]:hr.TIGO,[Lr.HALOTEL]:hr.HALOTEL,[Lr.SAFARICOM]:hr.SAFARICOM};function Wr(e){return Object.values(Lr).includes(e)}function Kr(e){return e===Mr.BANK}class Yr{id;serviceCode;msisdn;amount;transactionDate;statusDescription;statusCodeText;transactionId;transactionRef;recipientNames;narration;serviceFee;notes;swiftCode;createdAt;updatedAt;statusCode;normalizedStatus;normalizedStatusCode;countryCode;postedAmount;walletId;currencyCode;externalId;cbaReferenceNo;beepTransactionId;receiptNumber;reversedTransactionId;serviceFeeTransactionId;isReconciled;requestId;_originalData;constructor(e){this._originalData={...e};let t="TZS";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=s.from(e.amount,t)??s.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:s.from(e.serviceFee,t)??s.from(0,t),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=e.updatedAt?new Date(e.updatedAt):void 0,this.statusCode=e.statusCode,this.normalizedStatus=cr(e.normalizedStatus),this.normalizedStatusCode=dr(e.normalizedStatusCode),this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?s.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[Fr.PENDING,Fr.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===Fr.PAYMENT_ACCEPTED}isFailed(){return Object.entries(qr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return qr[this.statusCodeText]}getDisplayStatus(){return lr({status:this.statusCodeText,statusInfo:qr[this.statusCodeText],statusCode:ur(this.statusCode),normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode})}getChannelInfo(){if(Wr(this.serviceCode))return Gr[this.serviceCode];if(Kr(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(Wr(this.serviceCode))return this.msisdn;if(Kr(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 Wr(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 Yr(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=Yr.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(!a.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!a.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!a.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=s.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=s.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=s.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,normalizedStatus:e.normalizedStatus,normalizedStatusCode:e.normalizedStatusCode,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 Yr(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=Yr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJSON(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:this.serviceFee?.toJSON(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt?.toISOString(),statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode,countryCode:this.countryCode,postedAmount:this.postedAmount?.toJSON(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}const Hr=["status","channel","id","ref","channelRef"],Qr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class Xr extends nr{static create(){return new Xr}static fromFilters(e){return(new Xr).applyFilters(e)}static fromUrlParams(e){try{const t=Jr.payoutURLQueryParams.parse(Xr.normalizeUrlParams(e)),r=Jr.payoutFilters.parse(t);return Xr.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Xr.fromUrlParams(Xr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Xr.fromSearchParams(t)}static from(e){return null==e?new Xr:nr.is(e)?new Xr(e.options):e instanceof URLSearchParams?Xr.fromSearchParams(e):Xr.isUrlParamsRecord(e)?Xr.fromUrlParams(e):Xr.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 Hr){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,i=`${e}In[]`,o=t[r],c=Vr([t[n],t[s],t[a],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[s],delete t[a],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",[Fr.PENDING,Fr.PENDING_ACK])}whereSuccessful(){return this.whereStatus(Fr.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[Fr.PAYMENT_REJECTED,Fr.GENERIC_FAILURE,Fr.AMOUNT_EXCEED_MAXIMUM,Fr.INVALID_SERVICE,Fr.INSUFFICIENT_BALANCE,Fr.THIRDPARTY_FAILED,Fr.WALLET_DEBITED,Fr.REVERSED])}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(Lr))}whereBank(){return this.whereChannel(Mr.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=Vr(t.value);if(0===r.length)continue;e[`${Qr[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=Vr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Vr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Vr(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(Lr).some(t=>t===e)||e===Mr.BANK}isValidStatus(e){return Object.values(Fr).some(t=>t===e)}}class en extends Yt{constructor(e){super("payout",zr,e)}async getPayouts(e){try{const t=Xr.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),i={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},o=Yr.createMany(s.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=Xr.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Yr.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 tn,rn,nn,sn;!function(e){e.PENDING="PENDING",e.APPROVED="APPROVED",e.PROCESSING="PROCESSING",e.PROCESSED="PROCESSED",e.REJECTED="REJECTED"}(tn||(tn={})),function(e){e.APPROVED="APPROVED",e.REJECTED="REJECTED"}(rn||(rn={})),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"}(nn||(nn={})),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"}(sn||(sn={}));const an=r.enum(tn),on=r.enum(rn),cn=r.enum(nn),un=r.enum(sn),dn=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:an,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()}),ln=r.object({status:an.optional(),amount:r.number().optional(),accountNo:r.string().optional()}),hn=r.object({status:an.optional(),amount:r.coerce.number().optional(),accountNo:r.string().optional()}),mn=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")}),pn=r.object({status:cn,data:dn.optional()}),fn=r.object({status:on}),yn=r.object({status:un,data:dn.optional()}),gn={settlement:dn,settlementStatus:an,settlementAction:on,settlementFilters:ln,settlementURLQueryParams:hn,createSettlementRequest:mn,createSettlementStatus:cn,createSettlementResponse:pn,actionSettlementRequest:fn,actionSettlementStatus:un,actionSettlementResponse:yn},vn=St().router({getSettlements:{method:"GET",path:"",query:gn.settlementFilters,responses:{200:r.array(gn.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:gn.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:gn.createSettlementRequest,responses:{201:gn.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:gn.actionSettlementRequest,responses:{201:gn.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"}}),In={[tn.PENDING]:{label:"Pending",description:"Pending approval or rejection",category:"pending",color:"warning",userFriendlyMessage:"Settlement is awaiting approval"},[tn.APPROVED]:{label:"Approved",description:"Approved by an admin or approver",category:"success",color:"success",userFriendlyMessage:"Settlement was approved"},[tn.PROCESSING]:{label:"Processing",description:"Approved and being processed to the settlement bank account",category:"processing",color:"info",userFriendlyMessage:"Settlement is being processed to your bank account"},[tn.PROCESSED]:{label:"Processed",description:"Approved and processed successfully",category:"success",color:"success",userFriendlyMessage:"Settlement was processed successfully"},[tn.REJECTED]:{label:"Rejected",description:"Rejected by an admin or approver",category:"failed",color:"error",userFriendlyMessage:"Settlement was rejected"}};function Nn(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}class bn{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=Nn(e.initiatedAt),this.initiatedById=e.initiatedById,this.actionedAt=Nn(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=s.from(e.amount,"TZS")??s.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===tn.PENDING}isApproved(){return this.status===tn.APPROVED}isProcessing(){return this.status===tn.PROCESSING}isProcessed(){return this.status===tn.PROCESSED}isRejected(){return this.status===tn.REJECTED}canBeActioned(){return this.isPending()}getStatusInfo(){return In[this.status]}static from(e){try{const t=e;return t?.id&&t?.accountNo&&void 0!==t?.amount?new bn(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=bn.from(r);e&&t.push(e)}return t}static fromJSON(e){return bn.from(e)}toJSON(){return{...this._originalData}}}class En{filters;constructor(e={}){this.filters={...e}}static create(){return new En}static fromFilters(e){return new En(gn.settlementFilters.parse(e))}static fromUrlParams(e){try{const t=En.flattenParams(e),r=gn.settlementURLQueryParams.parse(t);return new En(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return En.fromUrlParams(En.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return En.fromSearchParams(t)}static from(e){try{return null==e?new En:En.is(e)?e.clone():e instanceof URLSearchParams?En.fromSearchParams(e):En.isUrlParamsRecord(e)?En.fromUrlParams(e):En.fromFilters(e)}catch(e){throw console.log(e),new Error("Invalid input! Could not create a SettlementQuery instance.")}}static is(e){return e instanceof En}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static flattenParams(e){const t=["status","amount","accountNo"],r={};for(const n of t){const t=e[n],s=(Array.isArray(t)?t[0]:t)?.trim();s&&(r[n]=s)}return r}whereStatus(e){return this.filters.status=e,this}whereAmount(e){return this.filters.amount=e,this}whereAccountNo(e){return this.filters.accountNo=e,this}wherePending(){return this.whereStatus(tn.PENDING)}whereApproved(){return this.whereStatus(tn.APPROVED)}whereProcessing(){return this.whereStatus(tn.PROCESSING)}whereProcessed(){return this.whereStatus(tn.PROCESSED)}whereRejected(){return this.whereStatus(tn.REJECTED)}clone(){return new En(this.filters)}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withAmount(e){const t=this.clone();return void 0!==e&&t.whereAmount(e),t}withAccountNo(e){const t=this.clone();return e&&t.whereAccountNo(e),t}toFilters(){const e={};return void 0!==this.filters.status&&(e.status=this.filters.status),void 0!==this.filters.amount&&(e.amount=this.filters.amount),void 0!==this.filters.accountNo&&(e.accountNo=this.filters.accountNo),e}build(){return this.toFilters()}toUrlParams(){const e=this.toFilters(),t={};for(const[r,n]of Object.entries(e))null!=n&&(t[r]=String(n));return t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}hasFilters(){const e=this.toFilters();return void 0!==e.status||void 0!==e.amount||void 0!==e.accountNo}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),void 0!==t.amount&&e.push(`Amount: ${t.amount}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),e}}class _n extends Yt{constructor(e){super("settlement",vn,e)}async getSettlements(e){const t=En.from(e),r=await this.client.getSettlements({query:t.build()}),n=this.handleResponse(r,200);return bn.createMany(n)}async getSettlementsFromRequest(e){return this.getSettlements(En.fromRequest(e))}async getSettlement(e){const t=await this.client.getSettlement({params:{id:e}}),r=this.handleResponse(t,200),n=bn.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?bn.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?bn.from(n.data):void 0}}async approveSettlement(e){return this.actionSettlement(e,rn.APPROVED)}async rejectSettlement(e){return this.actionSettlement(e,rn.REJECTED)}}const An={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()})},wn=St().router({localTransfer:{method:"POST",path:"/local-transfer",body:An.localTransferRequest,responses:{201:An.localTransferResponse,400:Kt.validationError,401:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});class Sn extends Yt{constructor(e){super("transaction",wn,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}}const Cn={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()})},Tn=St().router({getMe:{method:"GET",path:"/me",responses:{200:Cn.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 Rn{businessName;tradeName;canCollect;canPayout;canRemit;automatedSettlements;disabledPaymentApproval;settlementAccount;constructor(e){this.businessName=e.businessName,this.tradeName=e.tradeName,this.canCollect=e.canCollect,this.canPayout=e.canPayout,this.canRemit=e.canRemit,this.automatedSettlements=e.automatedSettlements,this.disabledPaymentApproval=e.disabledPaymentApproval,this.settlementAccount=e.settlementAccount}hasSettlementAccount(){return null!==this.settlementAccount}getDisplayName(){return this.tradeName||this.businessName}static from(e){try{const t=e;if(!t?.businessName)return void console.error("Missing required Vendor fields:",e);const r=t,n=r.bankCode?c.fromBIC(r.bankCode):void 0,s=n&&r.bankAccountName&&r.bankAccountNo?{accountName:r.bankAccountName,accountNo:r.bankAccountNo,bank:n}:null;return new Rn({businessName:r.businessName,tradeName:r.tradeName,canCollect:1===r.enableCollections,canPayout:1===r.enablePayouts,canRemit:1===r.enableRemittance,automatedSettlements:1===r.enableAutoSettlement,disabledPaymentApproval:1===r.disablePaymentApproval,settlementAccount:s})}catch(e){return void console.error("Error creating Vendor:",e)}}static fromJSON(e){let t=null;if(e.settlementAccount){const r=c.fromJSON(e.settlementAccount.bank);r&&(t={accountName:e.settlementAccount.accountName,accountNo:e.settlementAccount.accountNo,bank:r})}return new Rn({...e,settlementAccount:t})}toJSON(){return{businessName:this.businessName,tradeName:this.tradeName,canCollect:this.canCollect,canPayout:this.canPayout,canRemit:this.canRemit,automatedSettlements:this.automatedSettlements,disabledPaymentApproval:this.disabledPaymentApproval,settlementAccount:this.settlementAccount?{accountName:this.settlementAccount.accountName,accountNo:this.settlementAccount.accountNo,bank:this.settlementAccount.bank.toJSON()}:null}}}class On extends Yt{constructor(e){super("vendor",Tn,e)}async getMe(){const e=await this.client.getMe(),t=this.handleResponse(e,200),r=Rn.from(t);if(!r)throw new Error("Invalid vendor data received from server");return r}}var Dn;function Pn(e){switch(e){case"DEFAULT COLLECTION":case Dn.COLLECTION:return Dn.COLLECTION;case"Vendor":case"DEFAULT DISBURSEMENT":case Dn.DISBURSEMENT:return Dn.DISBURSEMENT;default:throw new TypeError(`Unsupported wallet type: ${String(e)}`)}}!function(e){e.COLLECTION="COLLECTION",e.DISBURSEMENT="DISBURSEMENT"}(Dn||(Dn={}));const xn=r.enum(Dn),kn=r.enum(["Vendor","DEFAULT DISBURSEMENT","DEFAULT COLLECTION","COLLECTION","DISBURSEMENT"]).transform(Pn),Fn=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:kn,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)}),Ln=r.object({availableBalance:r.number(),currentBalance:r.number(),accountStatus:r.string().min(1),accountNo:r.string().min(1),accountName:r.string().min(1)}),Mn={wallet:Fn,walletType:xn,walletPathParams:r.object({accountNo:r.string().min(1)}),walletBalance:Ln,walletStatementQuery:r.object({startDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},jn=St().router({listWallets:{method:"GET",path:"",responses:{200:r.array(Mn.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:Mn.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:Mn.walletPathParams,responses:{200:Mn.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:Mn.walletPathParams,query:Mn.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 Un{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){const t=Pn(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=s.from(e.balance,r)??s.from(0,r),this.minBalance=s.from(this.parseAmountValue(e.minBalance),r)??s.from(0,r),this.approvalLimit=s.from(this.parseAmountValue(e.approvalLimit),r)??s.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===Dn.COLLECTION}isDisbursementWallet(){return this.type===Dn.DISBURSEMENT}isDefaultWallet(){return!1}static from(e){return new Un(e)}static createMany(e){const t=[];for(const r of e)try{t.push(Un.from(r))}catch(e){console.warn("Skipping unsupported wallet:",e)}return t}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!a.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!a.getInstance().isAmountJSON(e.minBalance)||!a.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=s.fromJSON(e.balance),r=s.fromJSON(e.minBalance),n=s.fromJSON(e.approvalLimit);return t&&r&&n?new Un({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 Zn extends Yt{constructor(e){super("wallet",jn,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=Un.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 Un.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=Ht.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{sn as ACTION_SETTLEMENT_STATUS,Mt as APIError,fr as AuthDTOSchemas,vr as AuthRepository,Mr as BANK_PAYOUT_CHANNEL,Yt as BaseRepository,Nr as COLLECTION_CHANNEL,Ir as COLLECTION_STATUS,ar as COLLECTION_STATUS_CODE,or as COLLECTION_STATUS_CODE_INFO,Tr as COLLECTION_STATUS_INFO,nn as CREATE_SETTLEMENT_STATUS,Dr as Collection,Sr as CollectionDTOSchemas,xr as CollectionQuery,kr as CollectionRepository,Kt as CommonSchemas,er as FilterOperator,Lr as MOBILE_PAYOUT_CHANNEL,hr as MobileChannels,sr as NORMALIZED_STATUS,ar as NORMALIZED_STATUS_CODE,or as NORMALIZED_STATUS_CODE_INFO,ir as NORMALIZED_STATUS_INFO,Fr as PAYOUT_STATUS,qr as PAYOUT_STATUS_INFO,Yr as Payout,Jr as PayoutDTOSchemas,Xr as PayoutQuery,en as PayoutRepository,rr as QUERY_BUILDER_TYPE,nr as QueryBuilder,rn as SETTLEMENT_ACTION,tn as SETTLEMENT_STATUS,In as SETTLEMENT_STATUS_INFO,bn as Settlement,gn as SettlementDTOSchemas,En as SettlementQuery,_n as SettlementRepository,tr as SortDirection,Ht as StatementEntry,An as TransactionDTOSchemas,Sn as TransactionRepository,Qt as TransactionSummary,mr as USER_ROLE,gr as User,Rn as Vendor,Cn as VendorDTOSchemas,On as VendorRepository,Dn as WALLET_TYPE,Un as Wallet,Mn as WalletDTOSchemas,Xt as WalletInfo,Zn as WalletRepository,cr as asNormalizedStatus,ur as asNormalizedStatusCode,yr as authContract,Cr as collectionContract,Ar as collectionToStringArray,Or as getCollectionStatusesByCategory,Pn as normalizeWalletType,zr as payoutContract,Vr as payoutToStringArray,lr as resolveDisplayStatus,vn as settlementContract,Wt as statementEntrySchema,dr as toCollectionStatusCode,dr as toNormalizedStatusCode,wn as transactionContract,Tn as vendorContract,jn as walletContract};
|
|
1
|
+
import{v4 as e}from"uuid";import t,{z as r}from"zod";import{CurrencyHelpers as n,Amount as s,AmountFactory as a,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 s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,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:s}=e,a=[...r,...s.path||[]],i={...s,path:a};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...s,path:a,message:s.message||o}};function I(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 N{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 b;"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 N.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return b;if("aborted"===s.status)return b;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const b=Object.freeze({status:"aborted"}),E=e=>({status:"dirty",value:e}),_=e=>({status:"valid",value:e}),A=e=>"aborted"===e.status,w=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 R{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 O=(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 D(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=n?n:t.defaultError}:{message:null!=r?r:t.defaultError},description:s}}class P{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 N,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)},s=this._parseSync({data:e,path:n.path,parent:n});return O(n,s)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:h(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(C(n)?n:Promise.resolve(n));return O(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const s=e(t),a=()=>n.addIssue({code:m.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(a(),!1)):!!s||(a(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new be({schema:this,typeName:xe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Ee.create(this,this._def)}nullable(){return _e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this,this._def)}promise(){return Ne.create(this,this._def)}or(e){return ae.create([this,e],this._def)}and(e){return ue.create(this,e,this._def)}transform(e){return new be({...D(this._def),schema:this,typeName:xe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...D(this._def),innerType:this,defaultValue:t,typeName:xe.ZodDefault})}brand(){return new Te({typeName:xe.ZodBranded,type:this,...D(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new we({...D(this._def),innerType:this,catchValue:t,typeName:xe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Re.create(this,e)}readonly(){return Oe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const x=/^c[^\s-]{8,}$/i,k=/^[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,M=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,j=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,U=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,Z=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,B=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||!U.test(e))||!("v6"!==t&&t||!Z.test(e))}class $ extends P{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 I(t,{code:m.invalid_type,expected:l.string,received:t.parsedType}),b}const t=new N;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),I(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),I(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 s=e.data.length>n.value,a=e.data.length<n.value;(s||a)&&(r=this._getOrReturnCtx(e,r),s?I(r,{code:m.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):a&&I(r,{code:m.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)M.test(e.data)||(r=this._getOrReturnCtx(e,r),I(r,{validation:"email",code:m.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)j.test(e.data)||(r=this._getOrReturnCtx(e,r),I(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),I(r,{validation:"uuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),I(r,{validation:"cuid",code:m.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)k.test(e.data)||(r=this._getOrReturnCtx(e,r),I(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),I(r,{validation:"ulid",code:m.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(s){r=this._getOrReturnCtx(e,r),I(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),I(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),I(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),I(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),I(r,{code:m.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){B(n).test(e.data)||(r=this._getOrReturnCtx(e,r),I(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),I(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,s=r>n?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}$.create=e=>{var t;return new $({checks:[],typeName:xe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...D(e)})};class z extends P{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 I(t,{code:m.invalid_type,expected:l.number,received:t.parsedType}),b}let t;const r=new N;for(const n of this._def.checks)if("int"===n.kind)u.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),I(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),I(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),I(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),I(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),I(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 z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:T.toString(n)}]})}_addCheck(e){return new z({...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)}}z.create=e=>new z({checks:[],typeName:xe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...D(e)});class q extends P{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 I(t,{code:m.invalid_type,expected:l.bigint,received:t.parsedType}),b}let t;const r=new N;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),I(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),I(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),I(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 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]})}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}}q.create=e=>{var t;return new q({checks:[],typeName:xe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...D(e)})};class G extends P{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==l.boolean){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.boolean,received:t.parsedType}),b}return _(e.data)}}G.create=e=>new G({typeName:xe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...D(e)});class W extends P{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==l.date){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.date,received:t.parsedType}),b}if(isNaN(e.data.getTime())){return I(this._getOrReturnCtx(e),{code:m.invalid_date}),b}const t=new N;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),I(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),I(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 W({...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}}W.create=e=>new W({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:xe.ZodDate,...D(e)});class K extends P{_parse(e){if(this._getType(e)!==l.symbol){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.symbol,received:t.parsedType}),b}return _(e.data)}}K.create=e=>new K({typeName:xe.ZodSymbol,...D(e)});class Y extends P{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.undefined,received:t.parsedType}),b}return _(e.data)}}Y.create=e=>new Y({typeName:xe.ZodUndefined,...D(e)});class H extends P{_parse(e){if(this._getType(e)!==l.null){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.null,received:t.parsedType}),b}return _(e.data)}}H.create=e=>new H({typeName:xe.ZodNull,...D(e)});class Q extends P{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}}Q.create=e=>new Q({typeName:xe.ZodAny,...D(e)});class X extends P{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}}X.create=e=>new X({typeName:xe.ZodUnknown,...D(e)});class ee extends P{_parse(e){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.never,received:t.parsedType}),b}}ee.create=e=>new ee({typeName:xe.ZodNever,...D(e)});class te extends P{_parse(e){if(this._getType(e)!==l.undefined){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.void,received:t.parsedType}),b}return _(e.data)}}te.create=e=>new te({typeName:xe.ZodVoid,...D(e)});class re extends P{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==l.array)return I(t,{code:m.invalid_type,expected:l.array,received:t.parsedType}),b;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(I(t,{code:e?m.too_big:m.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(I(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&&(I(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 R(t,e,t.path,r)))).then(e=>N.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new R(t,e,t.path,r)));return N.mergeArray(r,s)}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 se){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ee.create(ne(n))}return new se({...e._def,shape:()=>t})}return e instanceof re?new re({...e._def,type:ne(e.element)}):e instanceof Ee?Ee.create(ne(e.unwrap())):e instanceof _e?_e.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:xe.ZodArray,...D(t)});class se extends P{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 I(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),b}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ee&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||a.push(e);const i=[];for(const e of s){const t=n[e],s=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new R(r,s,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 a)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(I(r,{code:m.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new R(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=>N.mergeObjectSync(t,e)):N.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return T.errToObj,new se({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,a,i;const o=null!==(a=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=T.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new se({...this._def,unknownKeys:"strip"})}passthrough(){return new se({...this._def,unknownKeys:"passthrough"})}extend(e){return new se({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new se({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:xe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new se({...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 se({...this._def,shape:()=>t})}omit(e){const t={};return u.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new se({...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 se({...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 Ee;)e=e._def.innerType;t[r]=e}}),new se({...this._def,shape:()=>t})}keyof(){return ge(u.objectKeys(this.shape))}}se.create=(e,t)=>new se({shape:()=>e,unknownKeys:"strip",catchall:ee.create(),typeName:xe.ZodObject,...D(t)}),se.strictCreate=(e,t)=>new se({shape:()=>e,unknownKeys:"strict",catchall:ee.create(),typeName:xe.ZodObject,...D(t)}),se.lazycreate=(e,t)=>new se({shape:e,unknownKeys:"strip",catchall:ee.create(),typeName:xe.ZodObject,...D(t)});class ae extends P{_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 I(t,{code:m.invalid_union,unionErrors:r}),b});{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map(e=>new p(e));return I(t,{code:m.invalid_union,unionErrors:s}),b}}get options(){return this._def.options}}ae.create=(e,t)=>new ae({options:e,typeName:xe.ZodUnion,...D(t)});const ie=e=>e instanceof fe?ie(e.schema):e instanceof be?ie(e.innerType()):e instanceof ye?[e.value]:e instanceof ve?e.options:e instanceof Ie?Object.keys(e.enum):e instanceof Ae?ie(e._def.innerType):e instanceof Y?[void 0]:e instanceof H?[null]:null;class oe extends P{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.object)return I(t,{code:m.invalid_type,expected:l.object,received:t.parsedType}),b;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(I(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),b)}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 s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new oe({typeName:xe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...D(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)),s={...e,...t};for(const r of n){const n=ce(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}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 s=ce(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===l.date&&n===l.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ue extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(A(e)||A(n))return b;const s=ce(e.value,n.value);return s.valid?((w(e)||w(n))&&t.dirty(),{status:t.value,value:s.data}):(I(r,{code:m.invalid_intersection_types}),b)};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:xe.ZodIntersection,...D(r)});class de extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.array)return I(r,{code:m.invalid_type,expected:l.array,received:r.parsedType}),b;if(r.data.length<this._def.items.length)return I(r,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&r.data.length>this._def.items.length&&(I(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 R(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>N.mergeArray(t,e)):N.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:xe.ZodTuple,rest:null,...D(t)})};class le extends P{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 I(r,{code:m.invalid_type,expected:l.object,received:r.parsedType}),b;const n=[],s=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new R(r,e,r.path,e)),value:a._parse(new R(r,r.data[e],r.path,e))});return r.common.async?N.mergeObjectAsync(t,n):N.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new le(t instanceof P?{keyType:e,valueType:t,typeName:xe.ZodRecord,...D(r)}:{keyType:$.create(),valueType:e,typeName:xe.ZodRecord,...D(t)})}}class he extends P{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 I(r,{code:m.invalid_type,expected:l.map,received:r.parsedType}),b;const n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([e,t],a)=>({key:n._parse(new R(r,e,r.path,[a,"key"])),value:s._parse(new R(r,t,r.path,[a,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return b;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return b;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}he.create=(e,t,r)=>new he({valueType:t,keyType:e,typeName:xe.ZodMap,...D(r)});class me extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.set)return I(r,{code:m.invalid_type,expected:l.set,received:r.parsedType}),b;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(I(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&&(I(r,{code:m.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return b;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>s._parse(new R(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>a(e)):a(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:xe.ZodSet,...D(t)});class pe extends P{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.function)return I(t,{code:m.invalid_type,expected:l.function,received:t.parsedType}),b;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 s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Ne){const e=this;return _(async function(...t){const i=new p([]),o=await e._def.args.parseAsync(t,s).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(a,this,o);return await e._def.returns._def.type.parseAsync(c,s).catch(e=>{throw i.addIssue(n(c,e)),i})})}{const e=this;return _(function(...t){const i=e._def.args.safeParse(t,s);if(!i.success)throw new p([r(t,i.error)]);const o=Reflect.apply(a,this,i.data),c=e._def.returns.safeParse(o,s);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:xe.ZodFunction,...D(r)})}}class fe extends P{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:xe.ZodLazy,...D(t)});class ye extends P{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ge(e,t){return new ve({values:e,typeName:xe.ZodEnum,...D(t)})}ye.create=(e,t)=>new ye({value:e,typeName:xe.ZodLiteral,...D(t)});class ve extends P{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return I(t,{expected:u.joinValues(r),received:t.parsedType,code:m.invalid_type}),b}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return I(t,{received:t.data,code:m.invalid_enum_value,options:r}),b}return _(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 Ie extends P{_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 I(r,{expected:u.joinValues(e),received:r.parsedType,code:m.invalid_type}),b}if(-1===t.indexOf(e.data)){const e=u.objectValues(t);return I(r,{received:r.data,code:m.invalid_enum_value,options:e}),b}return _(e.data)}get enum(){return this._def.values}}Ie.create=(e,t)=>new Ie({values:e,typeName:xe.ZodNativeEnum,...D(t)});class Ne extends P{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.promise&&!1===t.common.async)return I(t,{code:m.invalid_type,expected:l.promise,received:t.parsedType}),b;const r=t.parsedType===l.promise?t.data:Promise.resolve(t.data);return _(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:xe.ZodPromise,...D(t)});class be extends P{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{I(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(r.data,s);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,s);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?b:("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?b:("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 a=n.transform(e.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>S(e)?Promise.resolve(n.transform(e.value,s)).then(e=>({status:t.value,value:e})):e)}u.assertNever(n)}}be.create=(e,t,r)=>new be({schema:e,typeName:xe.ZodEffects,effect:t,...D(r)}),be.createWithPreprocess=(e,t,r)=>new be({schema:t,effect:{type:"preprocess",transform:e},typeName:xe.ZodEffects,...D(r)});class Ee extends P{_parse(e){return this._getType(e)===l.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:xe.ZodOptional,...D(t)});class _e extends P{_parse(e){return this._getType(e)===l.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(e,t)=>new _e({innerType:e,typeName:xe.ZodNullable,...D(t)});class Ae extends P{_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:xe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...D(t)});class we extends P{_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}}we.create=(e,t)=>new we({innerType:e,typeName:xe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...D(t)});class Se extends P{_parse(e){if(this._getType(e)!==l.nan){const t=this._getOrReturnCtx(e);return I(t,{code:m.invalid_type,expected:l.nan,received:t.parsedType}),b}return{status:"valid",value:e.data}}}Se.create=e=>new Se({typeName:xe.ZodNaN,...D(e)});const Ce=Symbol("zod_brand");class Te extends P{_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 Re extends P{_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?b:"dirty"===e.status?(t.dirty(),E(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?b:"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 Re({in:e,out:t,typeName:xe.ZodPipeline})}}class Oe extends P{_parse(e){const t=this._def.innerType._parse(e);return S(t)&&(t.value=Object.freeze(t.value)),t}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:xe.ZodReadonly,...D(t)});const De=(e,t={},r)=>e?Q.create().superRefine((n,s)=>{var a,i;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(i=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;s.addIssue({code:"custom",...c,fatal:o})}}):Q.create(),Pe={object:se.lazycreate};var xe;!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"}(xe||(xe={}));const ke=$.create,Fe=z.create,Le=Se.create,Me=q.create,je=G.create,Ue=W.create,Ze=K.create,Be=Y.create,Ve=H.create,$e=Q.create,Je=X.create,ze=ee.create,qe=te.create,Ge=re.create,We=se.create,Ke=se.strictCreate,Ye=ae.create,He=oe.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=me.create,nt=pe.create,st=fe.create,at=ye.create,it=ve.create,ot=Ie.create,ct=Ne.create,ut=be.create,dt=Ee.create,lt=_e.create,ht=be.createWithPreprocess,mt=Re.create,pt={string:e=>$.create({...e,coerce:!0}),number:e=>z.create({...e,coerce:!0}),boolean:e=>G.create({...e,coerce:!0}),bigint:e=>q.create({...e,coerce:!0}),date:e=>W.create({...e,coerce:!0})},ft=b;var yt=Object.freeze({__proto__:null,defaultErrorMap:f,setErrorMap:function(e){y=e},getErrorMap:g,makeIssue:v,EMPTY_PATH:[],addIssueToContext:I,ParseStatus:N,INVALID:b,DIRTY:E,OK:_,isAborted:A,isDirty:w,isValid:S,isAsync:C,get util(){return u},get objectUtil(){return d},ZodParsedType:l,getParsedType:h,ZodType:P,ZodString:$,ZodNumber:z,ZodBigInt:q,ZodBoolean:G,ZodDate:W,ZodSymbol:K,ZodUndefined:Y,ZodNull:H,ZodAny:Q,ZodUnknown:X,ZodNever:ee,ZodVoid:te,ZodArray:re,ZodObject:se,ZodUnion:ae,ZodDiscriminatedUnion:oe,ZodIntersection:ue,ZodTuple:de,ZodRecord:le,ZodMap:he,ZodSet:me,ZodFunction:pe,ZodLazy:fe,ZodLiteral:ye,ZodEnum:ve,ZodNativeEnum:Ie,ZodPromise:Ne,ZodEffects:be,ZodTransformer:be,ZodOptional:Ee,ZodNullable:_e,ZodDefault:Ae,ZodCatch:we,ZodNaN:Se,BRAND:Ce,ZodBranded:Te,ZodPipeline:Re,ZodReadonly:Oe,custom:De,Schema:P,ZodSchema:P,late:Pe,get ZodFirstPartyTypeKind(){return xe},coerce:pt,any:$e,array:Ge,bigint:Me,boolean:je,date:Ue,discriminatedUnion:He,effect:ut,enum:it,function:nt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>De(t=>t instanceof e,t),intersection:Qe,lazy:st,literal:at,map:tt,nan:Le,nativeEnum:ot,never:ze,null:Ve,nullable:lt,number:Fe,object:We,oboolean:()=>je().optional(),onumber:()=>Fe().optional(),optional:dt,ostring:()=>ke().optional(),pipeline:mt,preprocess:ht,promise:ct,record:et,set:rt,strictObject:Ke,string:ke,symbol:Ze,transformer:ut,tuple:Xe,undefined:Be,union:Ye,unknown:Je,void:qe,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 It 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 Nt="zod-ts-rest-polyfill",bt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof se&&t instanceof se){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}},Et=Symbol("ContractNoBody"),_t=e=>"method"in e&&"path"in e,At=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,s,a;return _t(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:bt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(s=r.validateResponseOnClient)&&void 0!==s?s:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(a=r.metadata)&&void 0!==a?a:{}}:r.metadata}]:[e,At(r,t)]})),wt=Symbol("ContractPlainType"),St=()=>({router:(e,t)=>At(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>wt,body:()=>wt,type:()=>wt,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>Et}),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=>Rt(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",Rt=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>Rt(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>Rt(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Ot extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const Dt=async({route:e,path:t,method:r,headers:n,body:s,validateResponse:a,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:n,body:s}),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===Et?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:Nt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(n&&(null!=a?a:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const n=t["~standard"].validate(e);if(n instanceof Promise)throw new Error("Schema validation must be synchronous");return n.issues?t["~standard"].vendor===Nt?{error:new p(n.issues)}:{error:new It(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}},Pt=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},xt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),kt=(e,t,r,n,s)=>{const a=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?Ct(e):Tt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,s);return t.endsWith("/")&&a.startsWith("/")?`${t}${a.substring(1)}${i}`:`${t}${a}${i}`},Ft=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const s=((e,t,r)=>{const{query:n,params:s,body:a,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof s?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,String(t)])):{};return{path:kt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:a,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...o,...i}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:s,query:a,extraInputArgs:i,headers:o,fetchOptions:c}=e,u=r.api||Dt,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&xt(d),...xt(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:s,rawQuery:a,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:s instanceof FormData?s:Pt(s)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof s?s:new URLSearchParams(s)}:null!=s&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(s)})),u({...h,...i})})(s);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new Ot(a,r)}},Lt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>_t(r)?[e,Ft(r,t)]:[e,Lt(r,t)]));class Mt 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 Mt.schema.safeParse(e).success}static unknown(e){return new Mt({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 jt=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()}),Ut=jt.extend({statusCode:t.literal(400)}),Zt=jt.extend({statusCode:t.literal(401)}),Bt=jt.extend({statusCode:t.literal(403)}),Vt=jt.extend({statusCode:t.literal(404)}),$t=jt.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()}),zt=t.object({balance:t.number(),availableBalance:t.number(),accountNumber:t.string(),accountName:t.string()}),qt=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"}`)}}),Wt=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:jt,validationError:Ut,unauthorizedError:Zt,forbiddenError:Bt,notFoundError:Vt,serverError:$t,pagination:Jt,transactionSummary:qt,walletSummary:zt,statementEntry:Wt};class Yt{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){return this.getClientWithHeaders()}getClientWithHeaders(t){const r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",s=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,a={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e()},i={baseUrl:s,baseHeaders:t?{...a,...t}:a};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,s=(t,r)=>new Mt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw s("Bad request","BAD_REQUEST");if(401===e.status)throw s("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw s("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw s("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw s("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw s("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class Ht{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 a=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===a?null:a>0?s.from(a,r)??s.from(0,r):null;const i=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===i?null:i>0?s.from(i,r)??s.from(0,r):null,this.balance=s.from(e.balance,r)??s.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 Ht(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=Ht.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(!a.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!a.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!a.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=s.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=s.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=s.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 Ht(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=Ht.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 s.from(r,t)??s.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 s.from(r,t)??s.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",r=Ht.getTotalCredits(e).numericValue,n=Ht.getTotalDebits(e).numericValue;return s.from(r-n,t)??s.from(0,t)}}class Qt{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=s.from(e.yesterday,t)??s.from(0,t),this.today=s.from(e.today,t)??s.from(0,t),this.thisMonth=s.from(e.thisMonth,t)??s.from(0,t),this.lastMonth=s.from(e.lastMonth,t)??s.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 s.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(!(a.getInstance().isAmountJSON(e.yesterday)&&a.getInstance().isAmountJSON(e.today)&&a.getInstance().isAmountJSON(e.thisMonth)&&a.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=s.fromJSON(e.yesterday),r=s.fromJSON(e.today),n=s.fromJSON(e.thisMonth),i=s.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=s.from(e.availableBalance,t)??s.from(0,t),this.currentBalance=s.from(e.currentBalance,t)??s.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(!a.getInstance().isAmountJSON(e.availableBalance)||!a.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=s.fromJSON(e.availableBalance),r=e.currentBalance??e.actualBalance;if(!a.getInstance().isAmountJSON(r))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const n=s.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)}}var sr,ar;!function(e){e.PENDING="PENDING",e.PENDING_ACK="PENDING_ACK",e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.PAYMENT_FAILED="PAYMENT_FAILED",e.PAYMENT_EXPIRED="PAYMENT_EXPIRED"}(sr||(sr={})),function(e){e.AWAITING_USER="AWAITING_USER",e.PROVIDER_UNCERTAIN="PROVIDER_UNCERTAIN",e.SUCCESS="SUCCESS",e.USER_TIMEOUT="USER_TIMEOUT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.INVALID_NUMBER="INVALID_NUMBER",e.INVALID_PIN="INVALID_PIN",e.ACCOUNT_LOCKED="ACCOUNT_LOCKED",e.ACCOUNT_RESTRICTED="ACCOUNT_RESTRICTED",e.USER_CANCELLED="USER_CANCELLED",e.USER_BUSY="USER_BUSY",e.USER_UNREACHABLE="USER_UNREACHABLE",e.LIMIT_EXCEEDED="LIMIT_EXCEEDED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.PROVIDER_BUSY="PROVIDER_BUSY",e.PROVIDER_ERROR="PROVIDER_ERROR",e.UNKNOWN="UNKNOWN"}(ar||(ar={}));const ir={[sr.PENDING]:{label:"Pending",description:"The payment is pending",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[sr.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[sr.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[sr.PAYMENT_FAILED]:{label:"Payment Failed",description:"The payment did not go through. See the status code for the reason",category:"failed",color:"error",userFriendlyMessage:"Payment failed. Please try again"},[sr.PAYMENT_EXPIRED]:{label:"Payment Expired",description:"The customer did not respond to the payment prompt in time",category:"failed",color:"error",userFriendlyMessage:"Payment request expired before it was approved"}},or={[ar.AWAITING_USER]:{label:"Awaiting Customer",description:"The prompt was sent and the customer has not responded yet",status:sr.PENDING_ACK,userFriendlyMessage:"Waiting for the customer to approve the payment"},[ar.PROVIDER_UNCERTAIN]:{label:"Outcome Unconfirmed",description:"The outcome is not yet known",status:sr.PENDING_ACK,userFriendlyMessage:"Payment is being confirmed with the provider"},[ar.SUCCESS]:{label:"Success",description:"Payment completed",status:sr.PAYMENT_ACCEPTED,userFriendlyMessage:"Payment received successfully"},[ar.USER_TIMEOUT]:{label:"Customer Timeout",description:"The prompt reached the customer but they did not answer in time",status:sr.PAYMENT_EXPIRED,userFriendlyMessage:"The customer did not approve the payment in time"},[ar.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Not enough money in the customer's wallet",status:sr.PAYMENT_FAILED,userFriendlyMessage:"Insufficient balance to complete the payment"},[ar.INVALID_NUMBER]:{label:"Invalid Number",description:"The phone number is wrong or not registered for mobile money",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The phone number is not registered for mobile money"},[ar.INVALID_PIN]:{label:"Invalid PIN",description:"The customer entered a wrong PIN",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer entered a wrong PIN"},[ar.ACCOUNT_LOCKED]:{label:"Account Locked",description:"Too many wrong PINs. The customer's wallet is locked",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is locked"},[ar.ACCOUNT_RESTRICTED]:{label:"Account Restricted",description:"The wallet is barred, blocked or not activated",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's wallet is restricted"},[ar.USER_CANCELLED]:{label:"Cancelled by Customer",description:"The customer declined or cancelled the prompt",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer cancelled the payment"},[ar.USER_BUSY]:{label:"Customer Busy",description:"The customer has another USSD session open",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone was busy with another session"},[ar.USER_UNREACHABLE]:{label:"Customer Unreachable",description:"The prompt could not be delivered (phone off, no network)",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's phone could not be reached"},[ar.LIMIT_EXCEEDED]:{label:"Limit Exceeded",description:"The customer hit a transaction, daily or wallet limit",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The customer's transaction limit was exceeded"},[ar.INVALID_AMOUNT]:{label:"Invalid Amount",description:"The amount is below the minimum, above the maximum, or badly formatted",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The payment amount is not allowed"},[ar.PROVIDER_BUSY]:{label:"Provider Busy",description:"The mobile money provider is busy",status:sr.PAYMENT_FAILED,userFriendlyMessage:"The mobile money provider is busy"},[ar.PROVIDER_ERROR]:{label:"Provider Error",description:"A system error on TemboPlus's side or the provider's side",status:sr.PAYMENT_FAILED,userFriendlyMessage:"Payment failed due to a system error"},[ar.UNKNOWN]:{label:"Unknown Reason",description:"The payment failed but the reason was not given",status:sr.PAYMENT_FAILED,userFriendlyMessage:"Payment failed for an unknown reason"}};function cr(e){return Object.values(sr).find(t=>t===e)}function ur(e){return Object.values(ar).find(t=>t===e)}function dr(e){if(null!=e&&""!==e)return ur(e)??ar.UNKNOWN}function lr(e){return e.status&&e.statusCode?{status:e.status,statusInfo:e.statusInfo,statusCode:e.statusCode,statusCodeInfo:or[e.statusCode],source:"native"}:e.normalizedStatus?{status:e.normalizedStatus,statusInfo:ir[e.normalizedStatus],statusCode:e.normalizedStatusCode,statusCodeInfo:e.normalizedStatusCode?or[e.normalizedStatusCode]:void 0,source:"normalized"}:{status:e.status,statusInfo:e.statusInfo,source:"legacy"}}const hr={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 mr;!function(e){e.READ_ONLY="ReadOnly",e.ADMIN="Admin",e.INITIATOR="Initiator",e.APPROVER="Approver"}(mr||(mr={}));const pr=r.enum(mr),fr={user:r.object({token:r.string(),identity:r.string(),name:r.string(),role:pr}),userRole:pr,loginRequest:r.object({identity:r.email(),password:r.string()}),updatePassword:r.object({currentPassword:r.string(),newPassword:r.string()})},yr=St().router({login:{method:"POST",path:"/login",body:fr.loginRequest,responses:{201:fr.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:fr.updatePassword,responses:{201:t.object({}),400:Kt.validationError,401:Kt.unauthorizedError,500:Kt.serverError},summary:"Update password",description:"Update user password"}});class gr{identity;name;role;constructor(e){this.identity=e.identity,this.name=e.name,this.role=e.role}static from(e){return new gr(e)}static fromJSON(e){return gr.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 vr extends Yt{constructor(e){super("auth",yr,e)}async login(e){const r=t.object({email:t.email().trim().toLowerCase(),password:t.string().min(1)}).safeParse(e);if(!r.success)throw new Mt({message:"Invalid email or password",statusCode:400});const{email:n,password:s}=r.data,a=await this.client.login({body:{identity:n,password:s}});if(400===a.status||401===a.status)throw new Mt({message:"Invalid email or password",statusCode:a.status});const{token:i,...o}=this.handleResponse(a,201);if(!i)throw new Mt({message:"Authentication token missing from server response",statusCode:500});const c=gr.from(o);if(!c)throw new Mt({message:"Invalid user data received from server",statusCode:500});return{user:c,token:i}}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 Ir,Nr;!function(e){e.PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",e.PENDING="PENDING",e.PENDING_ACK="PENDING_ACK",e.PAYMENT_FAILED="PAYMENT_FAILED",e.PAYMENT_EXPIRED="PAYMENT_EXPIRED",e.GENERIC_FAILURE="GENERIC_FAILURE",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.INVALID_REFERENCE="INVALID_REFERENCE",e.PAYMENT_REJECTED="PAYMENT_REJECTED",e.PROVIDER_FAILED="PROVIDER_FAILED"}(Ir||(Ir={})),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",e.CRDB="TZ-CRDB",e.ECOBANK="TZ-ECOBANK"}(Nr||(Nr={}));const br=r.enum(Ir),Er=r.enum(ar),_r=r.enum(Nr),Ar=e=>{const t=Array.isArray(e)?e.flatMap(e=>Ar(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},wr=r.union([r.string(),r.array(r.string())]),Sr={collection:r.object({id:r.string().min(1),status:br,statusCode:r.unknown().optional().transform(dr),normalizedStatus:r.unknown().optional().transform(cr),normalizedStatusCode:r.unknown().optional().transform(dr),statusMessage:r.string(),accountNo:r.string().min(1),walletId:r.string(),transactionDate:r.iso.datetime(),narration:r.string(),msisdn:r.string().min(1),channel:_r,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:_r.optional(),channelIn:r.array(_r).optional(),status:br.optional(),statusIn:r.array(br).optional(),statusCode:Er.optional(),statusCodeIn:r.array(Er).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:wr.transform(Ar).optional(),reference:r.string().optional(),referenceIn:wr.transform(Ar).optional(),accountNo:r.string().optional(),walletId:r.string().optional(),partnerReference:r.string().optional(),channel:r.string().refine(e=>Object.values(Nr).includes(e)).transform(e=>e).optional(),channelIn:wr.transform(Ar).pipe(r.array(_r)).optional(),status:r.string().refine(e=>Object.values(Ir).includes(e)).transform(e=>e).optional(),statusIn:wr.transform(Ar).pipe(r.array(br)).optional(),statusCode:Er.optional(),statusCodeIn:wr.transform(Ar).pipe(r.array(Er)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),paymentStatus:br,statusCode:Er,paymentChannel:_r},Cr=St().router({getCollections:{method:"GET",path:"/",query:Sr.collectionURLQueryParams,responses:{200:r.object({results:r.array(Sr.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:Sr.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"}}),Tr={...ir,[Ir.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"},[Ir.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"},[Ir.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"},[Ir.INVALID_REFERENCE]:{label:"Invalid Reference",description:"This collection was not found on the provider's side",category:"failed",color:"error",userFriendlyMessage:"Payment could not be found with the provider"},[Ir.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"}},Rr={[Nr.AIRTEL]:hr.AIRTEL,[Nr.TIGO]:hr.TIGO,[Nr.HALOTEL]:hr.HALOTEL,[Nr.VODACOM]:hr.VODACOM,[Nr.SAFARICOM]:hr.SAFARICOM};function Or(e){return Object.entries(Tr).filter(([t,r])=>r.category===e).map(([e])=>e)}class Dr{id;status;statusCode;normalizedStatus;normalizedStatusCode;statusMessage;accountNo;walletId;transactionDate;narration;msisdn;channel;amount;serviceFee;postedAmount;reference;partnerReference;payerName;payerReference;merchantName;merchantReference;transactionId;serviceFeeTransactionId;requestId;completedAt;createdAt;updatedAt;notes;currencyCode;_originalData;constructor(e){this._originalData={...e};let t="TZS";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,this.statusCode=dr(e.statusCode),this.normalizedStatus=cr(e.normalizedStatus),this.normalizedStatusCode=dr(e.normalizedStatusCode),this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=s.from(e.amount,t)??s.from(0,t),this.serviceFee=e.serviceFee?s.from(parseFloat(e.serviceFee),t)??s.from(0,t):void 0,this.postedAmount=e.postedAmount?s.from(parseFloat(e.postedAmount),t)??s.from(0,t):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.payerName=e.payerName,this.payerReference=e.payerReference,this.merchantName=e.merchantName,this.merchantReference=e.merchantReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return"pending"===Tr[this.status]?.category}isSuccessful(){return this.status===Ir.PAYMENT_ACCEPTED}isFailed(){return"failed"===Tr[this.status]?.category}isExpired(){return this.status===Ir.PAYMENT_EXPIRED}isFinal(){return this.isSuccessful()||this.isFailed()}getStatusInfo(){return Tr[this.status]}getStatusCode(){return this.statusCode}getStatusCodeInfo(){return this.statusCode?or[this.statusCode]:void 0}getDisplayStatus(){return lr({status:this.status,statusInfo:Tr[this.status],statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode})}getChannelInfo(){return Rr[this.channel]}getProviderName(){return this.getChannelInfo()?.networkOperator}getServiceName(){return this.getChannelInfo()?.serviceName}isMobileCollection(){return this.channel in Rr}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Dr(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=Dr.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(!a.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!a.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!a.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=s.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=s.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=s.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,statusCode:e.statusCode,normalizedStatus:e.normalizedStatus,normalizedStatusCode:e.normalizedStatusCode,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee: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 Dr(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=Dr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJSON(),serviceFee:this.serviceFee?.toJSON(),postedAmount:this.postedAmount?.toJSON(),reference:this.reference,partnerReference:this.partnerReference,payerName:this.payerName,payerReference:this.payerReference,merchantName:this.merchantName,merchantReference:this.merchantReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:this.completedAt?.toISOString()??null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}const Pr=["id","reference","channel","status","statusCode"];class xr extends nr{static create(){return new xr}static fromFilters(e){return(new xr).applyFilters(e)}static fromUrlParams(e){try{const t=Sr.collectionURLQueryParams.parse(xr.normalizeUrlParams(e)),r=Sr.collectionFilters.parse(t);return xr.fromFilters(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return xr.fromUrlParams(xr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return xr.fromSearchParams(t)}static from(e){try{return null==e?new xr:nr.is(e)?new xr(e.options):e instanceof URLSearchParams?xr.fromSearchParams(e):xr.isUrlParamsRecord(e)?xr.fromUrlParams(e):xr.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 Pr){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,i=`${e}In[]`,o=t[r],c=Ar([t[n],t[s],t[a],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[s],delete t[a],delete t[i]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereStatusCode(e){return this.where("statusCode",e)}whereStatusCodeIn(e){return this.whereInValues("statusCode",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}whereIdIn(e){return this.whereInValues("id",e)}whereReferenceIn(e){return this.whereInValues("reference",e)}wherePending(){return this.whereStatusIn(Or("pending"))}whereSuccessful(){return this.whereStatus(Ir.PAYMENT_ACCEPTED)}whereFailed(){return this.whereStatusIn(Or("failed"))}whereExpired(){return this.whereStatus(Ir.PAYMENT_EXPIRED)}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("reference",e)}wherePartnerReference(e){return this.where("partnerReference",e)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.statusCodeIn?.length?this.whereStatusCodeIn(e.statusCodeIn):e.statusCode&&this.whereStatusCode(e.statusCode),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.referenceIn?.length?this.whereReferenceIn(e.referenceIn):e.reference&&this.whereReference(e.reference),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,id:e.id,idIn:e.idIn,reference:e.reference,referenceIn:e.referenceIn,accountNo:e.accountNo,walletId:e.walletId,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),statusCode:this.isValidStatusCode(e.statusCode)?e.statusCode:void 0,statusCodeIn:this.getValidStatusCodes(e.statusCodeIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.idIn?.length||e.reference||e.referenceIn?.length||e.accountNo||e.walletId||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.statusCode||e.statusCodeIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.statusCodeIn?.length?e.push(`Reason: ${t.statusCodeIn.join(", ")}`):t.statusCode&&e.push(`Reason: ${t.statusCode}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.referenceIn?.length?e.push(`Reference: ${t.referenceIn.join(", ")}`):t.reference&&e.push(`Reference: ${t.reference}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=Ar(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=Ar(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Ar(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidStatusCodes(e){const t=Ar(e).filter(e=>this.isValidStatusCode(e));return t.length>0?t:void 0}getValidChannels(e){const t=Ar(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(Nr).some(t=>t===e)}isValidStatus(e){return Object.values(Ir).some(t=>t===e)}isValidStatusCode(e){return Object.values(ar).some(t=>t===e)}}class kr extends Yt{constructor(e){super("collection",Cr,e)}async getCollections(e){try{const t=xr.from(e),r=t.build(),n=await this.client.getCollections({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),i={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},o=Dr.createMany(s.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=xr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=Dr.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 Fr,Lr,Mr;!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"}(Fr||(Fr={})),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"}(Lr||(Lr={})),function(e){e.BANK="TZ-BANK-B2C"}(Mr||(Mr={}));const jr=r.enum(Fr),Ur=r.enum(Lr),Zr=r.enum(Mr),Br=r.union([Ur,Zr]),Vr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Vr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},$r=r.union([r.string(),r.array(r.string())]),Jr={payout:r.object({id:r.string().min(1),statusCode:r.string().optional(),statusCodeText:jr,normalizedStatus:r.unknown().optional().transform(cr),normalizedStatusCode:r.unknown().optional().transform(dr),statusDescription:r.string(),countryCode:r.string(),serviceCode:Br,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:Br.optional(),channelIn:r.array(Br).optional(),status:jr.optional(),statusIn:r.array(jr).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:$r.transform(Vr).optional(),ref:r.string().optional(),refIn:$r.transform(Vr).optional(),channelRef:r.string().optional(),channelRefIn:$r.transform(Vr).optional(),channel:r.string().refine(e=>Object.values(Lr).includes(e)||e===Mr.BANK).transform(e=>e).optional(),channelIn:$r.transform(Vr).pipe(r.array(Br)).optional(),status:r.string().refine(e=>Object.values(Fr).includes(e)).transform(e=>e).optional(),statusIn:$r.transform(Vr).pipe(r.array(jr)).optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional()}),payoutStatus:jr,payoutChannel:Br,mobileChannel:Ur,bankChannel:Zr,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()})},zr=St().router({getPayouts:{method:"GET",path:"",query:Jr.payoutURLQueryParams,responses:{200:r.object({results:r.array(Jr.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:Jr.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"}}),qr={[Fr.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[Fr.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[Fr.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[Fr.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"},[Fr.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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"},[Fr.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."}},Gr={[Lr.AIRTEL]:hr.AIRTEL,[Lr.VODACOM]:hr.VODACOM,[Lr.TIGO]:hr.TIGO,[Lr.HALOTEL]:hr.HALOTEL,[Lr.SAFARICOM]:hr.SAFARICOM};function Wr(e){return Object.values(Lr).includes(e)}function Kr(e){return e===Mr.BANK}class Yr{id;serviceCode;msisdn;amount;transactionDate;statusDescription;statusCodeText;transactionId;transactionRef;recipientNames;narration;serviceFee;notes;swiftCode;createdAt;updatedAt;statusCode;normalizedStatus;normalizedStatusCode;countryCode;postedAmount;walletId;currencyCode;externalId;cbaReferenceNo;beepTransactionId;receiptNumber;reversedTransactionId;serviceFeeTransactionId;isReconciled;requestId;_originalData;constructor(e){this._originalData={...e};let t="TZS";n.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=s.from(e.amount,t)??s.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:s.from(e.serviceFee,t)??s.from(0,t),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=e.updatedAt?new Date(e.updatedAt):void 0,this.statusCode=e.statusCode,this.normalizedStatus=cr(e.normalizedStatus),this.normalizedStatusCode=dr(e.normalizedStatusCode),this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?s.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[Fr.PENDING,Fr.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===Fr.PAYMENT_ACCEPTED}isFailed(){return Object.entries(qr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return qr[this.statusCodeText]}getDisplayStatus(){return lr({status:this.statusCodeText,statusInfo:qr[this.statusCodeText],statusCode:ur(this.statusCode),normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode})}getChannelInfo(){if(Wr(this.serviceCode))return Gr[this.serviceCode];if(Kr(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(Wr(this.serviceCode))return this.msisdn;if(Kr(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 Wr(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 Yr(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=Yr.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(!a.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!a.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!a.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=s.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=s.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=s.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,normalizedStatus:e.normalizedStatus,normalizedStatusCode:e.normalizedStatusCode,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 Yr(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=Yr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJSON(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:this.serviceFee?.toJSON(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt?.toISOString(),statusCode:this.statusCode,normalizedStatus:this.normalizedStatus,normalizedStatusCode:this.normalizedStatusCode,countryCode:this.countryCode,postedAmount:this.postedAmount?.toJSON(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}const Hr=["status","channel","id","ref","channelRef"],Qr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class Xr extends nr{static create(){return new Xr}static fromFilters(e){return(new Xr).applyFilters(e)}static fromUrlParams(e){try{const t=Jr.payoutURLQueryParams.parse(Xr.normalizeUrlParams(e)),r=Jr.payoutFilters.parse(t);return Xr.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Xr.fromUrlParams(Xr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Xr.fromSearchParams(t)}static from(e){return null==e?new Xr:nr.is(e)?new Xr(e.options):e instanceof URLSearchParams?Xr.fromSearchParams(e):Xr.isUrlParamsRecord(e)?Xr.fromUrlParams(e):Xr.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 Hr){const r=e,n=`${e}In`,s=`${e}:in`,a=`${e}[]`,i=`${e}In[]`,o=t[r],c=Vr([t[n],t[s],t[a],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[s],delete t[a],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",[Fr.PENDING,Fr.PENDING_ACK])}whereSuccessful(){return this.whereStatus(Fr.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[Fr.PAYMENT_REJECTED,Fr.GENERIC_FAILURE,Fr.AMOUNT_EXCEED_MAXIMUM,Fr.INVALID_SERVICE,Fr.INSUFFICIENT_BALANCE,Fr.THIRDPARTY_FAILED,Fr.WALLET_DEBITED,Fr.REVERSED])}whereAmount(e){return this.where("amount",e)}whereAmountLessThan(e){return this.whereLessThan("amount",e)}whereAmountGreaterThan(e){return this.whereGreaterThan("amount",e)}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.where("msisdn",e)}whereAccount(e){return this.where("accountNo",e)}whereWalletId(e){return this.where("walletId",e)}whereReference(e){return this.where("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(Lr))}whereBank(){return this.whereChannel(Mr.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=Vr(t.value);if(0===r.length)continue;e[`${Qr[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=Vr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Vr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Vr(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(Lr).some(t=>t===e)||e===Mr.BANK}isValidStatus(e){return Object.values(Fr).some(t=>t===e)}}class en extends Yt{constructor(e){super("payout",zr,e)}async getPayouts(e){try{const t=Xr.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),s=this.handleResponse(n,200),a=t.toFilters(),i={page:a.page,limit:a.limit,total:s.total,totalPages:s.total>0?Math.ceil(s.total/a.limit):0,hasNext:a.page*a.limit<s.total,hasPrev:a.page>1},o=Yr.createMany(s.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=Xr.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Yr.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 tn,rn,nn,sn;!function(e){e.PENDING="PENDING",e.APPROVED="APPROVED",e.PROCESSING="PROCESSING",e.PROCESSED="PROCESSED",e.REJECTED="REJECTED"}(tn||(tn={})),function(e){e.APPROVED="APPROVED",e.REJECTED="REJECTED"}(rn||(rn={})),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"}(nn||(nn={})),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"}(sn||(sn={}));const an=r.enum(tn),on=r.enum(rn),cn=r.enum(nn),un=r.enum(sn),dn=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:an,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()}),ln=r.object({status:an.optional(),amount:r.number().optional(),accountNo:r.string().optional()}),hn=r.object({status:an.optional(),amount:r.coerce.number().optional(),accountNo:r.string().optional()}),mn=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")}),pn=r.object({status:cn,data:dn.optional()}),fn=r.object({status:on}),yn=r.object({status:un,data:dn.optional()}),gn={settlement:dn,settlementStatus:an,settlementAction:on,settlementFilters:ln,settlementURLQueryParams:hn,createSettlementRequest:mn,createSettlementStatus:cn,createSettlementResponse:pn,actionSettlementRequest:fn,actionSettlementStatus:un,actionSettlementResponse:yn},vn=St().router({getSettlements:{method:"GET",path:"",query:gn.settlementFilters,responses:{200:r.array(gn.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:gn.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:gn.createSettlementRequest,responses:{201:gn.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:gn.actionSettlementRequest,responses:{201:gn.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"}}),In={[tn.PENDING]:{label:"Pending",description:"Pending approval or rejection",category:"pending",color:"warning",userFriendlyMessage:"Settlement is awaiting approval"},[tn.APPROVED]:{label:"Approved",description:"Approved by an admin or approver",category:"success",color:"success",userFriendlyMessage:"Settlement was approved"},[tn.PROCESSING]:{label:"Processing",description:"Approved and being processed to the settlement bank account",category:"processing",color:"info",userFriendlyMessage:"Settlement is being processed to your bank account"},[tn.PROCESSED]:{label:"Processed",description:"Approved and processed successfully",category:"success",color:"success",userFriendlyMessage:"Settlement was processed successfully"},[tn.REJECTED]:{label:"Rejected",description:"Rejected by an admin or approver",category:"failed",color:"error",userFriendlyMessage:"Settlement was rejected"}};function Nn(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}class bn{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=Nn(e.initiatedAt),this.initiatedById=e.initiatedById,this.actionedAt=Nn(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=s.from(e.amount,"TZS")??s.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===tn.PENDING}isApproved(){return this.status===tn.APPROVED}isProcessing(){return this.status===tn.PROCESSING}isProcessed(){return this.status===tn.PROCESSED}isRejected(){return this.status===tn.REJECTED}canBeActioned(){return this.isPending()}getStatusInfo(){return In[this.status]}static from(e){try{const t=e;return t?.id&&t?.accountNo&&void 0!==t?.amount?new bn(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=bn.from(r);e&&t.push(e)}return t}static fromJSON(e){return bn.from(e)}toJSON(){return{...this._originalData}}}class En{filters;constructor(e={}){this.filters={...e}}static create(){return new En}static fromFilters(e){return new En(gn.settlementFilters.parse(e))}static fromUrlParams(e){try{const t=En.flattenParams(e),r=gn.settlementURLQueryParams.parse(t);return new En(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return En.fromUrlParams(En.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return En.fromSearchParams(t)}static from(e){try{return null==e?new En:En.is(e)?e.clone():e instanceof URLSearchParams?En.fromSearchParams(e):En.isUrlParamsRecord(e)?En.fromUrlParams(e):En.fromFilters(e)}catch(e){throw console.log(e),new Error("Invalid input! Could not create a SettlementQuery instance.")}}static is(e){return e instanceof En}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static flattenParams(e){const t=["status","amount","accountNo"],r={};for(const n of t){const t=e[n],s=(Array.isArray(t)?t[0]:t)?.trim();s&&(r[n]=s)}return r}whereStatus(e){return this.filters.status=e,this}whereAmount(e){return this.filters.amount=e,this}whereAccountNo(e){return this.filters.accountNo=e,this}wherePending(){return this.whereStatus(tn.PENDING)}whereApproved(){return this.whereStatus(tn.APPROVED)}whereProcessing(){return this.whereStatus(tn.PROCESSING)}whereProcessed(){return this.whereStatus(tn.PROCESSED)}whereRejected(){return this.whereStatus(tn.REJECTED)}clone(){return new En(this.filters)}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withAmount(e){const t=this.clone();return void 0!==e&&t.whereAmount(e),t}withAccountNo(e){const t=this.clone();return e&&t.whereAccountNo(e),t}toFilters(){const e={};return void 0!==this.filters.status&&(e.status=this.filters.status),void 0!==this.filters.amount&&(e.amount=this.filters.amount),void 0!==this.filters.accountNo&&(e.accountNo=this.filters.accountNo),e}build(){return this.toFilters()}toUrlParams(){const e=this.toFilters(),t={};for(const[r,n]of Object.entries(e))null!=n&&(t[r]=String(n));return t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}hasFilters(){const e=this.toFilters();return void 0!==e.status||void 0!==e.amount||void 0!==e.accountNo}getActiveFilters(){const e=[],t=this.toFilters();return t.status&&e.push(`Status: ${t.status}`),void 0!==t.amount&&e.push(`Amount: ${t.amount}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),e}}class _n extends Yt{constructor(e){super("settlement",vn,e)}async getSettlements(e){const t=En.from(e),r=await this.client.getSettlements({query:t.build()}),n=this.handleResponse(r,200);return bn.createMany(n)}async getSettlementsFromRequest(e){return this.getSettlements(En.fromRequest(e))}async getSettlement(e){const t=await this.client.getSettlement({params:{id:e}}),r=this.handleResponse(t,200),n=bn.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?bn.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?bn.from(n.data):void 0}}async approveSettlement(e){return this.actionSettlement(e,rn.APPROVED)}async rejectSettlement(e){return this.actionSettlement(e,rn.REJECTED)}}const An={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()})},wn=St().router({localTransfer:{method:"POST",path:"/local-transfer",body:An.localTransferRequest,responses:{201:An.localTransferResponse,400:Kt.validationError,401:Kt.unauthorizedError,404:Kt.notFoundError,500:Kt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});class Sn extends Yt{constructor(e){super("transaction",wn,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}}const Cn={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()})},Tn=St().router({getMe:{method:"GET",path:"/me",responses:{200:Cn.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 Rn{businessName;tradeName;canCollect;canPayout;canRemit;automatedSettlements;disabledPaymentApproval;settlementAccount;constructor(e){this.businessName=e.businessName,this.tradeName=e.tradeName,this.canCollect=e.canCollect,this.canPayout=e.canPayout,this.canRemit=e.canRemit,this.automatedSettlements=e.automatedSettlements,this.disabledPaymentApproval=e.disabledPaymentApproval,this.settlementAccount=e.settlementAccount}hasSettlementAccount(){return null!==this.settlementAccount}getDisplayName(){return this.tradeName||this.businessName}static from(e){try{const t=e;if(!t?.businessName)return void console.error("Missing required Vendor fields:",e);const r=t,n=r.bankCode?c.fromBIC(r.bankCode):void 0,s=n&&r.bankAccountName&&r.bankAccountNo?{accountName:r.bankAccountName,accountNo:r.bankAccountNo,bank:n}:null;return new Rn({businessName:r.businessName,tradeName:r.tradeName,canCollect:1===r.enableCollections,canPayout:1===r.enablePayouts,canRemit:1===r.enableRemittance,automatedSettlements:1===r.enableAutoSettlement,disabledPaymentApproval:1===r.disablePaymentApproval,settlementAccount:s})}catch(e){return void console.error("Error creating Vendor:",e)}}static fromJSON(e){let t=null;if(e.settlementAccount){const r=c.fromJSON(e.settlementAccount.bank);r&&(t={accountName:e.settlementAccount.accountName,accountNo:e.settlementAccount.accountNo,bank:r})}return new Rn({...e,settlementAccount:t})}toJSON(){return{businessName:this.businessName,tradeName:this.tradeName,canCollect:this.canCollect,canPayout:this.canPayout,canRemit:this.canRemit,automatedSettlements:this.automatedSettlements,disabledPaymentApproval:this.disabledPaymentApproval,settlementAccount:this.settlementAccount?{accountName:this.settlementAccount.accountName,accountNo:this.settlementAccount.accountNo,bank:this.settlementAccount.bank.toJSON()}:null}}}class On extends Yt{constructor(e){super("vendor",Tn,e)}async getMe(){const e=await this.client.getMe(),t=this.handleResponse(e,200),r=Rn.from(t);if(!r)throw new Error("Invalid vendor data received from server");return r}}var Dn;function Pn(e){switch(e){case"DEFAULT COLLECTION":case Dn.COLLECTION:return Dn.COLLECTION;case"Vendor":case"DEFAULT DISBURSEMENT":case Dn.DISBURSEMENT:return Dn.DISBURSEMENT;default:throw new TypeError(`Unsupported wallet type: ${String(e)}`)}}!function(e){e.COLLECTION="COLLECTION",e.DISBURSEMENT="DISBURSEMENT"}(Dn||(Dn={}));const xn=r.enum(Dn),kn=r.enum(["Vendor","DEFAULT DISBURSEMENT","DEFAULT COLLECTION","COLLECTION","DISBURSEMENT"]).transform(Pn),Fn=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:kn,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)}),Ln=r.object({availableBalance:r.number(),currentBalance:r.number(),accountStatus:r.string().min(1),accountNo:r.string().min(1),accountName:r.string().min(1)}),Mn={wallet:Fn,walletType:xn,walletPathParams:r.object({accountNo:r.string().min(1)}),walletBalance:Ln,walletStatementQuery:r.object({startDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},jn=St().router({listWallets:{method:"GET",path:"",responses:{200:r.array(Mn.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:Mn.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:Mn.walletPathParams,responses:{200:Mn.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:Mn.walletPathParams,query:Mn.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 Un{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){const t=Pn(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=s.from(e.balance,r)??s.from(0,r),this.minBalance=s.from(this.parseAmountValue(e.minBalance),r)??s.from(0,r),this.approvalLimit=s.from(this.parseAmountValue(e.approvalLimit),r)??s.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===Dn.COLLECTION}isDisbursementWallet(){return this.type===Dn.DISBURSEMENT}isDefaultWallet(){return!1}static from(e){return new Un(e)}static createMany(e){const t=[];for(const r of e)try{t.push(Un.from(r))}catch(e){console.warn("Skipping unsupported wallet:",e)}return t}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!a.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!a.getInstance().isAmountJSON(e.minBalance)||!a.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=s.fromJSON(e.balance),r=s.fromJSON(e.minBalance),n=s.fromJSON(e.approvalLimit);return t&&r&&n?new Un({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 Zn extends Yt{constructor(e){super("wallet",jn,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=Un.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 Un.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=Ht.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{sn as ACTION_SETTLEMENT_STATUS,Mt as APIError,fr as AuthDTOSchemas,vr as AuthRepository,Mr as BANK_PAYOUT_CHANNEL,Yt as BaseRepository,Nr as COLLECTION_CHANNEL,Ir as COLLECTION_STATUS,ar as COLLECTION_STATUS_CODE,or as COLLECTION_STATUS_CODE_INFO,Tr as COLLECTION_STATUS_INFO,nn as CREATE_SETTLEMENT_STATUS,Dr as Collection,Sr as CollectionDTOSchemas,xr as CollectionQuery,kr as CollectionRepository,Kt as CommonSchemas,er as FilterOperator,Lr as MOBILE_PAYOUT_CHANNEL,hr as MobileChannels,sr as NORMALIZED_STATUS,ar as NORMALIZED_STATUS_CODE,or as NORMALIZED_STATUS_CODE_INFO,ir as NORMALIZED_STATUS_INFO,Fr as PAYOUT_STATUS,qr as PAYOUT_STATUS_INFO,Yr as Payout,Jr as PayoutDTOSchemas,Xr as PayoutQuery,en as PayoutRepository,rr as QUERY_BUILDER_TYPE,nr as QueryBuilder,rn as SETTLEMENT_ACTION,tn as SETTLEMENT_STATUS,In as SETTLEMENT_STATUS_INFO,bn as Settlement,gn as SettlementDTOSchemas,En as SettlementQuery,_n as SettlementRepository,tr as SortDirection,Ht as StatementEntry,An as TransactionDTOSchemas,Sn as TransactionRepository,Qt as TransactionSummary,mr as USER_ROLE,gr as User,Rn as Vendor,Cn as VendorDTOSchemas,On as VendorRepository,Dn as WALLET_TYPE,Un as Wallet,Mn as WalletDTOSchemas,Xt as WalletInfo,Zn as WalletRepository,cr as asNormalizedStatus,ur as asNormalizedStatusCode,yr as authContract,Cr as collectionContract,Ar as collectionToStringArray,Or as getCollectionStatusesByCategory,Pn as normalizeWalletType,zr as payoutContract,Vr as payoutToStringArray,lr as resolveDisplayStatus,vn as settlementContract,Wt as statementEntrySchema,dr as toCollectionStatusCode,dr as toNormalizedStatusCode,wn as transactionContract,Tn as vendorContract,jn as walletContract};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|