@temboplus/afloat 0.2.1-beta.9 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +54 -207
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/lib/api/base-repository.d.ts +2 -2
- package/dist/lib/api/base-repository.d.ts.map +1 -0
- package/dist/lib/api/index.d.ts +1 -0
- package/dist/lib/api/index.d.ts.map +1 -0
- package/dist/lib/error/error.api.d.ts +3 -2
- package/dist/lib/error/error.api.d.ts.map +1 -0
- package/dist/lib/error/error.permission.d.ts +2 -1
- package/dist/lib/error/error.permission.d.ts.map +1 -0
- package/dist/lib/error/error.utils.d.ts +1 -0
- package/dist/lib/error/error.utils.d.ts.map +1 -0
- package/dist/lib/error/index.d.ts +1 -0
- package/dist/lib/error/index.d.ts.map +1 -0
- package/dist/lib/query/index.d.ts +3 -2
- package/dist/lib/query/index.d.ts.map +1 -0
- package/dist/lib/query/pagination/pagination.d.ts +1 -0
- package/dist/lib/query/pagination/pagination.d.ts.map +1 -0
- package/dist/lib/query/pagination/pagination.schemas.d.ts +8 -61
- package/dist/lib/query/pagination/pagination.schemas.d.ts.map +1 -0
- package/dist/lib/query/query.builder.d.ts +10 -3
- package/dist/lib/query/query.builder.d.ts.map +1 -0
- package/dist/lib/query/query.types.d.ts +1 -0
- package/dist/lib/query/query.types.d.ts.map +1 -0
- package/dist/modules/auth/auth.contract.d.ts +10 -69
- package/dist/modules/auth/auth.contract.d.ts.map +1 -0
- package/dist/modules/auth/auth.dtos.d.ts +8 -67
- package/dist/modules/auth/auth.dtos.d.ts.map +1 -0
- package/dist/modules/auth/auth.repository.d.ts +1 -0
- package/dist/modules/auth/auth.repository.d.ts.map +1 -0
- package/dist/modules/auth/company-membership.model.d.ts +7 -86
- package/dist/modules/auth/company-membership.model.d.ts.map +1 -0
- package/dist/modules/auth/index.d.ts +3 -2
- package/dist/modules/auth/index.d.ts.map +1 -0
- package/dist/modules/auth/user.model.d.ts +26 -163
- package/dist/modules/auth/user.model.d.ts.map +1 -0
- package/dist/modules/beneficiary/beneficiary-info.model.d.ts +30 -67
- package/dist/modules/beneficiary/beneficiary-info.model.d.ts.map +1 -0
- package/dist/modules/beneficiary/beneficiary-input-handler.d.ts +3 -2
- package/dist/modules/beneficiary/beneficiary-input-handler.d.ts.map +1 -0
- package/dist/modules/beneficiary/beneficiary.api-contract.d.ts +16 -115
- package/dist/modules/beneficiary/beneficiary.api-contract.d.ts.map +1 -0
- package/dist/modules/beneficiary/beneficiary.dtos.d.ts +6 -34
- package/dist/modules/beneficiary/beneficiary.dtos.d.ts.map +1 -0
- package/dist/modules/beneficiary/beneficiary.model.d.ts +5 -27
- package/dist/modules/beneficiary/beneficiary.model.d.ts.map +1 -0
- package/dist/modules/beneficiary/beneficiary.repository.d.ts +2 -1
- package/dist/modules/beneficiary/beneficiary.repository.d.ts.map +1 -0
- package/dist/modules/beneficiary/index.d.ts +5 -4
- package/dist/modules/beneficiary/index.d.ts.map +1 -0
- package/dist/modules/login/index.d.ts +1 -0
- package/dist/modules/login/index.d.ts.map +1 -0
- package/dist/modules/login/login.api-contract.d.ts +3 -28
- package/dist/modules/login/login.api-contract.d.ts.map +1 -0
- package/dist/modules/login/login.dtos.d.ts +5 -56
- package/dist/modules/login/login.dtos.d.ts.map +1 -0
- package/dist/modules/login/login.model.d.ts +7 -34
- package/dist/modules/login/login.model.d.ts.map +1 -0
- package/dist/modules/login/login.repository.d.ts +2 -1
- package/dist/modules/login/login.repository.d.ts.map +1 -0
- package/dist/modules/login/permission.type.d.ts +1 -0
- package/dist/modules/login/permission.type.d.ts.map +1 -0
- package/dist/modules/payout/index.d.ts +3 -2
- package/dist/modules/payout/index.d.ts.map +1 -0
- package/dist/modules/payout/payout-channel-handler.d.ts +5 -4
- package/dist/modules/payout/payout-channel-handler.d.ts.map +1 -0
- package/dist/modules/payout/payout.api-contract.d.ts +78 -666
- package/dist/modules/payout/payout.api-contract.d.ts.map +1 -0
- package/dist/modules/payout/payout.dtos.d.ts +99 -506
- package/dist/modules/payout/payout.dtos.d.ts.map +1 -0
- package/dist/modules/payout/payout.model.d.ts +8 -85
- package/dist/modules/payout/payout.model.d.ts.map +1 -0
- package/dist/modules/payout/payout.query.d.ts +3 -2
- package/dist/modules/payout/payout.query.d.ts.map +1 -0
- package/dist/modules/payout/payout.repository.d.ts +7 -6
- package/dist/modules/payout/payout.repository.d.ts.map +1 -0
- package/dist/modules/profile/index.d.ts +1 -0
- package/dist/modules/profile/index.d.ts.map +1 -0
- package/dist/modules/profile/profile.api-contract.d.ts +2 -19
- package/dist/modules/profile/profile.api-contract.d.ts.map +1 -0
- package/dist/modules/profile/profile.dtos.d.ts +3 -38
- package/dist/modules/profile/profile.dtos.d.ts.map +1 -0
- package/dist/modules/profile/profile.model.d.ts +5 -42
- package/dist/modules/profile/profile.model.d.ts.map +1 -0
- package/dist/modules/profile/profile.repository.d.ts +1 -0
- package/dist/modules/profile/profile.repository.d.ts.map +1 -0
- package/dist/modules/team-member/index.d.ts +3 -2
- package/dist/modules/team-member/index.d.ts.map +1 -0
- package/dist/modules/team-member/role.model.d.ts +6 -21
- package/dist/modules/team-member/role.model.d.ts.map +1 -0
- package/dist/modules/team-member/team-member.contract.d.ts +74 -615
- package/dist/modules/team-member/team-member.contract.d.ts.map +1 -0
- package/dist/modules/team-member/team-member.dtos.d.ts +15 -162
- package/dist/modules/team-member/team-member.dtos.d.ts.map +1 -0
- package/dist/modules/team-member/team-member.model.d.ts +7 -66
- package/dist/modules/team-member/team-member.model.d.ts.map +1 -0
- package/dist/modules/team-member/team-member.repository.d.ts +3 -2
- package/dist/modules/team-member/team-member.repository.d.ts.map +1 -0
- package/dist/modules/wallet/index.d.ts +4 -2
- package/dist/modules/wallet/index.d.ts.map +1 -0
- package/dist/modules/wallet/narration.model.d.ts +3 -8
- package/dist/modules/wallet/narration.model.d.ts.map +1 -0
- package/dist/modules/wallet/statement-entry.model.d.ts +14 -131
- package/dist/modules/wallet/statement-entry.model.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.contract.d.ts +17 -90
- package/dist/modules/wallet/wallet.contract.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.dtos.d.ts +33 -138
- package/dist/modules/wallet/wallet.dtos.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.model.d.ts +5 -26
- package/dist/modules/wallet/wallet.model.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.query.d.ts +2 -1
- package/dist/modules/wallet/wallet.query.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.repository.d.ts +49 -25
- package/dist/modules/wallet/wallet.repository.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.timezone.d.ts +87 -0
- package/dist/modules/wallet/wallet.timezone.d.ts.map +1 -0
- package/dist/modules/wallet/wallet.utils.d.ts +3 -2
- package/dist/modules/wallet/wallet.utils.d.ts.map +1 -0
- package/package.json +40 -29
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("zod"),t=require("uuid"),r=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var o=n(e);class a extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return a.schema.safeParse(e).success}static unknown(e){return new a({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return e.z.object({message:e.z.string(),statusCode:e.z.number().int(),error:e.z.string().optional(),details:e.z.object({}).optional()})}}const s={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Beneficiary:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},TeamManagement:{ViewMembers:"login.findAll",ViewMember:"login.findById",CreateMember:"login.create",UpdateMember:"login.update",ArchiveMember:"login.archive",UnArchiveMember:"login.unarchive",ResetPassword:"login.resetPassword"}};class i extends Error{requiredPermissions;constructor(e){super(e.message??`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(t){const r=e.z.union([e.z.enum(Object.values(s.Profile)),e.z.enum(Object.values(s.Beneficiary)),e.z.enum(Object.values(s.Payment)),e.z.enum(Object.values(s.Payout)),e.z.enum(Object.values(s.Transfer)),e.z.enum(Object.values(s.Wallet))]);return e.z.object({name:e.z.literal("PermissionError").nullish(),message:e.z.string(),requiredPermissions:e.z.array(r)}).safeParse(t).success}}const c=e=>"function"==typeof(null==e?void 0:e.passthrough);e.z.object({name:e.z.literal("ZodError"),issues:e.z.array(e.z.object({path:e.z.array(e.z.union([e.z.string(),e.z.number()])),message:e.z.string().optional(),code:e.z.nativeEnum(e.z.ZodIssueCode)}).catchall(e.z.any()))});const u=Symbol("ContractNoBody"),d=e=>"method"in e&&"path"in e,l=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,o,a,s,i;return d(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(s=null==t?void 0:t.baseHeaders,i=r.headers,c(s)?c(i)?s.merge(i):s:c(i)?i:Object.assign({},s,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(o=r.validateResponseOnClient)&&void 0!==o?o: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,l(r,t)]})),p=Symbol("ContractPlainType"),h=()=>({router:(e,t)=>l(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>p,body:()=>p,type:()=>p,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>u}),m=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("&"):"",y=e=>e?Object.keys(e).flatMap(t=>f(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",f=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>f(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>f(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class g extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const b=async({route:e,path:t,method:r,headers:n,body:o,validateResponse:a,fetchOptions:s})=>{const i=await fetch(t,{...s,method:r,headers:n,body:o}),c=i.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t={status:i.status,body:await i.json(),headers:i.headers},r=e.responses[t.status];return(null!=a?a:e.validateResponseOnClient)&&"function"==typeof(null==(u=r)?void 0:u.safeParse)?{...t,body:r.parse(t.body)}:t}var u;return(null==c?void 0:c.includes("text/"))?{status:i.status,body:await i.text(),headers:i.headers}:{status:i.status,body:await i.blob(),headers:i.headers}},N=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},v=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),I=(e,t,r,n,o)=>{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}),s=((e,t=!1)=>{const r=t?m(e):y(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,o);return`${t}${a}${s}`},w=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const o=((e,t,r)=>{const{query:n,params:o,body:a,headers:s,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...p}=r||{},h={...t,...c};return{path:I(n,h.baseUrl,o,e,!!h.jsonQuery),clientArgs:h,route:e,body:a,query:n,extraInputArgs:p,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...s}}})(e,t,n),a=await(e=>{const{path:t,clientArgs:r,route:n,body:o,query:a,extraInputArgs:s,headers:i,fetchOptions:c}=e,u=r.api||b,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&v(d),...v(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let p={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:o,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?p={...p,contentType:"multipart/form-data",body:o instanceof FormData?o:N(o)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?p={...p,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...p.headers},body:"string"==typeof o?o:new URLSearchParams(o)}:null!=o&&(p={...p,contentType:"application/json",headers:{"content-type":"application/json",...p.headers},body:JSON.stringify(o)})),u({...p,...s})})(o);if(!t.throwOnUnknownStatus)return a;if(r.includes(a.status.toString()))return a;throw new g(a,r)}},S=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>d(r)?[e,w(r,t)]:[e,S(r,t)]));let A;class _{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){if(this.token&&this.token.trim().length>0)return this.token;if(A){const e=A();if(e&&e.trim().length>0)return e}return""}get client(){const e={baseUrl:this.root?`${this.root}/${this.endpoint}`:`https://api.afloat.money/v1/${this.endpoint}`,baseHeaders:{token:this.getToken(),"x-request-id":t.v4()}};return S(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;if(400===e.status){const t=o.default.object({statusCode:o.default.number(),message:o.default.string(),error:o.default.string(),details:o.default.record(o.default.string()).optional()}).safeParse(e.body);if(t.success)throw new a(t.data);throw new a({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===e.status)throw new a({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new a({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new a({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});const r=e.status||502;throw new a({message:`We encountered an error trying to process your request. Please try again later (upstream status ${r}).`,statusCode:r,error:"UNKNOWN_ERROR"})}}var O,C;exports.FilterOperator=void 0,(O=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",O.NOT_EQUALS="neq",O.LESS_THAN="lt",O.LESS_THAN_OR_EQUAL="lte",O.GREATER_THAN="gt",O.GREATER_THAN_OR_EQUAL="gte",O.LIKE="like",O.LIKE_LOWER="likeLower",O.IS_NULL="isNull",O.IS_NOT_NULL="isNotNull",O.IN="in",exports.SortDirection=void 0,(C=exports.SortDirection||(exports.SortDirection={})).ASC="asc",C.DESC="desc";const P=Symbol("query-builder-type");class B{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*"};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}}[P]="query-builder";static is(e){return null!==e&&"object"==typeof e&&P in e&&"query-builder"===e[P]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){if(e){const t=e instanceof Date?e.toISOString():e;this.whereGreaterThanOrEqual("createdAt",t)}if(t){const e=t instanceof Date?t.toISOString():t;this.whereLessThanOrEqual("createdAt",e)}return this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new B(e)}}const z=e.z.object({page:e.z.coerce.number().int().min(1).default(1),limit:e.z.coerce.number().int().min(1).max(100).default(10)}),T=e.z.object({page:e.z.number().int().min(1),limit:e.z.number().int().min(1),total:e.z.number().int().min(0),totalPages:e.z.number().int().min(0),hasNext:e.z.boolean(),hasPrev:e.z.boolean()});class E{page;limit;total;constructor(e,t,r){if(this.page=e,this.limit=t,this.total=r,e<1)throw new Error("Page must be >= 1");if(t<1)throw new Error("Limit must be >= 1");if(r<0)throw new Error("Total must be >= 0")}get totalPages(){return Math.ceil(this.total/this.limit)}get hasNext(){return this.page<this.totalPages}get hasPrev(){return this.page>1}get offset(){return(this.page-1)*this.limit}get isFirstPage(){return 1===this.page}get isLastPage(){return this.page===this.totalPages}nextPage(){return this.hasNext?new E(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new E(this.page-1,this.limit,this.total):null}toJSON(){return{page:this.page,limit:this.limit,total:this.total,totalPages:this.totalPages,hasNext:this.hasNext,hasPrev:this.hasPrev}}}const D={profileDTOSchema:e.z.object({id:e.z.string(),firstName:e.z.string().nullish(),lastName:e.z.string().nullish(),displayName:e.z.string(),phone:e.z.string().nullish(),accountNo:e.z.string().min(1),email:e.z.string().email().nullish(),autoApprove:e.z.boolean().nullish()})},x=e.z.object({id:e.z.string(),firstName:e.z.string().nullable().optional(),lastName:e.z.string().nullable().optional(),displayName:e.z.string(),phone:e.z.string().nullable().optional(),accountNo:e.z.string(),email:e.z.string().nullable().optional(),autoApprove:e.z.boolean().nullable().optional(),_version:e.z.string().optional().default("1.0")});class R{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return D.profileDTOSchema}constructor(e){this._id=e.id,this._firstName=e.firstName,this._lastName=e.lastName,this._displayName=e.displayName,this._phone=e.phone,this._accountNo=e.accountNo,this._email=e.email,this._autoApprove=e.autoApprove}static create(e){return new R({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove})}get id(){return this._id}get firstName(){return this._firstName}get lastName(){return this._lastName}get displayName(){return this._displayName}get phone(){return this._phone}get accountNo(){return this._accountNo}get email(){return this._email}get autoApprove(){return this._autoApprove}getName(){if(this._displayName&&""!==this._displayName.trim())return this._displayName;return`${this._firstName??""} ${this._lastName??""}`.trim()}validate(){try{return R.schema.safeParse(this.toJSON()).success}catch(e){return console.error("Profile validation error:",e),!1}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?R.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const n=t._autoApprove;return null==n||"boolean"==typeof n}toJSON(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=x.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return R.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return x.safeParse(e).success}}const J={loginDTO:o.default.object({id:o.default.string().min(1,"ID is required"),profileId:o.default.string().min(1,"Profile ID is required"),name:o.default.string().min(1,"Name is required"),identity:o.default.string().email("Identity must be a valid email address"),type:o.default.string().min(1,"Type is required"),roleId:o.default.string().min(1,"Role ID is required"),isActive:o.default.boolean(),isArchived:o.default.boolean(),resetPassword:o.default.boolean(),createdAt:o.default.string().datetime("Invalid creation timestamp"),updatedAt:o.default.string().datetime("Invalid update timestamp"),access:o.default.array(o.default.string())})},M=e.z.object({id:e.z.string(),profileId:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),resetPassword:e.z.boolean(),createdAt:e.z.string(),updatedAt:e.z.string(),access:e.z.array(e.z.string()),_version:e.z.string().optional().default("1.0")});class j{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;_permissionMap;constructor(e,t,r,n,o,a,s,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=o,this._roleId=a,this._isActive=s,this._isArchived=i,this._resetPassword=c,this._createdAt=u,this._updatedAt=d,this._access=l,this._permissionMap={},this._access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){const t=J.loginDTO.parse(e);return new j(t.id,t.profileId,t.name,t.identity,t.type,t.roleId,t.isActive,t.isArchived,t.resetPassword,new Date(t.createdAt),new Date(t.updatedAt),t.access)}get id(){return this._id}get profileId(){return this._profileId}get name(){return this._name}get identity(){return this._identity}get type(){return this._type}get roleId(){return this._roleId}get isActive(){return this._isActive}get isArchived(){return this._isArchived}get resetPassword(){return this._resetPassword}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get access(){return this._access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=M.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const n=r.data;return j.from({id:n.id,profileId:n.profileId,name:n.name,identity:n.identity,type:n.type,roleId:n.roleId,isActive:n.isActive,isArchived:n.isArchived,resetPassword:n.resetPassword,createdAt:n.createdAt,updatedAt:n.updatedAt,access:n.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return M.safeParse(e).success}}const F=o.default.object({id:o.default.string(),name:o.default.string(),description:o.default.string().nullable().optional(),access:o.default.array(o.default.string()),createdAt:o.default.string(),updatedAt:o.default.string(),_version:o.default.string().optional().default("1.0")});class k{id;name;description;permissions;createdAt;updatedAt;constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.permissions=new Set(e.access),this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}hasPermission(e){return this.permissions.has(e)}static from(e){try{if(!e?.id||!e?.name||!Array.isArray(e?.access))return;return new k(e)}catch(e){return void console.error("Error creating Role:",e)}}toJSON(){return{id:this.id,name:this.name,description:this.description,access:Array.from(this.permissions),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=F.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const n=r.data;return k.from({id:n.id,name:n.name,description:n.description,access:n.access,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return F.safeParse(e).success}}const L=o.default.object({companyProfile:x,role:F.optional(),_version:o.default.string().optional().default("1.0")});class ${_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return R.is(e.companyProfile)?new $(e):void console.error("Invalid company profile")}catch(e){return void console.error("Error creating CompanyMembership:",e)}}get companyProfile(){return this._companyProfile}get role(){return this._role}toJSON(){return{companyProfile:this._companyProfile.toJSON(),role:this._role?.toJSON(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=L.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,o=R.fromJSON(n.companyProfile),a=n.role?k.fromJSON(n.role):void 0;return o?$.from({companyProfile:o,role:a}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return L.safeParse(e).success}}const q=o.default.object({logIn:M,companyProfile:x,role:F.optional(),_version:o.default.string().optional().default("1.0")});class U{_logIn;_membership;constructor(e){this._logIn=e.logIn,this._membership=e.membership}static from(e){try{if(!e.logIn||!e.companyProfile)return void console.error("Missing required User fields");const t=$.from({companyProfile:e.companyProfile,role:e.role});return t?new U({logIn:e.logIn,membership:t}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get login(){return this._logIn}get membership(){return this._membership}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=q.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,o=j.fromJSON(n.logIn),a=R.fromJSON(n.companyProfile),s=n.role?k.fromJSON(n.role):void 0;if(!o||!a)return void console.error("Failed to reconstruct nested objects from UserJSON");const i=$.from({companyProfile:a,role:s});return i?new U({logIn:o,membership:i}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return q.safeParse(e).success}}const V={logInRequestDTO:e.z.object({type:e.z.string().default("password"),identity:e.z.string().email(),password:e.z.string()}),logInResponseDTO:e.z.object({profile:D.profileDTOSchema,token:e.z.string(),access:e.z.array(e.z.string()),resetPassword:e.z.boolean()}),accessResponseDTO:e.z.array(e.z.string()),resetPasswordRequestDTO:e.z.object({currentPassword:e.z.string(),newPassword:e.z.string()}),emptyResponseDTO:e.z.object({})},W=h().router({logIn:{method:"POST",path:"/login",body:V.logInRequestDTO,responses:{201:V.logInResponseDTO,400:V.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:V.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:V.resetPasswordRequestDTO,responses:{200:V.emptyResponseDTO,400:V.emptyResponseDTO}}}),H=h().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:J.loginDTO}}});class K extends _{constructor(e){super("login",H,e)}async getIdentity(){const e=await this.client.getUserCredentials();if(200===e.status)return e.body;throw new Error(`Failed to get user identity. Status: ${e.status}`)}}const G=e.z.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),Z=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Role name is required"),description:e.z.string().nullable().optional(),access:e.z.array(e.z.string()),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Q=e.z.object({id:e.z.string().min(1),name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Invalid email address"),type:e.z.string().min(1,"Team member type is required"),profileId:e.z.string().min(1,"Profile ID is required"),roleId:e.z.string().min(1,"Role ID is required"),resetPassword:e.z.boolean(),isActive:e.z.boolean(),isArchived:e.z.boolean(),role:Z.optional(),createdAt:e.z.string().datetime("Invalid creation timestamp"),updatedAt:e.z.string().datetime("Invalid update timestamp")}),Y={role:Z,teamMember:Q,teamMemberQueryParams:e.z.object({id:e.z.string().min(1).optional(),name:e.z.string().min(1).optional(),identity:e.z.string().email("Invalid email address").optional(),type:e.z.string().min(1).optional(),profileId:e.z.string().min(1).optional(),roleId:e.z.string().min(1).optional(),resetPassword:e.z.number().optional(),isActive:e.z.number().optional(),isArchived:e.z.number().optional(),createdAt:e.z.string().datetime("Invalid creation timestamp").optional(),updatedAt:e.z.string().datetime("Invalid update timestamp").optional(),eager:e.z.string().optional()}),createTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name is required"),identity:e.z.string().email("Valid email address is required"),password:G.optional(),roleId:e.z.string().optional(),resetPassword:e.z.boolean().optional()}),updateTeamMemberRequest:e.z.object({name:e.z.string().min(1,"Team member name cannot be empty").optional(),roleId:e.z.string().min(1,"Role ID cannot be empty").optional(),password:G.optional(),resetPassword:e.z.boolean().optional(),isActive:e.z.boolean().optional()}),resetPasswordRequest:e.z.object({newPassword:G.optional(),sendNotification:e.z.boolean().optional()}),createTeamMemberResponse:e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string(),type:e.z.string(),profileId:e.z.string(),resetPassword:e.z.boolean(),roleId:e.z.string(),isActive:e.z.boolean(),isArchived:e.z.boolean(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}),password:G},X=h().router({getTeamMembers:{method:"GET",path:"/login",query:Y.teamMemberQueryParams,responses:{200:e.z.array(Y.teamMember),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all team members",description:"Retrieve a list of all team member accounts in the system"},getTeamMember:{method:"GET",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),query:Y.teamMemberQueryParams,responses:{200:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:Y.createTeamMemberRequest,responses:{201:Y.createTeamMemberResponse,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),409:e.z.object({message:e.z.string().optional()})},summary:"Create new team member",description:"Create a new team member account with specified role and permissions"},updateTeamMember:{method:"PATCH",path:"/login/:id",pathParams:e.z.object({id:e.z.string()}),body:Y.updateTeamMemberRequest,responses:{200:Y.teamMember,400:e.z.object({message:e.z.string().optional(),errors:e.z.array(e.z.string()).optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Update team member",description:"Update team member information, role, status, or force password reset"},archiveTeamMember:{method:"POST",path:"/login/:id/archive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{201:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:e.z.object({id:e.z.string()}),body:e.z.object({}),responses:{201:Y.teamMember,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:e.z.object({id:e.z.string()}),body:Y.resetPasswordRequest,responses:{201:e.z.object({success:e.z.boolean()}),400:e.z.object({message:e.z.string().optional()}),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Reset team member password",description:"Reset a team member's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:e.z.array(Y.role),401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:e.z.object({id:e.z.string()}),responses:{200:Y.role,401:e.z.object({message:e.z.string().optional()}),403:e.z.object({message:e.z.string().optional()}),404:e.z.object({message:e.z.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),ee=o.default.object({id:o.default.string(),name:o.default.string(),identity:o.default.string(),type:o.default.string(),profileId:o.default.string(),roleId:o.default.string(),resetPassword:o.default.boolean(),isActive:o.default.boolean(),isArchived:o.default.boolean(),role:F.optional(),createdAt:o.default.string(),updatedAt:o.default.string(),_version:o.default.string().optional().default("1.0")});class te{id;name;identity;type;profileId;roleId;resetPassword;isActive;isArchived;role;createdAt;updatedAt;permissions;constructor(e){if(this.id=e.id,this.name=e.name,this.identity=e.identity,this.type=e.type,this.profileId=e.profileId,this.roleId=e.roleId,this.resetPassword=e.resetPassword,this.isActive=e.isActive,this.isArchived=e.isArchived,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.permissions=new Set(e.role?.access??[]),e.role)try{this.role=new k(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new te(e):void console.error("Missing required TeamMember fields:",e)}catch(e){return void console.error("Error creating TeamMember:",e)}}static fromJson(e){try{const t=JSON.parse(e);return te.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>te.from(e)).filter(Boolean)}can(e){return this.permissions.has(e)}canAny(e){return e.some(e=>this.permissions.has(e))}canAll(e){return e.every(e=>this.permissions.has(e))}isAccountActive(){return this.isActive}isAccountArchived(){return this.isArchived}needsPasswordReset(){return this.resetPassword}getAccountStatus(){return this.isArchived?{status:"archived",label:"Archived",color:"default",description:"Account has been archived and is no longer accessible"}:this.isActive?this.resetPassword?{status:"password_reset_required",label:"Password Reset Required",color:"warning",description:"User must reset their password on next login"}:{status:"active",label:"Active",color:"success",description:"Account is active and ready to use"}:{status:"inactive",label:"Inactive",color:"error",description:"Account has been deactivated by an administrator"}}getRoleName(){return this.role?.name??""}getCreatedDate(){return this.createdAt.toLocaleDateString()}getLastUpdateInfo(){const e=(new Date).getTime()-this.updatedAt.getTime(),t=Math.floor(e/864e5);return 0===t?"Today":1===t?"Yesterday":t<7?`${t} days ago`:t<30?`${Math.floor(t/7)} weeks ago`:this.updatedAt.toLocaleDateString()}toJSON(){return{id:this.id,name:this.name,identity:this.identity,type:this.type,profileId:this.profileId,roleId:this.roleId,resetPassword:this.resetPassword,isActive:this.isActive,isArchived:this.isArchived,role:this.role?.toJSON(),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ee.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,o=n.role?{id:n.role.id,name:n.role.name,description:n.role.description,access:n.role.access,createdAt:n.role.createdAt,updatedAt:n.role.updatedAt}:void 0;return te.from({id:n.id,name:n.name,identity:n.identity,type:n.type,profileId:n.profileId,roleId:n.roleId,resetPassword:n.resetPassword,isActive:n.isActive,isArchived:n.isArchived,role:o,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return ee.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>te.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing TeamMember JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}class re extends _{constructor(e){super("admin",X,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),n=this.handleResponse(r,200),o=te.from(n);if(!o)throw new Error("Invalid team member data received from server");return o}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e},body:{}}),r=this.handleResponse(t,201),n=te.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e},body:{}}),r=this.handleResponse(t,201),n=te.from(r);if(!n)throw new Error("Invalid team member data received from server");return n}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,201)}async getAllTeamMembers(e={eager:"roleId"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return te.createMany(r)}async getTeamMember(e,t={eager:"roleId"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),o=te.from(n);if(!o)throw new Error("Invalid team member data received from server");return o}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=k.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),n=k.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}var ne;exports.BeneficiaryType=void 0,(ne=exports.BeneficiaryType||(exports.BeneficiaryType={})).BANK="Bank",ne.MOBILE="Mobile";const oe=e.z.nativeEnum(exports.BeneficiaryType),ae=e.z.object({displayName:e.z.string().min(1,"Display name is required"),accountNo:e.z.string().min(1,"Account number is required"),channel:e.z.string().min(1,"Channel is required"),type:oe}),se={beneficiaryDTO:e.z.object({id:e.z.string().min(1,"Beneficiary id is required"),profileId:e.z.string(),createdAt:e.z.string().datetime(),updatedAt:e.z.string().datetime()}).merge(ae),beneficiaryInputDTO:ae,beneficiaryType:oe},ie=e.z.object({type:e.z.literal(exports.BeneficiaryType.MOBILE),name:e.z.string().min(1),phoneNumber:r.E164PhoneNumberFormatSchema,mnoId:r.MobileMoneyProviderIdSchema,_version:e.z.string().optional().default("1.0")}),ce=e.z.object({type:e.z.literal(exports.BeneficiaryType.BANK),accName:e.z.string().min(1),swiftCode:e.z.union([r.TZBankSWIFTCodeSchema,r.KEBankSWIFTCodeSchema]),countryCode:r.ISO2CountryCodeSchema,accNo:e.z.string().min(1),_version:e.z.string().optional().default("1.0")}),ue=e.z.discriminatedUnion("type",[ie,ce]);class de extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class le{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===exports.BeneficiaryType.MOBILE}get isBank(){return this.type===exports.BeneficiaryType.BANK}get displayName(){return this.accountName}}class pe extends le{name;phoneNumber;mnoId;constructor(e,t,r){super(exports.BeneficiaryType.MOBILE,t.countryCode),this.name=e,this.phoneNumber=t;const n=pe.resolveMnoId(t,r),o=pe.checkInputs(e,t,n);if(!o.isValid)throw new de(o.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:n});this.mnoId=n}static resolveMnoId(e,t){return r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)?t:r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,n){const o=[];return e?.trim()||o.push("Name is required and cannot be empty"),t?.validate()||o.push("Invalid phone number"),n?r.MobileMoneyProviderHelpers.validateProviderForPhoneNumber(t,n)||o.push(`Invalid MNO ${n} for phone number ${t.e164Format}`):o.push(r.MobileMoneyProviderHelpers.requiresExplicitProvider(t.countryCode)?`MNO must be explicitly provided for phone numbers in ${t.countryCode}`:`Failed to determine MNO for phone number ${t.e164Format}`),{isValid:0===o.length,errors:o,warnings:[]}}static pickMnoIdFromDTO(e,t){const n=pe.pickMnoIdFromPayoutChannel(e.countryCode,t);if(n)return n;if(r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return r.MobileMoneyProviderHelpers.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const o=r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e);if(o)return o.id;console.warn(`Failed to auto-detect MNO for phone number ${e.e164Format}`)}static pickMnoIdFromPayoutChannel(e,t){if("string"!=typeof t)return;const[n,o,a]=t.split("-");return"B2C"===a&&"BANK"!==o&&n===e&&r.MobileMoneyProviderHelpers.isProviderSupported(e,o)?o:void 0}static from(e){try{return new pe(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.MOBILE)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,n=r.PhoneNumber.from(t);if(!n)return void console.error(`Failed to parse phone number ${t}`);const o=pe.pickMnoIdFromDTO(n,e.channel);return o?pe.from({name:e.displayName,phoneNumber:n,mnoId:o}):void 0}static fromBeneficiaryDTO(e){return pe.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=r.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);const n=pe.pickMnoIdFromDTO(t,e.channel);return n?pe.from({name:e.payeeName,phoneNumber:t,mnoId:n}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.MOBILE&&(!("string"!=typeof t.name||!t.name.trim())&&(!!r.PhoneNumber.is(t.phoneNumber)&&("string"==typeof t.mnoId&&r.MobileMoneyProviderHelpers.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return pe.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return pe.checkInputs(this.name,this.phoneNumber,this.mnoId)}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(r.PhoneNumberFormat.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode)}toJSON(){return{type:exports.BeneficiaryType.MOBILE,name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=ie.safeParse(t);if(!n.success)return void console.error("Invalid MobileBeneficiaryJSON:",n.error.flatten());const o=r.PhoneNumber.from(n.data.phoneNumber);if(!o)return;return pe.from({name:n.data.name,phoneNumber:o,mnoId:n.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return pe.fromJSON(e)}static isJSON(e){return ie.safeParse(e).success}}class he extends le{accName;bank;accNo;constructor(e,t,r){super(exports.BeneficiaryType.BANK,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=he.checkInputs(e,t,r);if(!n.isValid)throw new de(n.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,n){const o=[];return r.BankHelpers.validateAccountName(e)||o.push("Invalid account name"),r.Bank.is(t)?r.BankHelpers.validateAccountNumber(n,t.countryCode)||o.push("Invalid account number"):o.push("Invalid bank reference"),{isValid:0===o.length,errors:o,warnings:[]}}static from(e){try{return new he(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.BANK)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const n=r.BankHelpers.getCountryFromSwiftCode(t);if(!n)return void console.error(`Could not identify country from SWIFT code: ${t}`);const o=r.Bank.fromBIC(t,n);if(o)return he.from({accName:e.displayName,bank:o,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromBeneficiaryDTO(e){return he.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank — expected 'swiftcode:accountno'");const[n,o]=t,a=r.Bank.fromBIC(n,e.countryCode);if(a)return he.from({accName:e.payeeName,bank:a,accNo:o});console.error(`Bank with SWIFT code ${n} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.BANK&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!r.Bank.is(t.bank)&&(r.BankHelpers.validateAccountName(t.accName)&&r.BankHelpers.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return he.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return he.checkInputs(this.accName,this.bank,this.accNo)}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.bic}get channelName(){return this.bank.shortName}toJSON(){return{type:exports.BeneficiaryType.BANK,accName:this.accName,swiftCode:this.bank.bic,countryCode:this.bank.countryCode,accNo:this.accNo,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=ce.safeParse(t);if(!n.success)return void console.error("Invalid BankBeneficiaryJSON:",n.error.flatten());const o=n.data;if(!r.CountryHelpers.isISO2Code(o.countryCode))return;const a=r.Bank.fromBIC(o.swiftCode,o.countryCode);if(!a)return;return he.from({accName:o.accName,bank:a,accNo:o.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return he.fromJSON(e)}static isJSON(e){return ce.safeParse(e).success}}class me{static fromInputDTO(e){return me.fromDTO(e)}static fromBeneficiaryDTO(e){return me.fromDTO(e)}static fromPayoutDTO(e){return e.msisdn.includes(":")?he.fromPayoutDTO(e):pe.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ue.safeParse(t);if(!r.success)return;return r.data.type===exports.BeneficiaryType.MOBILE?pe.fromJSON(r.data):he.fromJSON(r.data)}catch{return}}static fromJSONString(e){return me.fromJSON(e)}static is(e){return pe.is(e)||he.is(e)}static isJSON(e){return ue.safeParse(e).success}static fromDTO(e){return e.type===exports.BeneficiaryType.MOBILE?pe.fromInputDTO(e):he.fromInputDTO(e)}}const ye={fromInputDTO:e=>me.fromInputDTO(e),fromBeneficiaryDTO:e=>me.fromBeneficiaryDTO(e),fromPayoutDTO:e=>me.fromPayoutDTO(e),fromJSON:e=>me.fromJSON(e),fromJSONString:e=>me.fromJSONString(e),is:e=>me.is(e),isJSON:e=>me.isJSON(e)},fe=se.beneficiaryDTO.extend({_version:e.z.string().optional().default("1.0")});class ge{_id;_profileId;_displayName;_accountNo;_channel;_type;_createdAt;_updatedAt;_info;_infoComputed=!1;constructor(e){const t=se.beneficiaryDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._displayName=t.displayName,this._accountNo=t.accountNo,this._channel=t.channel,this._type=t.type,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt}get id(){return this._id}get profileId(){return this._profileId}get displayName(){return this._displayName}get type(){return this._type}get createdAt(){return new Date(this._createdAt)}get updatedAt(){return new Date(this._updatedAt)}get info(){return this._infoComputed||(this._infoComputed=!0,this._info=me.fromBeneficiaryDTO(this.toDTO())),this._info}get accNo(){const e=this.info;return e?e.accountNumber:this._accountNo}get accName(){return this._displayName}get accNoLabel(){return this.type===exports.BeneficiaryType.MOBILE?"Phone Number":this.type===exports.BeneficiaryType.BANK?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===exports.BeneficiaryType.MOBILE?"Channel":this.type===exports.BeneficiaryType.BANK?"Bank":"Channel"}get accNameLabel(){return this.type===exports.BeneficiaryType.MOBILE?"Full Name":this.type===exports.BeneficiaryType.BANK?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new ge(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new ge(e)}static createMany(e){return e.map(e=>new ge(e))}static createSafe(e){return ge.from(e)??null}static canConstruct(e){return se.beneficiaryDTO.safeParse(e).success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return fe.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{...this.toDTO(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=t&&"object"==typeof t&&"data"in t?t.data:t,n=fe.safeParse(r);if(!n.success)return void console.error("Invalid BeneficiaryJSON:",n.error.flatten());const o=n.data,{_version:a,...s}=o;return ge.from(s)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return ge.fromJSON(e)}static isBeneficiaryJSON(e){return fe.safeParse(e).success}toDTO(){return{id:this._id,profileId:this._profileId,displayName:this._displayName,accountNo:this._accountNo,channel:this._channel,type:this._type,createdAt:this._createdAt,updatedAt:this._updatedAt}}}class be{canHandle(e){return e.type===exports.BeneficiaryType.MOBILE&&pe.is(e)}createInput(e){if(pe.is(e))return{type:exports.BeneficiaryType.MOBILE,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class Ne{canHandle(e){return e.type===exports.BeneficiaryType.BANK&&he.is(e)}createInput(e){if(he.is(e))return{type:exports.BeneficiaryType.BANK,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class ve{handlers=[new be,new Ne];resolve(e){const t=this.handlers.find(t=>t.canHandle(e));if(!t)throw new Error("Please check your data and try again");return t.createInput(e)}}const Ie=h().router({createBeneficiary:{method:"POST",path:"/",body:se.beneficiaryInputDTO,responses:{201:se.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:se.beneficiaryInputDTO,responses:{200:se.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:e.z.object({orderByDesc:e.z.string()}),responses:{200:e.z.array(se.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:se.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:e.z.object({}),responses:{200:e.z.object({})}}});var we,Se,Ae;exports.PayoutChannel=void 0,(we=exports.PayoutChannel||(exports.PayoutChannel={})).TZ_TIGO_B2C="TZ-TIGO-B2C",we.TZ_VODACOM_B2C="TZ-VODACOM-B2C",we.TZ_AIRTEL_B2C="TZ-AIRTEL-B2C",we.TZ_HALOTEL_B2C="TZ-HALOTEL-B2C",we.KE_SAFARICOM_B2C="KE-SAFARICOM-B2C",we.TZ_BANK_B2C="TZ-BANK-B2C",we.KE_BANK_B2C="KE-BANK-B2C",exports.PayoutStatus=void 0,(Se=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",Se.PENDING="PENDING",Se.PAID="PAID",Se.FAILED="FAILED",Se.REJECTED="REJECTED",Se.REVERSED="REVERSED",Se.QUEUED="QUEUED",exports.PayoutApprovalStatus=void 0,(Ae=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",Ae.APPROVED="Approved",Ae.REJECTED="Rejected";const _e=e.z.object({id:e.z.string(),name:e.z.string(),identity:e.z.string()}),Oe=e.z.nativeEnum(exports.PayoutStatus),Ce=e.z.nativeEnum(exports.PayoutApprovalStatus),Pe=e.z.nativeEnum(exports.PayoutChannel),Be=e.z.union([e.z.string(),e.z.array(e.z.string())]).transform(e=>(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(e=>e.length>0)),ze=Be.pipe(e.z.array(Oe)),Te=Be.pipe(e.z.array(Ce)),Ee=e.z.object({channel:Pe,msisdn:e.z.string(),amount:e.z.coerce.number(),description:e.z.string(),notes:e.z.string().nullish()}),De=Ee.extend({payeeName:e.z.string()}),xe=Ee.extend({id:e.z.string(),profileId:e.z.string(),payeeName:e.z.string(),countryCode:e.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(e),{message:"Provided currency code is not a valid currency code."}),channel:e.z.string(),status:Oe,statusMessage:e.z.string(),partnerReference:e.z.string().nullish(),createdAt:e.z.coerce.date(),updatedAt:e.z.coerce.date(),actionedAt:e.z.coerce.date().nullish(),approvalStatus:Ce.nullish(),createdById:e.z.string().nullish(),actionedById:e.z.string().nullish(),createdBy:_e.nullish(),actionedBy:_e.nullish()}),Re=e.z.object({page:e.z.number().int().positive().default(1),limit:e.z.number().int().positive().max(100).default(10),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().datetime().nullish(),endDate:e.z.string().datetime().nullish(),payeeName:e.z.string().nullish(),msisdn:e.z.string().nullish(),msisdnIn:Be.nullish(),profileId:e.z.string().nullish(),id:e.z.string().nullish(),partnerReference:e.z.string().nullish(),channel:e.z.string().nullish(),channelIn:Be.nullish(),currencyCode:e.z.string().nullish(),status:Oe.nullish(),statusIn:ze.nullish(),approvalStatus:Ce.nullish(),approvalStatusIn:Te.nullish(),createdById:e.z.string().nullish(),createdByIdIn:Be.nullish(),actionedById:e.z.string().nullish(),actionedByIdIn:Be.nullish(),minAmount:e.z.number().min(0).nullish(),maxAmount:e.z.number().min(0).nullish(),search:e.z.string().nullish(),relations:e.z.array(e.z.string()).nullish()}),Je={PayoutDTO:xe,PayoutInputDTO:De,PayoutStatus:Oe,PayoutApprovalStatus:Ce,PayoutChannel:Pe,PayoutAuthorizer:_e,PayoutFilters:Re,PayoutURLQueryParams:e.z.object({page:e.z.string().transform(e=>parseInt(e)||1).optional(),limit:e.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:e.z.string().default("createdAt"),sortOrder:e.z.enum(["asc","desc"]).default("desc"),startDate:e.z.string().optional(),endDate:e.z.string().optional(),payeeName:e.z.string().optional(),msisdn:e.z.string().optional(),msisdnIn:Be.optional(),profileId:e.z.string().optional(),id:e.z.string().optional(),partnerReference:e.z.string().optional(),channel:e.z.string().optional(),channelIn:Be.optional(),status:e.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),statusIn:ze.optional(),approvalStatus:e.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),approvalStatusIn:Te.optional(),createdById:e.z.string().optional(),createdByIdIn:Be.optional(),actionedById:e.z.string().optional(),actionedByIdIn:Be.optional(),minAmount:e.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:e.z.string().transform(e=>parseFloat(e)).optional(),search:e.z.string().optional(),relations:e.z.array(e.z.string()).optional()})},Me=o.default.object({id:o.default.string(),profileId:o.default.string(),payeeName:o.default.string(),channel:o.default.string(),msisdn:o.default.string(),amount:o.default.number(),currencyCode:o.default.string(),countryCode:o.default.string(),description:o.default.string(),notes:o.default.string().nullish(),status:Je.PayoutStatus,statusMessage:o.default.string(),partnerReference:o.default.string().nullish(),createdAt:o.default.string(),updatedAt:o.default.string(),actionedAt:o.default.string().nullish(),approvalStatus:Je.PayoutApprovalStatus.nullish(),createdById:o.default.string().nullish(),actionedById:o.default.string().nullish(),createdBy:Je.PayoutAuthorizer.nullish(),actionedBy:Je.PayoutAuthorizer.nullish(),_version:o.default.string().optional().default("1.0")});class je{_id;_profileId;_payeeName;_channel;_msisdn;_amount;_currencyCode;_countryCode;_description;_notes;_status;_statusMessage;_partnerReference;_createdAt;_updatedAt;_actionedAt;_approvalStatus;_createdById;_actionedById;_createdBy;_actionedBy;constructor(e){const t=Je.PayoutDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._payeeName=t.payeeName,this._channel=t.channel,this._msisdn=t.msisdn,this._amount=t.amount,this._currencyCode=t.currencyCode,this._countryCode=t.countryCode,this._description=t.description,this._notes=t.notes,this._status=t.status,this._statusMessage=t.statusMessage,this._partnerReference=t.partnerReference,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt,this._actionedAt=t.actionedAt,this._approvalStatus=t.approvalStatus,this._createdById=t.createdById,this._actionedById=t.actionedById,this._createdBy=t.createdBy,this._actionedBy=t.actionedBy}get id(){return this._id}get profileId(){return this._profileId}get payeeName(){return this._payeeName}get channel(){return this._channel}get msisdn(){return this._msisdn}get amount(){return r.Amount.from(this._amount,this._currencyCode)}get description(){return this._description}get notes(){return this._notes}get status(){return this._approvalStatus===exports.PayoutApprovalStatus.REJECTED?exports.PayoutStatus.REJECTED:this._approvalStatus===exports.PayoutApprovalStatus.APPROVED?"FAILED"===this._status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:this._approvalStatus===exports.PayoutApprovalStatus.PENDING?exports.PayoutStatus.PENDING:this._status}get statusMessage(){return this._statusMessage}get partnerReference(){return this._partnerReference}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get actionedAt(){return this._actionedAt}get approvalStatus(){return this._approvalStatus}get createdById(){return this._createdById}get actionedById(){return this._actionedById}get createdBy(){return this._createdBy}get actionedBy(){return this._actionedBy}get beneficiaryInfo(){return me.fromPayoutDTO(this.toDTO())}get contactInfo(){return this.beneficiaryInfo}static create(e){return new je(e)}static createMany(e){return e.map(e=>new je(e))}static createSafe(e){try{return new je(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Je.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==je.createSafe(t.data)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return Me.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),actionedAt:this._actionedAt?.toISOString()??null,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=Me.safeParse(t);if(!n.success)return void console.error("Invalid PayoutJSON:",n.error.flatten());const o=n.data,a=o.currencyCode;if(!r.CurrencyHelpers.isCode(a))return void console.error("Invalid currency code:",a);const s=o.countryCode;if(!r.CountryHelpers.isISO2Code(s))return void console.error("Invalid country code:",s);const i={id:o.id,profileId:o.profileId,payeeName:o.payeeName,channel:o.channel,msisdn:o.msisdn,amount:o.amount,currencyCode:a,countryCode:s,description:o.description,notes:o.notes,status:o.status,statusMessage:o.statusMessage,partnerReference:o.partnerReference,createdAt:new Date(o.createdAt),updatedAt:new Date(o.updatedAt),actionedAt:o.actionedAt?new Date(o.actionedAt):null,approvalStatus:o.approvalStatus,createdById:o.createdById,actionedById:o.actionedById,createdBy:o.createdBy,actionedBy:o.actionedBy};return je.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return Me.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>je.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toDTO(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt,updatedAt:this._updatedAt,actionedAt:this._actionedAt,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy}}}const Fe="MOBILE TRANSFER ",ke="PAYOUT",Le="PAYOUT TO BANK",$e="TO_BANK",qe="PAYOUT TO MOBILE",Ue="TO_MOMO",Ve=o.default.object({text:o.default.string(),_version:o.default.string().optional().default("2.0")});class We{text;constructor(e){this.text=e}get mediumText(){return this.text.length>50?this.text.substring(0,47)+"...":this.text}get shortText(){return this.text.length>35?this.text.substring(0,32)+"...":this.text}static generateDefaultPayoutNarration(e){return pe.is(e)?We.generateMobilePayoutNarrationV2(e):he.is(e)?We.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${ke.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${ke.toUpperCase()} ${t.bic.trim()} ${n.trim()} ${r.trim()}`.toUpperCase()}getBeneficiaryDetails=()=>{const e=this.getBankBeneficiaryDetails(),t=this.getMobileBeneficiaryDetails();return e||(t||void 0)};getBankBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(Fe)&&(e=e.substring(16));try{if(e.startsWith(ke)){const t=e.replace(ke,"").trim().split(" ");if(t.length>=3){const e=t[0],n=t[1],o=t.slice(2).map(He).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=r.BankHelpers.getCountryFromSwiftCode(e);if(t){if(r.BankHelpers.validateSwiftCode(e,t)){const a=r.Bank.fromBIC(e,t);if(n&&o&&a)return new he(o,a,n)}}}}}if(e.startsWith($e)){const t=e.split("=>")[1].trim(),n=JSON.parse(t),o=n.account_number,a=n.account_name,s=n.swift_code,i=r.BankHelpers.getCountryFromSwiftCode(s);if(!i)return;if(!r.BankHelpers.validateSwiftCode(s,i))return;const c=r.Bank.fromBIC(s,i);if(o&&a&&c)return new he(a,c,o)}if(e.startsWith(Le)){const t=e.replace(Le,"").trim().split(" "),n=r.BankRegistry.getInstance().searchBanks("TZ",t[0]),o=n.length>0?n[0]:void 0,a=t[1],s=t.slice(2).map(He).join(" ");if(s&&a&&o)return new he(s,o,a)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(Fe)&&(e=e.substring(16));try{if(e.startsWith(ke)){const t=e.replace(ke,"").trim().split(" ");if(t.length>=2){const e=t[0],n=t.slice(1).map(He).join(" ");if(e.startsWith("+")){const t=r.PhoneNumber.from(e);if(t&&n)return new pe(n,t)}}}if(e.startsWith(Ue)){const t=e.split("=>")[1].trim(),n=JSON.parse(t),o=r.PhoneNumber.from(n.phone_number,{defaultCountry:"TZ"});let a=n.username;void 0===a&&(a="");let s=a.split(" ");if(s=s.filter(e=>e.trim().length>0),a=s.map(He).join(" "),o&&a)return new pe(a,o)}if(e.startsWith(qe)){const t=e.replace(qe,"").trim().split(" "),n=r.PhoneNumber.from(t[0],{defaultCountry:"TZ"}),o=t.slice(1).map(He).join(" ");if(n&&o)return new pe(o,n)}}catch(e){return}};static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getBeneficiaryDetails&&"function"==typeof t.toJson}catch(e){return!1}}toJSON(){return{text:this.text,_version:"2.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ve.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new We(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return Ve.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return We.fromJSON(e)}}function He(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const Ke=["TZ","KE"],Ge={TZ:exports.PayoutChannel.TZ_BANK_B2C,KE:exports.PayoutChannel.KE_BANK_B2C},Ze={TIGO:exports.PayoutChannel.TZ_TIGO_B2C,VODACOM:exports.PayoutChannel.TZ_TIGO_B2C,AIRTEL:exports.PayoutChannel.TZ_AIRTEL_B2C,HALOTEL:exports.PayoutChannel.TZ_HALOTEL_B2C},Qe="Invalid bank beneficiary info",Ye="Invalid phone number",Xe="The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",et="Wallet country does not match beneficiary country",tt="Wallet currency does not match payout amount currency",rt="Payout amount currency does not match the payout country currency",nt="Only TZ and KE bank payout channels are supported for now",ot="Only TZ and KE mobile money payout channels are supported for now",at="Mobile money provider is not supported for payouts in this country",st=e=>Ke.includes(e);class it{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}static isPhoneEligibleForPayout(e){const t=e.getNumberType();return t===r.PhoneNumberType.MOBILE||t===r.PhoneNumberType.FIXED_LINE_OR_MOBILE}}class ct{static resolve(e){const{wallet:t,receiver:r,amount:n}=e;return this.assertCompatibleWalletReceiverAndAmount(t,r,n),pe.is(r)?this.forMobile(r.phoneNumber,r.mnoId,t):this.forBank(r,t)}static forBank(e,t){if(!he.is(e))throw new Error(Qe);if(!st(t.countryCode))throw new Error(nt);if(t.countryCode!==e.countryCode)throw new Error(et);return Ge[t.countryCode]}static forMobile(e,t,n){if(!r.PhoneNumber.is(e))throw new Error(Ye);if(!st(n.countryCode)||!st(e.countryCode))throw new Error(ot);if(n.countryCode!==e.countryCode)throw new Error(et);if(!it.isPhoneEligibleForPayout(e))throw new Error(Xe);if("KE"===n.countryCode)return exports.PayoutChannel.KE_SAFARICOM_B2C;const o=r.MobileMoneyProviderHelpers.findById(t,e.countryCode);if(!o||!o.supportsDirection(r.TransactionDirection.PAYOUT))throw new Error(at);const a=Ze[o.id];if(!a)throw new Error(at);return a}static getChannelType(e){return this.isBankChannel(e)?r.ChannelType.BANK:r.ChannelType.MOBILE_MONEY}static getCountryCode(e){return e.slice(0,2)}static getProviderId(e){if(!this.isBankChannel(e))return e.split("-")[1]}static isBankChannel(e){return e.endsWith("-BANK-B2C")}static isMobileMoneyChannel(e){return!this.isBankChannel(e)}static assertCompatibleWalletReceiverAndAmount(e,t,n){if(e.countryCode!==t.countryCode)throw new Error(et);if(e.currencyCode!==n.currencyCode)throw new Error(tt);const o=r.Country.fromCode(e.countryCode)?.currencyCode;if(o&&n.currencyCode!==o)throw new Error(rt)}}class ut{getPayoutInput(e,t){const r=ct.resolve({...e,wallet:t});if(pe.is(e.receiver))return this.createMobileInput(e.receiver,e.amount,r,e.notes);if(he.is(e.receiver))return this.createBankInput(e.receiver,e.amount,r,e.notes);throw new Error("Cannot create payout input for unknown beneficiary info")}createMobileInput(e,t,n,o){const a=it.processNotes(o);return{channel:n,msisdn:e.phoneNumber.getWithFormat(r.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:a??We.generateDefaultPayoutNarration(e),payeeName:e.name,notes:a,amount:t.numericValue}}createBankInput(e,t,r,n){const o=it.processNotes(n);return{channel:r,msisdn:`${e.bank.bic}:${e.accNo}`,description:o??We.generateDefaultPayoutNarration(e),payeeName:e.accName,notes:o,amount:t.numericValue}}}const dt={bank:ct.forBank.bind(ct),mobile:ct.forMobile.bind(ct)},lt=h().router({getPayouts:{method:"GET",path:"",query:e.z.object({}),responses:{200:e.z.object({results:e.z.array(Je.PayoutDTO),total:e.z.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:e.z.object({rangeStart:e.z.number(),rangeEnd:e.z.number(),eager:e.z.string(),approvalStatus:Je.PayoutApprovalStatus,orderByDesc:e.z.string()}),responses:{200:e.z.object({results:e.z.array(Je.PayoutDTO),total:e.z.number()})}},postPayout:{method:"POST",path:"",body:Je.PayoutInputDTO,responses:{201:Je.PayoutDTO,400:a.schema}},approve:{method:"POST",path:"/:id/approve",body:e.z.object({action:e.z.enum(["Approve","Reject"]),notes:e.z.string().optional()}),responses:{201:Je.PayoutDTO,400:a.schema,401:a.schema,404:e.z.object({}),409:e.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Je.PayoutDTO,404:e.z.object({})}}}),pt=["approvalStatus","status","channel","msisdn","createdById","actionedById"];class ht extends B{static create(){return new ht}static fromFilters(e){return(new ht).applyFilters(e)}static fromUrlParams(e){try{const t=Je.PayoutURLQueryParams.parse(this.normalizeUrlParams(e)),r=Je.PayoutFilters.parse(t);return ht.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return ht.fromUrlParams(this.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ht.fromSearchParams(t)}static from(e){try{return null==e?new ht:B.is(e)?new ht(e.options):e instanceof URLSearchParams?ht.fromSearchParams(e):this.isUrlParamsRecord(e)?ht.fromUrlParams(e):ht.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery 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},r=t.eager;if("string"==typeof r){const e=r.replace(/^\[|\]$/g,"").split(",").map(e=>e.trim()).filter(Boolean);e.length>0&&(t.relations=e),delete t.eager}for(const e of pt){const r=e,n=`${e}In`,o=`${e}:in`,a=`${e}[]`,s=`${e}In[]`,i=t[r],c=ht.toStringList([t[n],t[o],t[a],t[s],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[o],delete t[a],delete t[s]}return t}static toStringList(e){const t=Array.isArray(e)?e.flatMap(e=>ht.toStringList(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereApprovalStatusIn(e){return this.whereInValues("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}wherePending(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.PENDING)}whereApproved(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.APPROVED)}whereRejected(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.REJECTED)}wherePaid(){return this.whereStatus(exports.PayoutStatus.PAID)}whereFailed(){return this.whereStatus(exports.PayoutStatus.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereMsisdnIn(e){return this.whereInValues("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}whereCreatedById(e){return this.where("createdById",e)}whereCreatedByIdIn(e){return this.whereInValues("createdById",e)}whereActionedById(e){return this.where("actionedById",e)}whereActionedByIdIn(e){return this.whereInValues("actionedById",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((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.approvalStatusIn?.length?this.whereApprovalStatusIn(e.approvalStatusIn):e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdnIn?.length?this.whereMsisdnIn(e.msisdnIn):e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.createdByIdIn?.length?this.whereCreatedByIdIn(e.createdByIdIn):e.createdById&&this.whereCreatedById(e.createdById),e.actionedByIdIn?.length?this.whereActionedByIdIn(e.actionedByIdIn):e.actionedById&&this.whereActionedById(e.actionedById),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,n=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:o}=e,a=o||"TZS";if(!r.CurrencyHelpers.isCode(a))return console.warn("Amount filter requires a valid currency code"),this;if(t&&n){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=r.Amount.from(e.minAmount,a),n=r.Amount.from(e.maxAmount,a);t&&n&&this.whereAmountBetween(t,n)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):n&&this.whereLessThanOrEqual("amount",e.maxAmount)}return e.search&&this.whereSearch(e.search),e.relations?.length&&this.with(e.relations),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,payeeName:e.payeeName,msisdn:e.msisdn,msisdnIn:e.msisdnIn,profileId:e.profileId,createdById:e.createdById,createdByIdIn:e.createdByIdIn,actionedById:e.actionedById,actionedByIdIn:e.actionedByIdIn,id:e.id,partnerReference:e.partnerReference,channel:e.channel,channelIn:e.channelIn,status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,approvalStatusIn:this.getValidApprovalStatuses(e.approvalStatusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search,relations:this.options.includes?.length?[...this.options.includes]:void 0}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&("relations"===e&&Array.isArray(r)?r.length>0&&(t.eager=`[${r.join(",")}]`):Array.isArray(r)?r.length>0&&(t[e]=r.join(",")):t[e]=String(r))}),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}withStatusIn(e){const t=this.clone();return e?.length&&t.whereStatusIn(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withApprovalStatusIn(e){const t=this.clone();return e?.length&&t.whereApprovalStatusIn(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}withChannelIn(e){const t=this.clone();return e?.length&&t.whereChannelIn(e),t}withMsisdnIn(e){const t=this.clone();return e?.length&&t.whereMsisdnIn(e),t}withCreatedById(e){const t=this.clone();return e&&t.whereCreatedById(e),t}withCreatedByIdIn(e){const t=this.clone();return e?.length&&t.whereCreatedByIdIn(e),t}withActionedById(e){const t=this.clone();return e&&t.whereActionedById(e),t}withActionedByIdIn(e){const t=this.clone();return e?.length&&t.whereActionedByIdIn(e),t}includeDefaultRelations(){return this.with(["createdBy","actionedBy"])}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.msisdnIn?.length||e.profileId||e.createdById||e.createdByIdIn?.length||e.actionedById||e.actionedByIdIn?.length||e.id||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.approvalStatus||e.approvalStatusIn?.length||e.minAmount||e.maxAmount||e.search)}describeFilters(e){const t=[],n=this.toFilters(),o=e?.formatDate??(e=>e);if(n.sortBy){const e="asc"===n.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(n.sortBy)} (${e})`})}if(n.startDate&&n.endDate?t.push({label:"Date Range",value:`${o(n.startDate)} — ${o(n.endDate)}`}):n.startDate?t.push({label:"From",value:o(n.startDate)}):n.endDate&&t.push({label:"Until",value:o(n.endDate)}),n.statusIn?.length?t.push({label:"Status",value:n.statusIn.join(", ")}):n.status&&t.push({label:"Status",value:n.status}),n.approvalStatusIn?.length?t.push({label:"Approval Status",value:n.approvalStatusIn.join(", ")}):n.approvalStatus&&t.push({label:"Approval Status",value:n.approvalStatus}),n.channelIn?.length?t.push({label:"Channel",value:n.channelIn.join(", ")}):n.channel&&t.push({label:"Channel",value:n.channel}),void 0!==n.minAmount&&void 0!==n.maxAmount){const e=Number(n.minAmount),o=Number(n.maxAmount);if(Number.isFinite(e)&&Number.isFinite(o)){const n=r.Amount.from(e,"TZS"),a=r.Amount.from(o,"TZS");n&&a&&t.push({label:"Amount Range",value:`${n.label} — ${a.label}`})}}else if(void 0!==n.minAmount){const e=Number(n.minAmount);if(Number.isFinite(e)){const n=r.Amount.from(e,"TZS");n&&t.push({label:"Minimum Amount",value:n.label})}}else if(void 0!==n.maxAmount){const e=Number(n.maxAmount);if(Number.isFinite(e)){const n=r.Amount.from(e,"TZS");n&&t.push({label:"Maximum Amount",value:n.label})}}return n.search&&t.push({label:"Search",value:`"${n.search}"`}),n.payeeName&&t.push({label:"Beneficiary Name",value:n.payeeName}),n.msisdnIn?.length?t.push({label:"MSISDN",value:n.msisdnIn.join(", ")}):n.msisdn&&t.push({label:"MSISDN",value:n.msisdn}),n.profileId&&t.push({label:"Profile",value:n.profileId}),n.createdByIdIn?.length?t.push({label:"Created By ID",value:n.createdByIdIn.join(", ")}):n.createdById&&t.push({label:"Created By ID",value:n.createdById}),n.actionedByIdIn?.length?t.push({label:"Actioned By ID",value:n.actionedByIdIn.join(", ")}):n.actionedById&&t.push({label:"Actioned By ID",value:n.actionedById}),n.partnerReference&&t.push({label:"Reference",value:n.partnerReference}),t}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",approvalStatus:"Approval Status",status:"Status",channel:"Channel",msisdn:"MSISDN",createdById:"Created By ID",actionedById:"Actioned By ID"}[e]??e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=ht.toStringList(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"payeeName":case"msisdn":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}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}whereInValues(e,t){const r=ht.toStringList(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=ht.toStringList(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidApprovalStatuses(e){const t=ht.toStringList(e).filter(e=>this.isValidApprovalStatus(e));return t.length>0?t:void 0}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const mt=e=>e.optional().transform(e=>e??void 0),yt={walletDTO:e.z.object({id:e.z.string().min(1,{message:"Wallet ID is required."}),profileId:e.z.string().min(1,{message:"Profile ID is required."}),accountNo:e.z.string().min(1,{message:"Account number is required."}),accountName:e.z.string().min(1,{message:"Account name is required."}),channel:e.z.string().min(1,{message:"Channel is required."}),countryCode:e.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:e.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:e.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:e.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:e.z.object({id:e.z.string().optional(),profileId:e.z.string().optional(),accountNo:e.z.string().optional(),accountName:e.z.string().optional(),channel:e.z.string().optional(),countryCode:e.z.string().default("TZ").refine(e=>r.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:e.z.string().default("TZS").refine(e=>{const t=r.Currency.fromCode(e);return void 0!==t&&r.CurrencyCodesSet.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:e.z.object({accountNo:mt(e.z.string()),debitOrCredit:e.z.string().min(1,"Transaction type is required"),tranRefNo:e.z.string().min(1,"Transaction reference is required"),narration:e.z.string().min(1,"Transaction description is required"),txnDate:e.z.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:e.z.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:e.z.number().min(0,"Credited amount must be non-negative"),amountDebited:e.z.number().min(0,"Debited amount must be non-negative"),balance:e.z.number(),currencyCode:mt(e.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},ft=o.default.object({id:o.default.string(),profileId:o.default.string(),accountNo:o.default.string(),accountName:o.default.string(),channel:o.default.string(),countryCode:o.default.string(),currencyCode:o.default.string(),createdAt:o.default.string(),updatedAt:o.default.string(),_version:o.default.string().optional().default("1.0")});class gt{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return yt.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=gt.schema.safeParse(e);if(t.success)return new gt(t.data);console.error("Wallet data validation failed:",t.error.flatten())}get id(){return this._id}get profileId(){return this._profileId}get accountNo(){return this._accountNo}get accountName(){return this._accountName}get channel(){return this._channel}get countryCode(){return this._countryCode}get currencyCode(){return this._currencyCode}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get createdAtDate(){return new Date(this._createdAt)}get updatedAtDate(){return new Date(this._updatedAt)}validate(){const e=gt.schema.safeParse(this.toJSON());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static from(e){if(e&&"object"==typeof e)return gt.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t._id&&"string"==typeof t._profileId&&"string"==typeof t._accountNo&&"string"==typeof t._accountName&&"string"==typeof t._channel&&"string"==typeof t._countryCode&&r.CountryHelpers.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&r.CurrencyHelpers.isCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ft.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const n=r.data;return gt.create(n)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return ft.safeParse(e).success}}const bt=o.default.object({accountNo:o.default.string().optional(),debitOrCredit:o.default.string(),tranRefNo:o.default.string(),narration:Ve,txnDate:o.default.string(),valueDate:o.default.string(),amountCredited:r.AmountJSONSchema,amountDebited:r.AmountJSONSchema,balance:r.AmountJSONSchema,currencyCode:o.default.string(),_version:o.default.string().optional().default("2.0")});class Nt{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return yt.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const n=r.Currency.fromCode(e.currencyCode);if(!n)throw new Error(`Currency not found for code: ${e.currencyCode}`);const o=r.Amount.from(e.amountCredited,n.code),a=r.Amount.from(e.amountDebited,n.code),s=r.Amount.from(e.balance,n.code);if(!o||!a||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=o,this._amountDebited=a,this._balance=s}static create(e){const t="string"==typeof e.narration?new We(e.narration):e.narration,r={...e,narration:t.text},n=Nt.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new Nt(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",n.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=Nt.schema.safeParse(e);return t.success||console.warn("WalletStatementEntry instance validation failed:",t.error.flatten()),t.success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return("string"==typeof t._accountNo||void 0===t._accountNo)&&"string"==typeof t._debitOrCredit&&"string"==typeof t._tranRefNo&&We.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&r.Amount.is(t._amountCredited)&&r.Amount.is(t._amountDebited)&&r.Amount.is(t._balance)&&"string"==typeof t._currencyCode}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return Nt.create({accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode})}toString(){return`WalletStatementEntry(${this._tranRefNo}: ${this._debitOrCredit} ${this._amountCredited.isPositive()?this._amountCredited.label:this._amountDebited.label} on ${this._txnDate.toISOString().split("T")[0]}${this._narration})`}static from(e){if(e&&"object"==typeof e)try{let t,n,o,a,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const a=r.Amount.fromJSON(e.amountCredited),i=r.Amount.fromJSON(e.amountDebited),c=r.Amount.fromJSON(e.balance);if(!a||!i||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=a.numericValue,n=i.numericValue,o=c.numericValue,e.currencyCode||(s=a.currencyCode)}else if(t=Number(e.amountCredited),n=Number(e.amountDebited),o=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(o))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)a=e.narration;else if(We.is(e.narration))a=e.narration;else{if(!We.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=We.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return Nt.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:a,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:n,balance:o,currencyCode:s})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}toJSON(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.toJSON(),txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJSON(),amountDebited:this._amountDebited.toJSON(),balance:this._balance.toJSON(),currencyCode:this._currencyCode,_version:"2.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,n=bt.safeParse(t);if(!n.success)return void console.error("Invalid WalletStatementEntryJSON:",n.error.flatten());const o=n.data,a=We.fromJSON(o.narration);if(!a)return void console.warn("Failed to deserialize narration");const s=r.Amount.fromJSON(o.amountCredited),i=r.Amount.fromJSON(o.amountDebited),c=r.Amount.fromJSON(o.balance);return s&&i&&c?s.currencyCode!==o.currencyCode||i.currencyCode!==o.currencyCode||c.currencyCode!==o.currencyCode?void console.warn("Currency code mismatch"):Nt.create({accountNo:o.accountNo,debitOrCredit:o.debitOrCredit,tranRefNo:o.tranRefNo,narration:a,txnDate:o.txnDate,valueDate:o.valueDate,amountCredited:s.numericValue,amountDebited:i.numericValue,balance:c.numericValue,currencyCode:o.currencyCode}):void console.warn("Failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJSON:",e)}}static isWalletStatementEntryJSON(e){return bt.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Nt.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntry JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toJson(){return this.toJSON()}static fromJson(e){return Nt.fromJSON(e)}static fromJsonArray(e){return Nt.fromJSONArray(e)}static toJsonArray(e){return Nt.toJSONArray(e)}}const vt=h().router({getWallets:{method:"GET",path:"/",query:yt.walletQuery,responses:{200:e.z.array(gt.schema)}},getBalance:{method:"POST",path:"/balance",body:e.z.object({accountNo:e.z.string().optional()}),responses:{201:e.z.object({availableBalance:e.z.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:e.z.object({endDate:e.z.date(),startDate:e.z.date(),accountNo:e.z.string().optional()}),responses:{201:e.z.array(Nt.schema)}}});class It extends B{static create(){return new It}static fromFilters(e){return(new It).applyFilters(e)}static fromUrlParams(e){try{const t=yt.walletQuery.parse(e);return It.fromFilters(t)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return It.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return It.fromSearchParams(t)}static from(e){try{return null==e?new It:B.is(e)?new It(e.options):e instanceof URLSearchParams?It.fromSearchParams(e):this.isStringRecord(e)?It.fromUrlParams(e):It.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a WalletQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereId(e){return this.where("id",e)}whereProfileId(e){return this.where("profileId",e)}whereAccountNo(e){return this.where("accountNo",e)}whereAccountName(e){return this.whereContains("accountName",e)}whereChannel(e){return this.where("channel",e)}whereCountryCode(e){return this.where("countryCode",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return e.id&&this.whereId(e.id),e.profileId&&this.whereProfileId(e.profileId),e.accountNo&&this.whereAccountNo(e.accountNo),e.accountName&&this.whereAccountName(e.accountName),e.channel&&this.whereChannel(e.channel),e.countryCode&&this.whereCountryCode(e.countryCode),e.currencyCode&&this.whereCurrencyCode(e.currencyCode),this}toFilters(){const e=this.extractFilterValues();return{id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,currencyCode:e.currencyCode}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withId(e){const t=this.clone();return t.whereId(e),t}withProfileId(e){const t=this.clone();return t.whereProfileId(e),t}withAccountNo(e){const t=this.clone();return t.whereAccountNo(e),t}withCountryCode(e){const t=this.clone();return t.whereCountryCode(e),t}withCurrencyCode(e){const t=this.clone();return t.whereCurrencyCode(e),t}hasFilters(){const e=this.toFilters();return!!(e.id||e.profileId||e.accountNo||e.accountName||e.channel||e.countryCode||e.currencyCode)}getActiveFilters(){const e=[],t=this.toFilters();return t.id&&e.push(`ID: ${t.id}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.accountName&&e.push(`Name: ${t.accountName}`),t.channel&&e.push(`Channel: ${t.channel}`),t.countryCode&&e.push(`Country: ${t.countryCode}`),t.currencyCode&&e.push(`Currency: ${t.currencyCode}`),e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}const wt={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)},St=h().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:R.schema}}});exports.APIError=a,exports.AuthDTOSchemas=V,exports.AuthRepository=class extends _{constructor(e){super("auth",W,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},n=await this.client.logIn({body:r});if(400===n.status)throw new a({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new K({token:e}),r=await t.getIdentity(),o=j.from(r);if(!o)throw new a({message:"Failed to construct login credentials",statusCode:502});const i=n.body.profile,c=R.from(i);if(!c)throw new a({message:"Failed to construct user profile",statusCode:502});let u;if(o.can(s.Role.ViewRole))try{const t=new re({token:e});u=await t.getRole(o.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const d=U.from({logIn:o,companyProfile:c,role:u});if(!d)throw new a({message:"Failed to construct user session",statusCode:502});return{token:e,user:d}}throw new a({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new a({message:"Invalid current password",statusCode:400});throw new a({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.BANK_NARR_PREFIX=Le,exports.BankBeneficiaryInfo=he,exports.BankBeneficiaryJSONSchema=ce,exports.BaseRepository=_,exports.Beneficiary=ge,exports.BeneficiaryDTOSchemas=se,exports.BeneficiaryError=de,exports.BeneficiaryInfo=ye,exports.BeneficiaryInfoFactory=me,exports.BeneficiaryInfoJSONSchema=ue,exports.BeneficiaryJSONSchema=fe,exports.BeneficiaryRepository=class extends _{constructor(e){super("contact",Ie,e)}async create(e){const t=(new ve).resolve(e),r=await this.client.createBeneficiary({body:t}),n=this.handleResponse(r,201);return ge.create(n)}async edit(e,t){const r=(new ve).resolve(t),n=await this.client.editBeneficiary({params:{id:e},body:r}),o=this.handleResponse(n,200);return ge.create(o)}async remove(e){const t=await this.client.deleteBeneficiary({params:{id:e}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getBeneficiaries({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return ge.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return ge.create(r)}},exports.CompanyMembership=$,exports.CompanyMembershipJSONSchema=L,exports.ECOBANK_PREFIX=Fe,exports.IdentityRepository=K,exports.LEGACY_BANK_NARR_PREFIX=$e,exports.LEGACY_MOBILE_NARR_PREFIX=Ue,exports.LogIn=j,exports.LogInJSONSchema=M,exports.LogInSchemas=J,exports.MOBILE_NARR_PREFIX=qe,exports.MobileBeneficiaryInfo=pe,exports.MobileBeneficiaryJSONSchema=ie,exports.NARR_V2_PREFIX=ke,exports.Narration=We,exports.NarrationJSONSchema=Ve,exports.Pagination=E,exports.PaginationParamsSchema=z,exports.PaginationSchema=T,exports.Payout=je,exports.PayoutChannelResolver=ct,exports.PayoutDTOSchemas=Je,exports.PayoutInputFactory=ut,exports.PayoutJSONSchema=Me,exports.PayoutQuery=ht,exports.PayoutRepository=class extends _{constructor(e){super("payout",lt,e)}async getPayouts(e){try{const t=ht.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),o=this.handleResponse(n,200),a=t.toFilters(),s=new E(a.page??1,a.limit??10,o.total);return{results:je.createMany(o.results),pagination:s}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=ht.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return je.createMany(n)}catch(e){throw console.log("error: ",e),new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=ht.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,receiver:n,amount:o,notes:s}=e,i=ct.resolve({wallet:t,receiver:n,amount:o}),c=r.TemboCoverage.getTransactionLimits({countryCode:t.countryCode,currencyCode:o.currencyCode,direction:r.TransactionDirection.PAYOUT,channelType:ct.getChannelType(i)});if(!c)throw new a({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${o.currencyCode} ${i} payouts`});const{min:u,max:d}=c;if(o.lessThan(u)||o.greaterThan(d))throw new a({statusCode:400,message:`Please make sure the amount is between ${u.label} - ${d.label}`});const l=(new ut).getPayoutInput({receiver:n,amount:o,notes:s},t),p=await this.client.postPayout({body:l});if(201===p.status)return je.create(p.body);if(400===p.status)throw new a(p.body);throw a.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return je.create(t.body);if(401===t.status)throw new a({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new a({message:"Payout not found",statusCode:404});if(409===t.status)throw new a({message:"Payout already approved",statusCode:409});throw a.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return je.create(t.body);if(401===t.status)throw new a({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new a({message:"Payout not found",statusCode:404});if(409===t.status)throw new a({message:"Payout already rejected",statusCode:409});throw a.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return je.create(t.body);if(404===t.status)throw new a({message:"Payout not found",statusCode:404});throw a.unknown()}async count(e){const t=ht.from(e).build(),r=await this.client.getPayouts({query:t});return this.handleResponse(r,200).total}async exists(e){return await this.count(e)>0}},exports.PermissionError=i,exports.Permissions=s,exports.Profile=R,exports.ProfileDTOSchemas=D,exports.ProfileJSONSchema=x,exports.ProfileRepository=class extends _{constructor(e){super("profile",St,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=R.from(e.body);if(t)return t;throw new Error("Invalid profile data received from server")}throw new Error(`Failed to get current profile. Status: ${e.status}`)}},exports.QUERY_BUILDER_TYPE=P,exports.QueryBuilder=B,exports.Role=k,exports.RoleJSONSchema=F,exports.TeamManagementDTOSchemas=Y,exports.TeamMember=te,exports.TeamMemberJSONSchema=ee,exports.TeamMemberRepository=re,exports.User=U,exports.UserJSONSchema=q,exports.ValidatedBeneficiaryInputFactory=ve,exports.Wallet=gt,exports.WalletDTOSchemas=yt,exports.WalletJSONSchema=ft,exports.WalletRepository=class extends _{constructor(e){super("wallet",vt,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const n=t.body.availableBalance,o=r.Amount.from(n,e.wallet.currencyCode);if(o)return o}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const n=t[0],o=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===o.status){const e=o.body.availableBalance,t=r.Amount.from(e,n.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=It.from(e).build(),r=await this.client.getWallets({query:t});if(200===r.status){const e=r.body;try{return e.map(e=>{const t=gt.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${r.status}`)}async getByID(e){const t=It.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),1),n=new Date(t.getFullYear(),t.getMonth()+1,0),o=e.range??{startDate:r,endDate:n};let a,s;if(e.wallet)a=e.wallet,s=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);a=t[0],s=e.accountNo}}const i={...o,accountNo:s},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:a.currencyCode})).reduce((e,t)=>{const r=Nt.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[])}throw new Error(`Failed to fetch statement. Status: ${c.status}`)}async exists(e){return(await this.getWallets(e)).length>0}async count(e){return(await this.getWallets(e)).length}},exports.WalletStatementEntry=Nt,exports.WalletStatementEntryJSONSchema=bt,exports.WalletUtils=wt,exports.contract=Ie,exports.createPaginatedResponse=function(e,t,r,n){return{results:e,pagination:new E(t,r,n)}},exports.createPaginatedResponseSchema=function(t){return e.z.object({results:e.z.array(t),pagination:T})},exports.createPayoutChannelCode=dt,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new E(e,t,0)}},exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.setGlobalTokenGetter=e=>{A=e};
|
|
1
|
+
"use strict";var e=require("uuid"),t=require("zod"),r=require("@temboplus/frontend-core");function a(e){return e&&e.__esModule?e:{default:e}}var n,s,i=a(t);!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},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}(n||(n={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const o=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=e=>{switch(typeof e){case"undefined":return o.undefined;case"string":return o.string;case"number":return isNaN(e)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":return Array.isArray(e)?o.array:null===e?o.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?o.promise:"undefined"!=typeof Map&&e instanceof Map?o.map:"undefined"!=typeof Set&&e instanceof Set?o.set:"undefined"!=typeof Date&&e instanceof Date?o.date:o.object;default:return o.unknown}},d=n.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 u 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:[]},a=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,a=0;for(;a<n.path.length;){const r=n.path[a];a===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,n.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}u.create=e=>new u(e);const l=(e,t)=>{let r;switch(e.code){case d.invalid_type:r=e.received===o.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.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}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case d.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 d.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 d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};let p=l;function h(){return p}const m=e=>{const{data:t,path:r,errorMaps:a,issueData:n}=e,s=[...r,...n.path||[]],i={...n,path:s};let o="";const c=a.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...n,path:s,message:n.message||o}};function f(e,t){const r=m({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,h(),l].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const a of t){if("aborted"===a.status)return g;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t)r.push({key:await e.key,value:await e.value});return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const a of t){const{key:t,value:n}=a;if("aborted"===t.status)return g;if("aborted"===n.status)return g;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!a.alwaysSet||(r[t.value]=n.value)}return{status:e.value,value:r}}}const g=Object.freeze({status:"aborted"}),v=e=>({status:"dirty",value:e}),_=e=>({status:"valid",value:e}),b=e=>"aborted"===e.status,N=e=>"dirty"===e.status,w=e=>"valid"===e.status,I=e=>"undefined"!=typeof Promise&&e instanceof Promise;var S;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(S||(S={}));class A{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}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(w(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 u(e.common.issues);return this._error=t,this._error}}};function C(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:n}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=a?a:t.defaultError}:{message:null!=r?r:t.defaultError},description:n}}class x{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return c(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(I(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 a={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},n=this._parseSync({data:e,path:a.path,parent:a});return O(a,n)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},a=this._parse({data:e,path:r.path,parent:r}),n=await(I(a)?a:Promise.resolve(a));return O(r,n)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{const n=e(t),s=()=>a.addIssue({code:d.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(s(),!1)):!!n||(s(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new ge({schema:this,typeName:Pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ve.create(this,this._def)}nullable(){return _e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Y.create(this,this._def)}promise(){return ye.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return se.create(this,e,this._def)}transform(e){return new ge({...C(this._def),schema:this,typeName:Pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new be({...C(this._def),innerType:this,defaultValue:t,typeName:Pe.ZodDefault})}brand(){return new Se({typeName:Pe.ZodBranded,type:this,...C(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ne({...C(this._def),innerType:this,catchValue:t,typeName:Pe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ae.create(this,e)}readonly(){return Oe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const P=/^c[^\s-]{8,}$/i,T=/^[a-z][a-z0-9]*$/,z=/[0-9A-HJKMNP-TV-Z]{26}/,E=/^[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,B=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,k=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,D=/^(((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}))$/,R=/^(([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})))$/,j=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 M(e,t){return!("v4"!==t&&t||!D.test(e))||!("v6"!==t&&t||!R.test(e))}class J extends x{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:d.invalid_string,...S.errToObj(r)}),this.nonempty=e=>this.min(1,S.errToObj(e)),this.trim=()=>new J({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new J({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new J({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==o.string){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.string,received:t.parsedType}),g}const t=new y;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("max"===a.kind)e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const n=e.data.length>a.value,s=e.data.length<a.value;(n||s)&&(r=this._getOrReturnCtx(e,r),n?f(r,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&f(r,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if("email"===a.kind)B.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:d.invalid_string,message:a.message}),t.dirty());else if("emoji"===a.kind)k.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:d.invalid_string,message:a.message}),t.dirty());else if("uuid"===a.kind)E.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:d.invalid_string,message:a.message}),t.dirty());else if("cuid"===a.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:d.invalid_string,message:a.message}),t.dirty());else if("cuid2"===a.kind)T.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:d.invalid_string,message:a.message}),t.dirty());else if("ulid"===a.kind)z.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:d.invalid_string,message:a.message}),t.dirty());else if("url"===a.kind)try{new URL(e.data)}catch(n){r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:d.invalid_string,message:a.message}),t.dirty()}else if("regex"===a.kind){a.regex.lastIndex=0;a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:d.invalid_string,message:a.message}),t.dirty())}else if("trim"===a.kind)e.data=e.data.trim();else if("includes"===a.kind)e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty());else if("toLowerCase"===a.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===a.kind)e.data=e.data.toUpperCase();else if("startsWith"===a.kind)e.data.startsWith(a.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty());else if("endsWith"===a.kind)e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty());else if("datetime"===a.kind){j(a).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:d.invalid_string,validation:"datetime",message:a.message}),t.dirty())}else"ip"===a.kind?M(e.data,a.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:d.invalid_string,message:a.message}),t.dirty()):n.assertNever(a);return{status:t.value,value:e.data}}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...S.errToObj(e)})}url(e){return this._addCheck({kind:"url",...S.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...S.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...S.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...S.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...S.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...S.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...S.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,...S.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...S.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...S.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...S.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...S.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...S.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...S.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...S.errToObj(t)})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Z(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}J.create=e=>{var t;return new J({checks:[],typeName:Pe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...C(e)})};class L extends x{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)!==o.number){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.number,received:t.parsedType}),g}let t;const r=new y;for(const a of this._def.checks)if("int"===a.kind)n.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else"multipleOf"===a.kind?0!==Z(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:d.not_finite,message:a.message}),r.dirty()):n.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,r,a){return new L({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:S.toString(a)}]})}_addCheck(e){return new L({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:S.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:S.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:S.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:S.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&n.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)}}L.create=e=>new L({checks:[],typeName:Pe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...C(e)});class F extends x{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)!==o.bigint){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.bigint,received:t.parsedType}),g}let t;const r=new y;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),f(t,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):n.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,r,a){return new F({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:S.toString(a)}]})}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}F.create=e=>{var t;return new F({checks:[],typeName:Pe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...C(e)})};class $ extends x{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==o.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.boolean,received:t.parsedType}),g}return _(e.data)}}$.create=e=>new $({typeName:Pe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...C(e)});class U extends x{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==o.date){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.date,received:t.parsedType}),g}if(isNaN(e.data.getTime())){return f(this._getOrReturnCtx(e),{code:d.invalid_date}),g}const t=new y;let r;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):n.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new U({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:S.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:S.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}U.create=e=>new U({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Pe.ZodDate,...C(e)});class q extends x{_parse(e){if(this._getType(e)!==o.symbol){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.symbol,received:t.parsedType}),g}return _(e.data)}}q.create=e=>new q({typeName:Pe.ZodSymbol,...C(e)});class V extends x{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.undefined,received:t.parsedType}),g}return _(e.data)}}V.create=e=>new V({typeName:Pe.ZodUndefined,...C(e)});class W extends x{_parse(e){if(this._getType(e)!==o.null){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.null,received:t.parsedType}),g}return _(e.data)}}W.create=e=>new W({typeName:Pe.ZodNull,...C(e)});class K extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}}K.create=e=>new K({typeName:Pe.ZodAny,...C(e)});class H extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}}H.create=e=>new H({typeName:Pe.ZodUnknown,...C(e)});class G extends x{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.never,received:t.parsedType}),g}}G.create=e=>new G({typeName:Pe.ZodNever,...C(e)});class Q extends x{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.void,received:t.parsedType}),g}return _(e.data)}}Q.create=e=>new Q({typeName:Pe.ZodVoid,...C(e)});class Y extends x{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==o.array)return f(t,{code:d.invalid_type,expected:o.array,received:t.parsedType}),g;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(f(t,{code:e?d.too_big:d.too_small,minimum:n?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(f(t,{code:d.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(f(t,{code:d.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new A(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const n=[...t.data].map((e,r)=>a.type._parseSync(new A(t,e,t.path,r)));return y.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new Y({...this._def,minLength:{value:e,message:S.toString(t)}})}max(e,t){return new Y({...this._def,maxLength:{value:e,message:S.toString(t)}})}length(e,t){return new Y({...this._def,exactLength:{value:e,message:S.toString(t)}})}nonempty(e){return this.min(1,e)}}function X(e){if(e instanceof ee){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=ve.create(X(a))}return new ee({...e._def,shape:()=>t})}return e instanceof Y?new Y({...e._def,type:X(e.element)}):e instanceof ve?ve.create(X(e.unwrap())):e instanceof _e?_e.create(X(e.unwrap())):e instanceof ie?ie.create(e.items.map(e=>X(e))):e}Y.create=(e,t)=>new Y({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Pe.ZodArray,...C(t)});class ee extends x{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=n.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==o.object){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.object,received:t.parsedType}),g}const{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),s=[];if(!(this._def.catchall instanceof G&&"strip"===this._def.unknownKeys))for(const e in r.data)n.includes(e)||s.push(e);const i=[];for(const e of n){const t=a[e],n=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new A(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof G){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(f(r,{code:d.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const a=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new A(r,a,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=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return S.errToObj,new ee({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var a,n,s,i;const o=null!==(s=null===(n=(a=this._def).errorMap)||void 0===n?void 0:n.call(a,t,r).message)&&void 0!==s?s:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=S.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new ee({...this._def,unknownKeys:"strip"})}passthrough(){return new ee({...this._def,unknownKeys:"passthrough"})}extend(e){return new ee({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ee({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Pe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ee({...this._def,catchall:e})}pick(e){const t={};return n.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}omit(e){const t={};return n.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}deepPartial(){return X(this)}partial(e){const t={};return n.objectKeys(this.shape).forEach(r=>{const a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}),new ee({...this._def,shape:()=>t})}required(e){const t={};return n.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ve;)e=e._def.innerType;t[r]=e}}),new ee({...this._def,shape:()=>t})}keyof(){return he(n.objectKeys(this.shape))}}ee.create=(e,t)=>new ee({shape:()=>e,unknownKeys:"strip",catchall:G.create(),typeName:Pe.ZodObject,...C(t)}),ee.strictCreate=(e,t)=>new ee({shape:()=>e,unknownKeys:"strict",catchall:G.create(),typeName:Pe.ZodObject,...C(t)}),ee.lazycreate=(e,t)=>new ee({shape:e,unknownKeys:"strip",catchall:G.create(),typeName:Pe.ZodObject,...C(t)});class te extends x{_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 u(e.ctx.common.issues));return f(t,{code:d.invalid_union,unionErrors:r}),g});{let e;const a=[];for(const n of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=a.map(e=>new u(e));return f(t,{code:d.invalid_union,unionErrors:n}),g}}get options(){return this._def.options}}te.create=(e,t)=>new te({options:e,typeName:Pe.ZodUnion,...C(t)});const re=e=>e instanceof le?re(e.schema):e instanceof ge?re(e.innerType()):e instanceof pe?[e.value]:e instanceof me?e.options:e instanceof fe?Object.keys(e.enum):e instanceof be?re(e._def.innerType):e instanceof V?[void 0]:e instanceof W?[null]:null;class ae extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.object)return f(t,{code:d.invalid_type,expected:o.object,received:t.parsedType}),g;const r=this.discriminator,a=t.data[r],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=re(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(a.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);a.set(n,r)}}return new ae({typeName:Pe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...C(r)})}}function ne(e,t){const r=c(e),a=c(t);if(e===t)return{valid:!0,data:e};if(r===o.object&&a===o.object){const r=n.objectKeys(t),a=n.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of a){const a=ne(e[r],t[r]);if(!a.valid)return{valid:!1};s[r]=a.data}return{valid:!0,data:s}}if(r===o.array&&a===o.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let a=0;a<e.length;a++){const n=ne(e[a],t[a]);if(!n.valid)return{valid:!1};r.push(n.data)}return{valid:!0,data:r}}return r===o.date&&a===o.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class se extends x{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(b(e)||b(a))return g;const n=ne(e.value,a.value);return n.valid?((N(e)||N(a))&&t.dirty(),{status:t.value,value:n.data}):(f(r,{code:d.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}se.create=(e,t,r)=>new se({left:e,right:t,typeName:Pe.ZodIntersection,...C(r)});class ie extends x{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.array)return f(r,{code:d.invalid_type,expected:o.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return f(r,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new A(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>y.mergeArray(t,e)):y.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ie({...this._def,rest:e})}}ie.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ie({items:e,typeName:Pe.ZodTuple,rest:null,...C(t)})};class oe extends x{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!==o.object)return f(r,{code:d.invalid_type,expected:o.object,received:r.parsedType}),g;const a=[],n=this._def.keyType,s=this._def.valueType;for(const e in r.data)a.push({key:n._parse(new A(r,e,r.path,e)),value:s._parse(new A(r,r.data[e],r.path,e))});return r.common.async?y.mergeObjectAsync(t,a):y.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new oe(t instanceof x?{keyType:e,valueType:t,typeName:Pe.ZodRecord,...C(r)}:{keyType:J.create(),valueType:e,typeName:Pe.ZodRecord,...C(t)})}}class ce extends x{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!==o.map)return f(r,{code:d.invalid_type,expected:o.map,received:r.parsedType}),g;const a=this._def.keyType,n=this._def.valueType,s=[...r.data.entries()].map(([e,t],s)=>({key:a._parse(new A(r,e,r.path,[s,"key"])),value:n._parse(new A(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const a=await r.key,n=await r.value;if("aborted"===a.status||"aborted"===n.status)return g;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const a=r.key,n=r.value;if("aborted"===a.status||"aborted"===n.status)return g;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}}ce.create=(e,t,r)=>new ce({valueType:t,keyType:e,typeName:Pe.ZodMap,...C(r)});class de extends x{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.set)return f(r,{code:d.invalid_type,expected:o.set,received:r.parsedType}),g;const a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(f(r,{code:d.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(f(r,{code:d.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const n=this._def.valueType;function s(e){const r=new Set;for(const a of e){if("aborted"===a.status)return g;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>n._parse(new A(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>s(e)):s(i)}min(e,t){return new de({...this._def,minSize:{value:e,message:S.toString(t)}})}max(e,t){return new de({...this._def,maxSize:{value:e,message:S.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}de.create=(e,t)=>new de({valueType:e,minSize:null,maxSize:null,typeName:Pe.ZodSet,...C(t)});class ue extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.function)return f(t,{code:d.invalid_type,expected:o.function,received:t.parsedType}),g;function r(e,r){return m({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,h(),l].filter(e=>!!e),issueData:{code:d.invalid_arguments,argumentsError:r}})}function a(e,r){return m({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,h(),l].filter(e=>!!e),issueData:{code:d.invalid_return_type,returnTypeError:r}})}const n={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof ye){const e=this;return _(async function(...t){const i=new u([]),o=await e._def.args.parseAsync(t,n).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(s,this,o);return await e._def.returns._def.type.parseAsync(c,n).catch(e=>{throw i.addIssue(a(c,e)),i})})}{const e=this;return _(function(...t){const i=e._def.args.safeParse(t,n);if(!i.success)throw new u([r(t,i.error)]);const o=Reflect.apply(s,this,i.data),c=e._def.returns.safeParse(o,n);if(!c.success)throw new u([a(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ue({...this._def,args:ie.create(e).rest(H.create())})}returns(e){return new ue({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ue({args:e||ie.create([]).rest(H.create()),returns:t||H.create(),typeName:Pe.ZodFunction,...C(r)})}}class le extends x{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}le.create=(e,t)=>new le({getter:e,typeName:Pe.ZodLazy,...C(t)});class pe extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}function he(e,t){return new me({values:e,typeName:Pe.ZodEnum,...C(t)})}pe.create=(e,t)=>new pe({value:e,typeName:Pe.ZodLiteral,...C(t)});class me extends x{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:n.joinValues(r),received:t.parsedType,code:d.invalid_type}),g}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:d.invalid_enum_value,options:r}),g}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 me.create(e)}exclude(e){return me.create(this.options.filter(t=>!e.includes(t)))}}me.create=he;class fe extends x{_parse(e){const t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==o.string&&r.parsedType!==o.number){const e=n.objectValues(t);return f(r,{expected:n.joinValues(e),received:r.parsedType,code:d.invalid_type}),g}if(-1===t.indexOf(e.data)){const e=n.objectValues(t);return f(r,{received:r.data,code:d.invalid_enum_value,options:e}),g}return _(e.data)}get enum(){return this._def.values}}fe.create=(e,t)=>new fe({values:e,typeName:Pe.ZodNativeEnum,...C(t)});class ye extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.promise&&!1===t.common.async)return f(t,{code:d.invalid_type,expected:o.promise,received:t.parsedType}),g;const r=t.parsedType===o.promise?t.data:Promise.resolve(t.data);return _(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ye.create=(e,t)=>new ye({type:e,typeName:Pe.ZodPromise,...C(t)});class ge extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:e=>{f(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===a.type){const e=a.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"===a.type){const e=e=>{const t=a.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 a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?g:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?g:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===a.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!w(e))return e;const n=a.transform(e.value,s);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>w(e)?Promise.resolve(a.transform(e.value,s)).then(e=>({status:t.value,value:e})):e)}n.assertNever(a)}}ge.create=(e,t,r)=>new ge({schema:e,typeName:Pe.ZodEffects,effect:t,...C(r)}),ge.createWithPreprocess=(e,t,r)=>new ge({schema:t,effect:{type:"preprocess",transform:e},typeName:Pe.ZodEffects,...C(r)});class ve extends x{_parse(e){return this._getType(e)===o.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ve.create=(e,t)=>new ve({innerType:e,typeName:Pe.ZodOptional,...C(t)});class _e extends x{_parse(e){return this._getType(e)===o.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(e,t)=>new _e({innerType:e,typeName:Pe.ZodNullable,...C(t)});class be extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===o.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}be.create=(e,t)=>new be({innerType:e,typeName:Pe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...C(t)});class Ne extends x{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return I(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:Pe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...C(t)});class we extends x{_parse(e){if(this._getType(e)!==o.nan){const t=this._getOrReturnCtx(e);return f(t,{code:d.invalid_type,expected:o.nan,received:t.parsedType}),g}return{status:"valid",value:e.data}}}we.create=e=>new we({typeName:Pe.ZodNaN,...C(e)});const Ie=Symbol("zod_brand");class Se extends x{_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 Ae extends x{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),v(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Ae({in:e,out:t,typeName:Pe.ZodPipeline})}}class Oe extends x{_parse(e){const t=this._def.innerType._parse(e);return w(t)&&(t.value=Object.freeze(t.value)),t}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:Pe.ZodReadonly,...C(t)});const Ce=(e,t={},r)=>e?K.create().superRefine((a,n)=>{var s,i;if(!e(a)){const e="function"==typeof t?t(a):"string"==typeof t?{message:t}:t,o=null===(i=null!==(s=e.fatal)&&void 0!==s?s:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;n.addIssue({code:"custom",...c,fatal:o})}}):K.create(),xe={object:ee.lazycreate};var Pe;!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"}(Pe||(Pe={}));const Te=J.create,ze=L.create,Ee=we.create,Be=F.create,ke=$.create,De=U.create,Re=q.create,je=V.create,Me=W.create,Je=K.create,Ze=H.create,Le=G.create,Fe=Q.create,$e=Y.create,Ue=ee.create,qe=ee.strictCreate,Ve=te.create,We=ae.create,Ke=se.create,He=ie.create,Ge=oe.create,Qe=ce.create,Ye=de.create,Xe=ue.create,et=le.create,tt=pe.create,rt=me.create,at=fe.create,nt=ye.create,st=ge.create,it=ve.create,ot=_e.create,ct=ge.createWithPreprocess,dt=Ae.create,ut={string:e=>J.create({...e,coerce:!0}),number:e=>L.create({...e,coerce:!0}),boolean:e=>$.create({...e,coerce:!0}),bigint:e=>F.create({...e,coerce:!0}),date:e=>U.create({...e,coerce:!0})},lt=g;var pt=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){p=e},getErrorMap:h,makeIssue:m,EMPTY_PATH:[],addIssueToContext:f,ParseStatus:y,INVALID:g,DIRTY:v,OK:_,isAborted:b,isDirty:N,isValid:w,isAsync:I,get util(){return n},get objectUtil(){return s},ZodParsedType:o,getParsedType:c,ZodType:x,ZodString:J,ZodNumber:L,ZodBigInt:F,ZodBoolean:$,ZodDate:U,ZodSymbol:q,ZodUndefined:V,ZodNull:W,ZodAny:K,ZodUnknown:H,ZodNever:G,ZodVoid:Q,ZodArray:Y,ZodObject:ee,ZodUnion:te,ZodDiscriminatedUnion:ae,ZodIntersection:se,ZodTuple:ie,ZodRecord:oe,ZodMap:ce,ZodSet:de,ZodFunction:ue,ZodLazy:le,ZodLiteral:pe,ZodEnum:me,ZodNativeEnum:fe,ZodPromise:ye,ZodEffects:ge,ZodTransformer:ge,ZodOptional:ve,ZodNullable:_e,ZodDefault:be,ZodCatch:Ne,ZodNaN:we,BRAND:Ie,ZodBranded:Se,ZodPipeline:Ae,ZodReadonly:Oe,custom:Ce,Schema:x,ZodSchema:x,late:xe,get ZodFirstPartyTypeKind(){return Pe},coerce:ut,any:Je,array:$e,bigint:Be,boolean:ke,date:De,discriminatedUnion:We,effect:st,enum:rt,function:Xe,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Ce(t=>t instanceof e,t),intersection:Ke,lazy:et,literal:tt,map:Qe,nan:Ee,nativeEnum:at,never:Le,null:Me,nullable:ot,number:ze,object:Ue,oboolean:()=>ke().optional(),onumber:()=>ze().optional(),optional:it,ostring:()=>Te().optional(),pipeline:dt,preprocess:ct,promise:nt,record:Ge,set:Ye,strictObject:qe,string:Te,symbol:Re,transformer:st,tuple:He,undefined:je,union:Ve,unknown:Ze,void:Fe,NEVER:lt,ZodIssueCode:d,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:u});const ht=e=>"function"==typeof(null==e?void 0:e.passthrough),mt=pt.object({name:pt.literal("ZodError"),issues:pt.array(pt.object({path:pt.array(pt.union([pt.string(),pt.number()])),message:pt.string().optional(),code:pt.nativeEnum(pt.ZodIssueCode)}).catchall(pt.any()))});class ft extends Error{constructor(e){super(JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t,2)),this.name="ValidationError",this.issues=e}toString(){return this.message}}pt.object({message:pt.literal("Request validation failed"),pathParameterErrors:mt.nullable(),headerErrors:mt.nullable(),queryParameterErrors:mt.nullable(),bodyErrors:mt.nullable()}),pt.object({pathParameterErrors:mt.nullable(),headerErrors:mt.nullable(),queryParameterErrors:mt.nullable(),bodyErrors:mt.nullable()}),pt.object({paramsResult:mt.nullable(),headersResult:mt.nullable(),queryResult:mt.nullable(),bodyResult:mt.nullable()});const yt="zod-ts-rest-polyfill",gt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof ee&&t instanceof ee){return a=t,ht(r=e)?ht(a)?r.merge(a):r:ht(a)?a:Object.assign({},r,a)}var r,a;return{...e,...t}},vt=Symbol("ContractNoBody"),_t=e=>"method"in e&&"path"in e,bt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var a,n,s;return _t(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:gt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(a=r.strictStatusCodes)&&void 0!==a?a:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(n=r.validateResponseOnClient)&&void 0!==n?n:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,bt(r,t)]})),Nt=Symbol("ContractPlainType"),wt=()=>({router:(e,t)=>bt(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Nt,body:()=>Nt,type:()=>Nt,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>vt}),It=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",St=e=>e?Object.keys(e).flatMap(t=>At(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",At=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>At(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>At(`${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 Ct=async({route:e,path:t,method:r,headers:a,body:n,validateResponse:s,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:a,body:n}),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===vt?void 0:await o.json(),headers:o.headers},a=(e=>{if((e=>{if(!e)return!1;const t=null==e?void 0:e["~standard"];return!!t&&1===t.version&&"function"==typeof t.validate})(e))return e;if("function"==typeof(null==(t=e)?void 0:t.safeParse)){const t={vendor:yt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(a&&(null!=s?s:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const a=t["~standard"].validate(e);if(a instanceof Promise)throw new Error("Schema validation must be synchronous");return a.issues?t["~standard"].vendor===yt?{error:new u(a.issues)}:{error:new ft(a.issues)}:r&&"object"==typeof e&&a.value?{value:{...e,...a.value}}:{value:a.value}})(r.body,a);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}},xt=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 a of t)r(e,a);else r(e,t)}),t},Pt=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Tt=(e,t,r,a,n)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:a.path,params:r}),i=((e,t=!1)=>{const r=t?It(e):St(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,n);return t.endsWith("/")&&s.startsWith("/")?`${t}${s.substring(1)}${i}`:`${t}${s}${i}`},zt=(e,t)=>{const r=Object.keys(e.responses);return async a=>{const n=((e,t,r)=>{const{query:a,params:n,body:s,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:d,cache:u,next:l,...p}=r||{},h={...t,...c},m="object"==typeof n?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,String(t)])):{};return{path:Tt(a,h.baseUrl,m,e,!!h.jsonQuery),clientArgs:h,route:e,body:s,query:a,extraInputArgs:p,fetchOptions:{...u&&{cache:u},...l&&{next:l},...d},headers:{...o,...i}}})(e,t,a),s=await(e=>{const{path:t,clientArgs:r,route:a,body:n,query:s,extraInputArgs:i,headers:o,fetchOptions:c}=e,d=r.api||Ct,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...u&&Pt(u),...Pt(o)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let p={route:a,path:t,method:a.method,headers:l,body:void 0,rawBody:n,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==a.method&&("contentType"in a&&"multipart/form-data"===a.contentType?p={...p,contentType:"multipart/form-data",body:n instanceof FormData?n:xt(n)}:"contentType"in a&&"application/x-www-form-urlencoded"===a.contentType?p={...p,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...p.headers},body:"string"==typeof n?n:new URLSearchParams(n)}:null!=n&&(p={...p,contentType:"application/json",headers:{"content-type":"application/json",...p.headers},body:JSON.stringify(n)})),d({...p,...i})})(n);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new Ot(s,r)}},Et=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>_t(r)?[e,zt(r,t)]:[e,Et(r,t)]));class Bt extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,this.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return Bt.schema.safeParse(e).success}static unknown(e){return new Bt({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.z.object({message:t.z.string(),statusCode:t.z.number().int(),error:t.z.string().optional(),details:t.z.object({}).optional()})}}let kt;class Dt{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){if(this.token&&this.token.trim().length>0)return this.token;if(kt){const e=kt();if(e&&e.trim().length>0)return e}return""}get client(){const t={baseUrl:this.root?`${this.root}/${this.endpoint}`:`https://api.afloat.money/v1/${this.endpoint}`,baseHeaders:{token:this.getToken(),"x-request-id":e.v4()}};return Et(this.contract,t)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;if(401===e.status)throw new Bt({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new Bt({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new Bt({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});const r=i.default.object({statusCode:i.default.number(),message:i.default.string(),error:i.default.string(),details:i.default.record(i.default.string(),i.default.string()).optional()}).safeParse(e.body);if(r.success)throw new Bt(r.data);const a=e.status||502;throw new Bt({message:`We encountered an error trying to process your request. Please try again later (upstream status ${a}).`,statusCode:a,error:"UNKNOWN_ERROR"})}}const Rt={Profile:{ViewCurrent:"profile.getCurrent",Update:"profile.update"},Beneficiary:{View:"contact.findById",List:"contact.findAll",Create:"contact.create",Update:"contact.update",Delete:"contact.delete"},Payment:{View:"payment.findById",List:"payment.findAll",Create:"payment.create"},Payout:{View:"payout.findById",List:"payout.findAll",Create:"payout.create",Approve:"payout.approve"},Transfer:{View:"transfer.findById",List:"transfer.findAll",Create:"transfer.create",Approve:"transfer.approve"},Wallet:{ViewBalance:"wallet.getBalance",ViewStatement:"wallet.getStatement"},Role:{ViewRoles:"role.findAll",ViewRole:"role.findById"},TeamManagement:{ViewMembers:"login.findAll",ViewMember:"login.findById",CreateMember:"login.create",UpdateMember:"login.update",ArchiveMember:"login.archive",UnArchiveMember:"login.unarchive",ResetPassword:"login.resetPassword"}};class jt extends Error{requiredPermissions;constructor(e){super(e.message??`Missing required permissions: ${e.requiredPermissions.join(", ")}`),this.name="PermissionError",this.requiredPermissions=e.requiredPermissions}static is(e){const r=t.z.union([t.z.enum(Object.values(Rt.Profile)),t.z.enum(Object.values(Rt.Beneficiary)),t.z.enum(Object.values(Rt.Payment)),t.z.enum(Object.values(Rt.Payout)),t.z.enum(Object.values(Rt.Transfer)),t.z.enum(Object.values(Rt.Wallet))]);return t.z.object({name:t.z.literal("PermissionError").nullish(),message:t.z.string(),requiredPermissions:t.z.array(r)}).safeParse(e).success}}class Mt{page;limit;total;constructor(e,t,r){if(this.page=e,this.limit=t,this.total=r,e<1)throw new Error("Page must be >= 1");if(t<1)throw new Error("Limit must be >= 1");if(r<0)throw new Error("Total must be >= 0")}get totalPages(){return Math.ceil(this.total/this.limit)}get hasNext(){return this.page<this.totalPages}get hasPrev(){return this.page>1}get offset(){return(this.page-1)*this.limit}get isFirstPage(){return 1===this.page}get isLastPage(){return this.page===this.totalPages}nextPage(){return this.hasNext?new Mt(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new Mt(this.page-1,this.limit,this.total):null}toJSON(){return{page:this.page,limit:this.limit,total:this.total,totalPages:this.totalPages,hasNext:this.hasNext,hasPrev:this.hasPrev}}}const Jt=t.z.object({page:t.z.coerce.number().int().min(1).default(1),limit:t.z.coerce.number().int().min(1).max(100).default(10)}),Zt=t.z.object({page:t.z.number().int().min(1),limit:t.z.number().int().min(1),total:t.z.number().int().min(0),totalPages:t.z.number().int().min(0),hasNext:t.z.boolean(),hasPrev:t.z.boolean()});var Lt,Ft;exports.FilterOperator=void 0,(Lt=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",Lt.NOT_EQUALS="neq",Lt.LESS_THAN="lt",Lt.LESS_THAN_OR_EQUAL="lte",Lt.GREATER_THAN="gt",Lt.GREATER_THAN_OR_EQUAL="gte",Lt.LIKE="like",Lt.LIKE_LOWER="likeLower",Lt.IS_NULL="isNull",Lt.IS_NOT_NULL="isNotNull",Lt.IN="in",exports.SortDirection=void 0,(Ft=exports.SortDirection||(exports.SortDirection={})).ASC="asc",Ft.DESC="desc";const $t=Symbol("query-builder-type");class Ut{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*"};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}}[$t]="query-builder";static is(e){return null!==e&&"object"==typeof e&&$t in e&&"query-builder"===e[$t]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){if(e){const t=qt(e);this.whereGreaterThanOrEqual("createdAt",t)}if(t){const e=qt(t);this.whereLessThanOrEqual("createdAt",e)}return this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new Ut(e)}}function qt(e){return"string"==typeof e?e:new Date(e.getTime()).toISOString()}const Vt={profileDTOSchema:t.z.object({id:t.z.string(),firstName:t.z.string().nullish(),lastName:t.z.string().nullish(),displayName:t.z.string(),phone:t.z.string().nullish(),accountNo:t.z.string().min(1),email:t.z.string().email().nullish(),autoApprove:t.z.boolean().nullish()})},Wt={logInRequestDTO:t.z.object({type:t.z.string().default("password"),identity:t.z.string().email(),password:t.z.string()}),logInResponseDTO:t.z.object({profile:Vt.profileDTOSchema,token:t.z.string(),access:t.z.array(t.z.string()),resetPassword:t.z.boolean()}),accessResponseDTO:t.z.array(t.z.string()),resetPasswordRequestDTO:t.z.object({currentPassword:t.z.string(),newPassword:t.z.string()}),emptyResponseDTO:t.z.object({})},Kt={loginDTO:i.default.object({id:i.default.string().min(1,"ID is required"),profileId:i.default.string().min(1,"Profile ID is required"),name:i.default.string().min(1,"Name is required"),identity:i.default.string().email("Identity must be a valid email address"),type:i.default.string().min(1,"Type is required"),roleId:i.default.string().min(1,"Role ID is required"),isActive:i.default.boolean(),isArchived:i.default.boolean(),resetPassword:i.default.boolean(),createdAt:i.default.string().datetime("Invalid creation timestamp"),updatedAt:i.default.string().datetime("Invalid update timestamp"),access:i.default.array(i.default.string())})},Ht=t.z.object({id:t.z.string(),profileId:t.z.string(),name:t.z.string(),identity:t.z.string(),type:t.z.string(),roleId:t.z.string(),isActive:t.z.boolean(),isArchived:t.z.boolean(),resetPassword:t.z.boolean(),createdAt:t.z.string(),updatedAt:t.z.string(),access:t.z.array(t.z.string()),_version:t.z.string().optional().default("1.0")});class Gt{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;_permissionMap;constructor(e,t,r,a,n,s,i,o,c,d,u,l){this._id=e,this._profileId=t,this._name=r,this._identity=a,this._type=n,this._roleId=s,this._isActive=i,this._isArchived=o,this._resetPassword=c,this._createdAt=d,this._updatedAt=u,this._access=l,this._permissionMap={},this._access.forEach(e=>{this._permissionMap[e]=!0})}static from(e){const t=Kt.loginDTO.parse(e);return new Gt(t.id,t.profileId,t.name,t.identity,t.type,t.roleId,t.isActive,t.isArchived,t.resetPassword,new Date(t.createdAt),new Date(t.updatedAt),t.access)}get id(){return this._id}get profileId(){return this._profileId}get name(){return this._name}get identity(){return this._identity}get type(){return this._type}get roleId(){return this._roleId}get isActive(){return this._isActive}get isArchived(){return this._isArchived}get resetPassword(){return this._resetPassword}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get access(){return this._access}can(e){return this._permissionMap[e]??!1}canAny(e){return e.some(e=>this.can(e))}canAll(e){return e.every(e=>this.can(e))}toJSON(){return{id:this._id,profileId:this._profileId,name:this._name,identity:this._identity,type:this._type,roleId:this._roleId,isActive:this._isActive,isArchived:this._isArchived,resetPassword:this._resetPassword,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),access:[...this._access],_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ht.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const a=r.data;return Gt.from({id:a.id,profileId:a.profileId,name:a.name,identity:a.identity,type:a.type,roleId:a.roleId,isActive:a.isActive,isArchived:a.isArchived,resetPassword:a.resetPassword,createdAt:a.createdAt,updatedAt:a.updatedAt,access:a.access})}catch(e){return void console.error("Error parsing LogInJSON:",e)}}static isLogInJSON(e){return Ht.safeParse(e).success}}const Qt=t.z.object({id:t.z.string(),firstName:t.z.string().nullable().optional(),lastName:t.z.string().nullable().optional(),displayName:t.z.string(),phone:t.z.string().nullable().optional(),accountNo:t.z.string(),email:t.z.string().nullable().optional(),autoApprove:t.z.boolean().nullable().optional(),_version:t.z.string().optional().default("1.0")});class Yt{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return Vt.profileDTOSchema}constructor(e){this._id=e.id,this._firstName=e.firstName,this._lastName=e.lastName,this._displayName=e.displayName,this._phone=e.phone,this._accountNo=e.accountNo,this._email=e.email,this._autoApprove=e.autoApprove}static create(e){return new Yt({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove})}get id(){return this._id}get firstName(){return this._firstName}get lastName(){return this._lastName}get displayName(){return this._displayName}get phone(){return this._phone}get accountNo(){return this._accountNo}get email(){return this._email}get autoApprove(){return this._autoApprove}getName(){if(this._displayName&&""!==this._displayName.trim())return this._displayName;return`${this._firstName??""} ${this._lastName??""}`.trim()}validate(){try{return Yt.schema.safeParse(this.toJSON()).success}catch(e){return console.error("Profile validation error:",e),!1}}static from(e){try{return e?"object"!=typeof e?void console.error("Data is not an object"):e.id&&e.accountNo&&e.displayName?Yt.create({id:e.id,firstName:e.firstName,lastName:e.lastName,displayName:e.displayName,phone:e.phone,accountNo:e.accountNo,email:e.email,autoApprove:e.autoApprove}):void console.error("Missing required profile fields"):void console.error("Data is null or undefined")}catch(e){return void console.error("Error creating profile from object:",e)}}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t._id||"string"!=typeof t._displayName||"string"!=typeof t._accountNo)return!1;if(null!==t._firstName&&void 0!==t._firstName&&"string"!=typeof t._firstName)return!1;if(null!==t._lastName&&void 0!==t._lastName&&"string"!=typeof t._lastName)return!1;if(null!==t._email&&void 0!==t._email&&"string"!=typeof t._email)return!1;const r=t._phone;if(null!=r&&"string"!=typeof r)return!1;const a=t._autoApprove;return null==a||"boolean"==typeof a}toJSON(){return{id:this._id,firstName:this._firstName,lastName:this._lastName,displayName:this._displayName,phone:this._phone,accountNo:this._accountNo,email:this._email,autoApprove:this._autoApprove,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Qt.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const a=r.data;return Yt.from(a)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return Qt.safeParse(e).success}}const Xt=i.default.object({id:i.default.string(),name:i.default.string(),description:i.default.string().nullable().optional(),access:i.default.array(i.default.string()),createdAt:i.default.string(),updatedAt:i.default.string(),_version:i.default.string().optional().default("1.0")});class er{id;name;description;permissions;createdAt;updatedAt;constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.permissions=new Set(e.access),this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}hasPermission(e){return this.permissions.has(e)}static from(e){try{if(!e?.id||!e?.name||!Array.isArray(e?.access))return;return new er(e)}catch(e){return void console.error("Error creating Role:",e)}}toJSON(){return{id:this.id,name:this.name,description:this.description,access:Array.from(this.permissions),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Xt.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const a=r.data;return er.from({id:a.id,name:a.name,description:a.description,access:a.access,createdAt:a.createdAt,updatedAt:a.updatedAt})}catch(e){return void console.error("Error parsing RoleJSON:",e)}}static isRoleJSON(e){return Xt.safeParse(e).success}}const tr=i.default.object({companyProfile:Qt,role:Xt.optional(),_version:i.default.string().optional().default("1.0")});class rr{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return Yt.is(e.companyProfile)?new rr(e):void console.error("Invalid company profile")}catch(e){return void console.error("Error creating CompanyMembership:",e)}}get companyProfile(){return this._companyProfile}get role(){return this._role}toJSON(){return{companyProfile:this._companyProfile.toJSON(),role:this._role?.toJSON(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=tr.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const a=r.data,n=Yt.fromJSON(a.companyProfile),s=a.role?er.fromJSON(a.role):void 0;return n?rr.from({companyProfile:n,role:s}):void console.error("Failed to reconstruct Profile from CompanyMembershipJSON")}catch(e){return void console.error("Error parsing CompanyMembershipJSON:",e)}}static isCompanyMembershipJSON(e){return tr.safeParse(e).success}}const ar=i.default.object({logIn:Ht,companyProfile:Qt,role:Xt.optional(),_version:i.default.string().optional().default("1.0")});class nr{_logIn;_membership;constructor(e){this._logIn=e.logIn,this._membership=e.membership}static from(e){try{if(!e.logIn||!e.companyProfile)return void console.error("Missing required User fields");const t=rr.from({companyProfile:e.companyProfile,role:e.role});return t?new nr({logIn:e.logIn,membership:t}):void console.error("Failed to create CompanyMembership")}catch(e){return void console.error("Error creating User:",e)}}get logIn(){return this._logIn}get login(){return this._logIn}get membership(){return this._membership}get id(){return this._logIn.id}get name(){return this._logIn.name}get identity(){return this._logIn.identity}get roleId(){return this._logIn.roleId}get resetPassword(){return this._logIn.resetPassword}get profile(){return this._membership.companyProfile}get role(){return this._membership.role}get access(){return this._logIn.access}toJSON(){return{logIn:this._logIn.toJSON(),companyProfile:this._membership.companyProfile.toJSON(),role:this._membership.role?.toJSON(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=ar.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const a=r.data,n=Gt.fromJSON(a.logIn),s=Yt.fromJSON(a.companyProfile),i=a.role?er.fromJSON(a.role):void 0;if(!n||!s)return void console.error("Failed to reconstruct nested objects from UserJSON");const o=rr.from({companyProfile:s,role:i});return o?new nr({logIn:n,membership:o}):void console.error("Failed to create CompanyMembership from UserJSON")}catch(e){return void console.error("Error parsing UserJSON:",e)}}static isUserJSON(e){return ar.safeParse(e).success}}const sr=wt().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:Kt.loginDTO}}});class ir extends Dt{constructor(e){super("login",sr,e)}async getIdentity(){const e=await this.client.getUserCredentials();if(200===e.status)return e.body;throw new Error(`Failed to get user identity. Status: ${e.status}`)}}const or=t.z.string().min(8,"Password must be at least 8 characters long").max(128,"Password must not exceed 128 characters").regex(/[A-Z]/,"Password must contain at least one uppercase letter").regex(/[a-z]/,"Password must contain at least one lowercase letter").regex(/[0-9]/,"Password must contain at least one number").regex(/[!@#$%^&*()_+\-=[\]{}|;:,.<>?]/,"Password must contain at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)").refine(e=>![/(.)\1{2,}/,/123456|654321|abcdef|qwerty|password|admin|user/i,/^[0-9]+$/,/^[a-zA-Z]+$/].some(t=>t.test(e)),"Password contains weak patterns. Avoid repeated characters, common words, or simple sequences").refine(e=>!/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)/i.test(e),"Password should not contain sequential characters").refine(e=>!/(?:qwer|wert|erty|rtyu|tyui|yuio|uiop|asdf|sdfg|dfgh|fghj|ghjk|hjkl|zxcv|xcvb|cvbn|vbnm)/i.test(e),"Password should not contain keyboard patterns"),cr=t.z.object({id:t.z.string().min(1),name:t.z.string().min(1,"Role name is required"),description:t.z.string().nullable().optional(),access:t.z.array(t.z.string()),createdAt:t.z.string().datetime("Invalid creation timestamp"),updatedAt:t.z.string().datetime("Invalid update timestamp")}),dr=t.z.object({id:t.z.string().min(1),name:t.z.string().min(1,"Team member name is required"),identity:t.z.string().email("Invalid email address"),type:t.z.string().min(1,"Team member type is required"),profileId:t.z.string().min(1,"Profile ID is required"),roleId:t.z.string().min(1,"Role ID is required"),resetPassword:t.z.boolean(),isActive:t.z.boolean(),isArchived:t.z.boolean(),role:cr.optional(),createdAt:t.z.string().datetime("Invalid creation timestamp"),updatedAt:t.z.string().datetime("Invalid update timestamp")}),ur={role:cr,teamMember:dr,teamMemberQueryParams:t.z.object({id:t.z.string().min(1).optional(),name:t.z.string().min(1).optional(),identity:t.z.string().email("Invalid email address").optional(),type:t.z.string().min(1).optional(),profileId:t.z.string().min(1).optional(),roleId:t.z.string().min(1).optional(),resetPassword:t.z.number().optional(),isActive:t.z.number().optional(),isArchived:t.z.number().optional(),createdAt:t.z.string().datetime("Invalid creation timestamp").optional(),updatedAt:t.z.string().datetime("Invalid update timestamp").optional(),eager:t.z.string().optional()}),createTeamMemberRequest:t.z.object({name:t.z.string().min(1,"Team member name is required"),identity:t.z.string().email("Valid email address is required"),password:or.optional(),roleId:t.z.string().optional(),resetPassword:t.z.boolean().optional()}),updateTeamMemberRequest:t.z.object({name:t.z.string().min(1,"Team member name cannot be empty").optional(),roleId:t.z.string().min(1,"Role ID cannot be empty").optional(),password:or.optional(),resetPassword:t.z.boolean().optional(),isActive:t.z.boolean().optional()}),resetPasswordRequest:t.z.object({newPassword:or.optional(),sendNotification:t.z.boolean().optional()}),createTeamMemberResponse:t.z.object({id:t.z.string(),name:t.z.string(),identity:t.z.string(),type:t.z.string(),profileId:t.z.string(),resetPassword:t.z.boolean(),roleId:t.z.string(),isActive:t.z.boolean(),isArchived:t.z.boolean(),createdAt:t.z.string().datetime(),updatedAt:t.z.string().datetime()}),password:or},lr=wt().router({getTeamMembers:{method:"GET",path:"/login",query:ur.teamMemberQueryParams,responses:{200:t.z.array(ur.teamMember),401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()})},summary:"List all team members",description:"Retrieve a list of all team member accounts in the system"},getTeamMember:{method:"GET",path:"/login/:id",pathParams:t.z.object({id:t.z.string()}),query:ur.teamMemberQueryParams,responses:{200:ur.teamMember,401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()}),404:t.z.object({message:t.z.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:ur.createTeamMemberRequest,responses:{201:ur.createTeamMemberResponse,400:t.z.object({message:t.z.string().optional(),errors:t.z.array(t.z.string()).optional()}),401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()}),409:t.z.object({message:t.z.string().optional()})},summary:"Create new team member",description:"Create a new team member account with specified role and permissions"},updateTeamMember:{method:"PATCH",path:"/login/:id",pathParams:t.z.object({id:t.z.string()}),body:ur.updateTeamMemberRequest,responses:{200:ur.teamMember,400:t.z.object({message:t.z.string().optional(),errors:t.z.array(t.z.string()).optional()}),401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()}),404:t.z.object({message:t.z.string().optional()})},summary:"Update team member",description:"Update team member information, role, status, or force password reset"},archiveTeamMember:{method:"POST",path:"/login/:id/archive",pathParams:t.z.object({id:t.z.string()}),body:t.z.object({}),responses:{201:ur.teamMember,401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()}),404:t.z.object({message:t.z.string().optional()}),409:t.z.object({message:t.z.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:t.z.object({id:t.z.string()}),body:t.z.object({}),responses:{201:ur.teamMember,401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()}),404:t.z.object({message:t.z.string().optional()}),409:t.z.object({message:t.z.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:t.z.object({id:t.z.string()}),body:ur.resetPasswordRequest,responses:{201:t.z.object({success:t.z.boolean()}),400:t.z.object({message:t.z.string().optional()}),401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()}),404:t.z.object({message:t.z.string().optional()})},summary:"Reset team member password",description:"Reset a team member's password and optionally send notification"},getRoles:{method:"GET",path:"/role",responses:{200:t.z.array(ur.role),401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:ur.role,401:t.z.object({message:t.z.string().optional()}),403:t.z.object({message:t.z.string().optional()}),404:t.z.object({message:t.z.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),pr=i.default.object({id:i.default.string(),name:i.default.string(),identity:i.default.string(),type:i.default.string(),profileId:i.default.string(),roleId:i.default.string(),resetPassword:i.default.boolean(),isActive:i.default.boolean(),isArchived:i.default.boolean(),role:Xt.optional(),createdAt:i.default.string(),updatedAt:i.default.string(),_version:i.default.string().optional().default("1.0")});class hr{id;name;identity;type;profileId;roleId;resetPassword;isActive;isArchived;role;createdAt;updatedAt;permissions;constructor(e){if(this.id=e.id,this.name=e.name,this.identity=e.identity,this.type=e.type,this.profileId=e.profileId,this.roleId=e.roleId,this.resetPassword=e.resetPassword,this.isActive=e.isActive,this.isArchived=e.isArchived,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.permissions=new Set(e.role?.access??[]),e.role)try{this.role=new er(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new hr(e):void console.error("Missing required TeamMember fields:",e)}catch(e){return void console.error("Error creating TeamMember:",e)}}static fromJson(e){try{const t=JSON.parse(e);return hr.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>hr.from(e)).filter(Boolean)}can(e){return this.permissions.has(e)}canAny(e){return e.some(e=>this.permissions.has(e))}canAll(e){return e.every(e=>this.permissions.has(e))}isAccountActive(){return this.isActive}isAccountArchived(){return this.isArchived}needsPasswordReset(){return this.resetPassword}getAccountStatus(){return this.isArchived?{status:"archived",label:"Archived",color:"default",description:"Account has been archived and is no longer accessible"}:this.isActive?this.resetPassword?{status:"password_reset_required",label:"Password Reset Required",color:"warning",description:"User must reset their password on next login"}:{status:"active",label:"Active",color:"success",description:"Account is active and ready to use"}:{status:"inactive",label:"Inactive",color:"error",description:"Account has been deactivated by an administrator"}}getRoleName(){return this.role?.name??""}getCreatedDate(){return this.createdAt.toLocaleDateString()}getLastUpdateInfo(){const e=(new Date).getTime()-this.updatedAt.getTime(),t=Math.floor(e/864e5);return 0===t?"Today":1===t?"Yesterday":t<7?`${t} days ago`:t<30?`${Math.floor(t/7)} weeks ago`:this.updatedAt.toLocaleDateString()}toJSON(){return{id:this.id,name:this.name,identity:this.identity,type:this.type,profileId:this.profileId,roleId:this.roleId,resetPassword:this.resetPassword,isActive:this.isActive,isArchived:this.isArchived,role:this.role?.toJSON(),createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=pr.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const a=r.data,n=a.role?{id:a.role.id,name:a.role.name,description:a.role.description,access:a.role.access,createdAt:a.role.createdAt,updatedAt:a.role.updatedAt}:void 0;return hr.from({id:a.id,name:a.name,identity:a.identity,type:a.type,profileId:a.profileId,roleId:a.roleId,resetPassword:a.resetPassword,isActive:a.isActive,isArchived:a.isArchived,role:n,createdAt:a.createdAt,updatedAt:a.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return pr.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>hr.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing TeamMember JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}}class mr extends Dt{constructor(e){super("admin",lr,e)}async createTeamMember(e){const t=await this.client.createTeamMember({body:e});return this.handleResponse(t,201)}async updateTeamMember(e,t){const r=await this.client.updateTeamMember({params:{id:e},body:t}),a=this.handleResponse(r,200),n=hr.from(a);if(!n)throw new Error("Invalid team member data received from server");return n}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e},body:{}}),r=this.handleResponse(t,201),a=hr.from(r);if(!a)throw new Error("Invalid team member data received from server");return a}async unArchiveTeamMember(e){const t=await this.client.unArchiveTeamMember({params:{id:e},body:{}}),r=this.handleResponse(t,201),a=hr.from(r);if(!a)throw new Error("Invalid team member data received from server");return a}async resetTeamMemberPassword(e,t={}){const r=await this.client.resetPassword({params:{id:e},body:t});return this.handleResponse(r,201)}async getAllTeamMembers(e={eager:"roleId"}){const t=await this.client.getTeamMembers({query:e}),r=this.handleResponse(t,200);return hr.createMany(r)}async getTeamMember(e,t={eager:"roleId"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),a=this.handleResponse(r,200),n=hr.from(a);if(!n)throw new Error("Invalid team member data received from server");return n}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=er.from(e);if(!t)throw new Error("Invalid role data received from server");return t})}async getRole(e){const t=await this.client.getRole({params:{id:e}}),r=this.handleResponse(t,200),a=er.from(r);if(!a)throw new Error("Invalid role data received from server");return a}}const fr=wt().router({logIn:{method:"POST",path:"/login",body:Wt.logInRequestDTO,responses:{201:Wt.logInResponseDTO,400:Wt.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:Wt.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:Wt.resetPasswordRequestDTO,responses:{200:Wt.emptyResponseDTO,400:Wt.emptyResponseDTO}}});var yr;exports.BeneficiaryType=void 0,(yr=exports.BeneficiaryType||(exports.BeneficiaryType={})).BANK="Bank",yr.MOBILE="Mobile";const gr=t.z.nativeEnum(exports.BeneficiaryType),vr=t.z.object({displayName:t.z.string().min(1,"Display name is required"),accountNo:t.z.string().min(1,"Account number is required"),channel:t.z.string().min(1,"Channel is required"),type:gr}),_r={beneficiaryDTO:t.z.object({id:t.z.string().min(1,"Beneficiary id is required"),profileId:t.z.string(),createdAt:t.z.string().datetime(),updatedAt:t.z.string().datetime()}).merge(vr),beneficiaryInputDTO:vr,beneficiaryType:gr},br=wt().router({createBeneficiary:{method:"POST",path:"/",body:_r.beneficiaryInputDTO,responses:{201:_r.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:_r.beneficiaryInputDTO,responses:{200:_r.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:t.z.object({orderByDesc:t.z.string()}),responses:{200:t.z.array(_r.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:_r.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:t.z.object({}),responses:{200:t.z.object({})}}}),Nr=t.z.object({type:t.z.literal(exports.BeneficiaryType.MOBILE),name:t.z.string().min(1),phoneNumber:r.E164PhoneNumberFormatSchema,mnoId:r.MobileMoneyProviderIdSchema,_version:t.z.string().optional().default("1.0")}),wr=t.z.object({type:t.z.literal(exports.BeneficiaryType.BANK),accName:t.z.string().min(1),swiftCode:t.z.union([r.TZBankSWIFTCodeSchema,r.KEBankSWIFTCodeSchema]),countryCode:r.ISO2CountryCodeSchema,accNo:t.z.string().min(1),_version:t.z.string().optional().default("1.0")}),Ir=t.z.discriminatedUnion("type",[Nr,wr]);class Sr extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class Ar{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===exports.BeneficiaryType.MOBILE}get isBank(){return this.type===exports.BeneficiaryType.BANK}get displayName(){return this.accountName}}class Or extends Ar{name;phoneNumber;mnoId;constructor(e,t,r){super(exports.BeneficiaryType.MOBILE,t.countryCode),this.name=e,this.phoneNumber=t;const a=Or.resolveMnoId(t,r),n=Or.checkInputs(e,t,a);if(!n.isValid)throw new Sr(n.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:a});this.mnoId=a}static resolveMnoId(e,t){return r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)?t:r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,a){const n=[];return e?.trim()||n.push("Name is required and cannot be empty"),t?.validate()||n.push("Invalid phone number"),a?r.MobileMoneyProviderHelpers.validateProviderForPhoneNumber(t,a)||n.push(`Invalid MNO ${a} for phone number ${t.e164Format}`):n.push(r.MobileMoneyProviderHelpers.requiresExplicitProvider(t.countryCode)?`MNO must be explicitly provided for phone numbers in ${t.countryCode}`:`Failed to determine MNO for phone number ${t.e164Format}`),{isValid:0===n.length,errors:n,warnings:[]}}static pickMnoIdFromDTO(e,t){const a=Or.pickMnoIdFromPayoutChannel(e.countryCode,t);if(a)return a;if(r.MobileMoneyProviderHelpers.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return r.MobileMoneyProviderHelpers.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const n=r.MobileMoneyProviderHelpers.detectProviderByPhoneNumber(e);if(n)return n.id;console.warn(`Failed to auto-detect MNO for phone number ${e.e164Format}`)}static pickMnoIdFromPayoutChannel(e,t){if("string"!=typeof t)return;const[a,n,s]=t.split("-");return"B2C"===s&&"BANK"!==n&&a===e&&r.MobileMoneyProviderHelpers.isProviderSupported(e,n)?n:void 0}static from(e){try{return new Or(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.MOBILE)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,a=r.PhoneNumber.from(t);if(!a)return void console.error(`Failed to parse phone number ${t}`);const n=Or.pickMnoIdFromDTO(a,e.channel);return n?Or.from({name:e.displayName,phoneNumber:a,mnoId:n}):void 0}static fromBeneficiaryDTO(e){return Or.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=r.PhoneNumber.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);const a=Or.pickMnoIdFromDTO(t,e.channel);return a?Or.from({name:e.payeeName,phoneNumber:t,mnoId:a}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.MOBILE&&(!("string"!=typeof t.name||!t.name.trim())&&(!!r.PhoneNumber.is(t.phoneNumber)&&("string"==typeof t.mnoId&&r.MobileMoneyProviderHelpers.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return Or.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return Or.checkInputs(this.name,this.phoneNumber,this.mnoId)}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(r.PhoneNumberFormat.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return r.MobileMoneyProviderHelpers.findById(this.mnoId,this.countryCode)}toJSON(){return{type:exports.BeneficiaryType.MOBILE,name:this.name,phoneNumber:this.phoneNumber.e164Format,mnoId:this.mnoId,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=Nr.safeParse(t);if(!a.success)return void console.error("Invalid MobileBeneficiaryJSON:",a.error.flatten());const n=r.PhoneNumber.from(a.data.phoneNumber);if(!n)return;return Or.from({name:a.data.name,phoneNumber:n,mnoId:a.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return Or.fromJSON(e)}static isJSON(e){return Nr.safeParse(e).success}}class Cr extends Ar{accName;bank;accNo;constructor(e,t,r){super(exports.BeneficiaryType.BANK,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const a=Cr.checkInputs(e,t,r);if(!a.isValid)throw new Sr(a.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,a){const n=[];return r.BankHelpers.validateAccountName(e)||n.push("Invalid account name"),r.Bank.is(t)?r.BankHelpers.validateAccountNumber(a,t.countryCode)||n.push("Invalid account number"):n.push("Invalid bank reference"),{isValid:0===n.length,errors:n,warnings:[]}}static from(e){try{return new Cr(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==exports.BeneficiaryType.BANK)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const a=r.BankHelpers.getCountryFromSwiftCode(t);if(!a)return void console.error(`Could not identify country from SWIFT code: ${t}`);const n=r.Bank.fromBIC(t,a);if(n)return Cr.from({accName:e.displayName,bank:n,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromBeneficiaryDTO(e){return Cr.fromInputDTO(e)}static fromPayoutDTO(e){if(!r.CountryHelpers.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=e.msisdn.trim().split(":");if(2!==t.length)return void console.error("Invalid PayoutDTO format for bank — expected 'swiftcode:accountno'");const[a,n]=t,s=r.Bank.fromBIC(a,e.countryCode);if(s)return Cr.from({accName:e.payeeName,bank:s,accNo:n});console.error(`Bank with SWIFT code ${a} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===exports.BeneficiaryType.BANK&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!r.Bank.is(t.bank)&&(r.BankHelpers.validateAccountName(t.accName)&&r.BankHelpers.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return Cr.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return Cr.checkInputs(this.accName,this.bank,this.accNo)}get accountName(){return this.accName}get accountNumber(){return this.accNo}get accountNameLabel(){return"Acc. Name"}get accountNumberLabel(){return"Bank Acc. No."}get channelLabel(){return"Bank"}get channelId(){return this.bank.bic}get channelName(){return this.bank.shortName}toJSON(){return{type:exports.BeneficiaryType.BANK,accName:this.accName,swiftCode:this.bank.bic,countryCode:this.bank.countryCode,accNo:this.accNo,_version:"1.0"}}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=wr.safeParse(t);if(!a.success)return void console.error("Invalid BankBeneficiaryJSON:",a.error.flatten());const n=a.data;if(!r.CountryHelpers.isISO2Code(n.countryCode))return;const s=r.Bank.fromBIC(n.swiftCode,n.countryCode);if(!s)return;return Cr.from({accName:n.accName,bank:s,accNo:n.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return Cr.fromJSON(e)}static isJSON(e){return wr.safeParse(e).success}}class xr{static fromInputDTO(e){return xr.fromDTO(e)}static fromBeneficiaryDTO(e){return xr.fromDTO(e)}static fromPayoutDTO(e){return e.msisdn.includes(":")?Cr.fromPayoutDTO(e):Or.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ir.safeParse(t);if(!r.success)return;return r.data.type===exports.BeneficiaryType.MOBILE?Or.fromJSON(r.data):Cr.fromJSON(r.data)}catch{return}}static fromJSONString(e){return xr.fromJSON(e)}static is(e){return Or.is(e)||Cr.is(e)}static isJSON(e){return Ir.safeParse(e).success}static fromDTO(e){return e.type===exports.BeneficiaryType.MOBILE?Or.fromInputDTO(e):Cr.fromInputDTO(e)}}const Pr={fromInputDTO:e=>xr.fromInputDTO(e),fromBeneficiaryDTO:e=>xr.fromBeneficiaryDTO(e),fromPayoutDTO:e=>xr.fromPayoutDTO(e),fromJSON:e=>xr.fromJSON(e),fromJSONString:e=>xr.fromJSONString(e),is:e=>xr.is(e),isJSON:e=>xr.isJSON(e)},Tr=_r.beneficiaryDTO.extend({_version:t.z.string().optional().default("1.0")});class zr{_id;_profileId;_displayName;_accountNo;_channel;_type;_createdAt;_updatedAt;_info;_infoComputed=!1;constructor(e){const t=_r.beneficiaryDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._displayName=t.displayName,this._accountNo=t.accountNo,this._channel=t.channel,this._type=t.type,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt}get id(){return this._id}get profileId(){return this._profileId}get displayName(){return this._displayName}get type(){return this._type}get createdAt(){return new Date(this._createdAt)}get updatedAt(){return new Date(this._updatedAt)}get info(){return this._infoComputed||(this._infoComputed=!0,this._info=xr.fromBeneficiaryDTO(this.toDTO())),this._info}get accNo(){const e=this.info;return e?e.accountNumber:this._accountNo}get accName(){return this._displayName}get accNoLabel(){return this.type===exports.BeneficiaryType.MOBILE?"Phone Number":this.type===exports.BeneficiaryType.BANK?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===exports.BeneficiaryType.MOBILE?"Channel":this.type===exports.BeneficiaryType.BANK?"Bank":"Channel"}get accNameLabel(){return this.type===exports.BeneficiaryType.MOBILE?"Full Name":this.type===exports.BeneficiaryType.BANK?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new zr(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new zr(e)}static createMany(e){return e.map(e=>new zr(e))}static createSafe(e){return zr.from(e)??null}static canConstruct(e){return _r.beneficiaryDTO.safeParse(e).success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return Tr.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{...this.toDTO(),_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=t&&"object"==typeof t&&"data"in t?t.data:t,a=Tr.safeParse(r);if(!a.success)return void console.error("Invalid BeneficiaryJSON:",a.error.flatten());const n=a.data,{_version:s,...i}=n;return zr.from(i)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return zr.fromJSON(e)}static isBeneficiaryJSON(e){return Tr.safeParse(e).success}toDTO(){return{id:this._id,profileId:this._profileId,displayName:this._displayName,accountNo:this._accountNo,channel:this._channel,type:this._type,createdAt:this._createdAt,updatedAt:this._updatedAt}}}class Er{canHandle(e){return e.type===exports.BeneficiaryType.MOBILE&&Or.is(e)}createInput(e){if(Or.is(e))return{type:exports.BeneficiaryType.MOBILE,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class Br{canHandle(e){return e.type===exports.BeneficiaryType.BANK&&Cr.is(e)}createInput(e){if(Cr.is(e))return{type:exports.BeneficiaryType.BANK,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class kr{handlers=[new Er,new Br];resolve(e){const t=this.handlers.find(t=>t.canHandle(e));if(!t)throw new Error("Please check your data and try again");return t.createInput(e)}}var Dr,Rr,jr;exports.PayoutChannel=void 0,(Dr=exports.PayoutChannel||(exports.PayoutChannel={})).TZ_TIGO_B2C="TZ-TIGO-B2C",Dr.TZ_VODACOM_B2C="TZ-VODACOM-B2C",Dr.TZ_AIRTEL_B2C="TZ-AIRTEL-B2C",Dr.TZ_HALOTEL_B2C="TZ-HALOTEL-B2C",Dr.KE_SAFARICOM_B2C="KE-SAFARICOM-B2C",Dr.TZ_BANK_B2C="TZ-BANK-B2C",Dr.KE_BANK_B2C="KE-BANK-B2C",exports.PayoutStatus=void 0,(Rr=exports.PayoutStatus||(exports.PayoutStatus={})).CREATED="CREATED",Rr.PENDING="PENDING",Rr.PAID="PAID",Rr.FAILED="FAILED",Rr.REJECTED="REJECTED",Rr.REVERSED="REVERSED",Rr.QUEUED="QUEUED",exports.PayoutApprovalStatus=void 0,(jr=exports.PayoutApprovalStatus||(exports.PayoutApprovalStatus={})).PENDING="Pending",jr.APPROVED="Approved",jr.REJECTED="Rejected";const Mr=t.z.object({id:t.z.string(),name:t.z.string(),identity:t.z.string()}),Jr=t.z.nativeEnum(exports.PayoutStatus),Zr=t.z.nativeEnum(exports.PayoutApprovalStatus),Lr=t.z.nativeEnum(exports.PayoutChannel),Fr=t.z.union([t.z.string(),t.z.array(t.z.string())]).transform(e=>(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(e=>e.length>0)),$r=Fr.pipe(t.z.array(Jr)),Ur=Fr.pipe(t.z.array(Zr)),qr=t.z.object({channel:Lr,msisdn:t.z.string(),amount:t.z.coerce.number(),description:t.z.string(),notes:t.z.string().nullish()}),Vr=qr.extend({payeeName:t.z.string()}),Wr=qr.extend({id:t.z.string(),profileId:t.z.string(),payeeName:t.z.string(),countryCode:t.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(e),{message:"Provided currency code is not a valid currency code."}),channel:t.z.string(),status:Jr,statusMessage:t.z.string(),partnerReference:t.z.string().nullish(),createdAt:t.z.coerce.date(),updatedAt:t.z.coerce.date(),actionedAt:t.z.coerce.date().nullish(),approvalStatus:Zr.nullish(),createdById:t.z.string().nullish(),actionedById:t.z.string().nullish(),createdBy:Mr.nullish(),actionedBy:Mr.nullish()}),Kr=t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(100).default(10),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().datetime().nullish(),endDate:t.z.string().datetime().nullish(),payeeName:t.z.string().nullish(),msisdn:t.z.string().nullish(),msisdnIn:Fr.nullish(),profileId:t.z.string().nullish(),id:t.z.string().nullish(),partnerReference:t.z.string().nullish(),channel:t.z.string().nullish(),channelIn:Fr.nullish(),currencyCode:t.z.string().nullish(),status:Jr.nullish(),statusIn:$r.nullish(),approvalStatus:Zr.nullish(),approvalStatusIn:Ur.nullish(),createdById:t.z.string().nullish(),createdByIdIn:Fr.nullish(),actionedById:t.z.string().nullish(),actionedByIdIn:Fr.nullish(),minAmount:t.z.number().min(0).nullish(),maxAmount:t.z.number().min(0).nullish(),search:t.z.string().nullish(),relations:t.z.array(t.z.string()).nullish()}),Hr={PayoutDTO:Wr,PayoutInputDTO:Vr,PayoutStatus:Jr,PayoutApprovalStatus:Zr,PayoutChannel:Lr,PayoutAuthorizer:Mr,PayoutFilters:Kr,PayoutURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),payeeName:t.z.string().optional(),msisdn:t.z.string().optional(),msisdnIn:Fr.optional(),profileId:t.z.string().optional(),id:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:t.z.string().optional(),channelIn:Fr.optional(),status:t.z.string().refine(e=>Object.values(exports.PayoutStatus).includes(e)).transform(e=>e).optional(),statusIn:$r.optional(),approvalStatus:t.z.string().refine(e=>Object.values(exports.PayoutApprovalStatus).includes(e)).transform(e=>e).optional(),approvalStatusIn:Ur.optional(),createdById:t.z.string().optional(),createdByIdIn:Fr.optional(),actionedById:t.z.string().optional(),actionedByIdIn:Fr.optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional(),relations:t.z.array(t.z.string()).optional()})},Gr=i.default.object({id:i.default.string(),profileId:i.default.string(),payeeName:i.default.string(),channel:i.default.string(),msisdn:i.default.string(),amount:i.default.number(),currencyCode:i.default.string(),countryCode:i.default.string(),description:i.default.string(),notes:i.default.string().nullish(),status:Hr.PayoutStatus,statusMessage:i.default.string(),partnerReference:i.default.string().nullish(),createdAt:i.default.string(),updatedAt:i.default.string(),actionedAt:i.default.string().nullish(),approvalStatus:Hr.PayoutApprovalStatus.nullish(),createdById:i.default.string().nullish(),actionedById:i.default.string().nullish(),createdBy:Hr.PayoutAuthorizer.nullish(),actionedBy:Hr.PayoutAuthorizer.nullish(),_version:i.default.string().optional().default("1.0")});class Qr{_id;_profileId;_payeeName;_channel;_msisdn;_amount;_currencyCode;_countryCode;_description;_notes;_status;_statusMessage;_partnerReference;_createdAt;_updatedAt;_actionedAt;_approvalStatus;_createdById;_actionedById;_createdBy;_actionedBy;constructor(e){const t=Hr.PayoutDTO.parse(e);this._id=t.id,this._profileId=t.profileId,this._payeeName=t.payeeName,this._channel=t.channel,this._msisdn=t.msisdn,this._amount=t.amount,this._currencyCode=t.currencyCode,this._countryCode=t.countryCode,this._description=t.description,this._notes=t.notes,this._status=t.status,this._statusMessage=t.statusMessage,this._partnerReference=t.partnerReference,this._createdAt=t.createdAt,this._updatedAt=t.updatedAt,this._actionedAt=t.actionedAt,this._approvalStatus=t.approvalStatus,this._createdById=t.createdById,this._actionedById=t.actionedById,this._createdBy=t.createdBy,this._actionedBy=t.actionedBy}get id(){return this._id}get profileId(){return this._profileId}get payeeName(){return this._payeeName}get channel(){return this._channel}get msisdn(){return this._msisdn}get amount(){return r.Amount.from(this._amount,this._currencyCode)}get description(){return this._description}get notes(){return this._notes}get status(){return this._approvalStatus===exports.PayoutApprovalStatus.REJECTED?exports.PayoutStatus.REJECTED:this._approvalStatus===exports.PayoutApprovalStatus.APPROVED?"FAILED"===this._status?exports.PayoutStatus.FAILED:exports.PayoutStatus.PAID:this._approvalStatus===exports.PayoutApprovalStatus.PENDING?exports.PayoutStatus.PENDING:this._status}get statusMessage(){return this._statusMessage}get partnerReference(){return this._partnerReference}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get actionedAt(){return this._actionedAt}get approvalStatus(){return this._approvalStatus}get createdById(){return this._createdById}get actionedById(){return this._actionedById}get createdBy(){return this._createdBy}get actionedBy(){return this._actionedBy}get beneficiaryInfo(){return xr.fromPayoutDTO(this.toDTO())}get contactInfo(){return this.beneficiaryInfo}static create(e){return new Qr(e)}static createMany(e){return e.map(e=>new Qr(e))}static createSafe(e){try{return new Qr(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Hr.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==Qr.createSafe(t.data)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;if("function"!=typeof t.toJSON)return!1;try{return Gr.safeParse(t.toJSON()).success}catch{return!1}}toJSON(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt.toISOString(),updatedAt:this._updatedAt.toISOString(),actionedAt:this._actionedAt?.toISOString()??null,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=Gr.safeParse(t);if(!a.success)return void console.error("Invalid PayoutJSON:",a.error.flatten());const n=a.data,s=n.currencyCode;if(!r.CurrencyHelpers.isCode(s))return void console.error("Invalid currency code:",s);const i=n.countryCode;if(!r.CountryHelpers.isISO2Code(i))return void console.error("Invalid country code:",i);const o={id:n.id,profileId:n.profileId,payeeName:n.payeeName,channel:n.channel,msisdn:n.msisdn,amount:n.amount,currencyCode:s,countryCode:i,description:n.description,notes:n.notes,status:n.status,statusMessage:n.statusMessage,partnerReference:n.partnerReference,createdAt:new Date(n.createdAt),updatedAt:new Date(n.updatedAt),actionedAt:n.actionedAt?new Date(n.actionedAt):null,approvalStatus:n.approvalStatus,createdById:n.createdById,actionedById:n.actionedById,createdBy:n.createdBy,actionedBy:n.actionedBy};return Qr.create(o)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return Gr.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Qr.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing Payout JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toDTO(){return{id:this._id,profileId:this._profileId,payeeName:this._payeeName,channel:this._channel,msisdn:this._msisdn,amount:this._amount,currencyCode:this._currencyCode,countryCode:this._countryCode,description:this._description,notes:this._notes,status:this._status,statusMessage:this._statusMessage,partnerReference:this._partnerReference,createdAt:this._createdAt,updatedAt:this._updatedAt,actionedAt:this._actionedAt,approvalStatus:this._approvalStatus,createdById:this._createdById,actionedById:this._actionedById,createdBy:this._createdBy,actionedBy:this._actionedBy}}}const Yr=["approvalStatus","status","channel","msisdn","createdById","actionedById"];class Xr extends Ut{static create(){return new Xr}static fromFilters(e){return(new Xr).applyFilters(e)}static fromUrlParams(e){try{const t=Hr.PayoutURLQueryParams.parse(Xr.normalizeUrlParams(e)),r=Hr.PayoutFilters.parse(t);return Xr.fromFilters(r)}catch(e){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){try{return null==e?new Xr:Ut.is(e)?new Xr(e.options):e instanceof URLSearchParams?Xr.fromSearchParams(e):Xr.isUrlParamsRecord(e)?Xr.fromUrlParams(e):Xr.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a PayoutQuery 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 a=t[r];void 0===a?t[r]=e:Array.isArray(a)?t[r]=[...a,e]:t[r]=[a,e]}),t}static normalizeUrlParams(e){const t={...e},r=t.eager;if("string"==typeof r){const e=r.replace(/^\[|\]$/g,"").split(",").map(e=>e.trim()).filter(Boolean);e.length>0&&(t.relations=e),delete t.eager}for(const e of Yr){const r=e,a=`${e}In`,n=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Xr.toStringList([t[a],t[n],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[a]=c),Array.isArray(o)&&delete t[r],delete t[n],delete t[s],delete t[i]}return t}static toStringList(e){const t=Array.isArray(e)?e.flatMap(e=>Xr.toStringList(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereApprovalStatus(e){return this.where("approvalStatus",e)}whereApprovalStatusIn(e){return this.whereInValues("approvalStatus",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}wherePending(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.PENDING)}whereApproved(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.APPROVED)}whereRejected(){return this.whereApprovalStatus(exports.PayoutApprovalStatus.REJECTED)}wherePaid(){return this.whereStatus(exports.PayoutStatus.PAID)}whereFailed(){return this.whereStatus(exports.PayoutStatus.FAILED)}whereAmountBetween(e,t){return e.currencyCode!==t.currencyCode||e.numericValue>t.numericValue?this:this.whereBetween("amount",e.numericValue,t.numericValue)}wherePayee(e){return this.whereContains("payeeName",e)}whereMsisdn(e){return this.whereContains("msisdn",e)}whereMsisdnIn(e){return this.whereInValues("msisdn",e)}whereProfileId(e){return this.where("profileId",e)}whereCreatedById(e){return this.where("createdById",e)}whereCreatedByIdIn(e){return this.whereInValues("createdById",e)}whereActionedById(e){return this.where("actionedById",e)}whereActionedByIdIn(e){return this.whereInValues("actionedById",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){if((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.approvalStatusIn?.length?this.whereApprovalStatusIn(e.approvalStatusIn):e.approvalStatus&&this.whereApprovalStatus(e.approvalStatus),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.payeeName&&this.wherePayee(e.payeeName),e.msisdnIn?.length?this.whereMsisdnIn(e.msisdnIn):e.msisdn&&this.whereMsisdn(e.msisdn),e.profileId&&this.whereProfileId(e.profileId),e.createdByIdIn?.length?this.whereCreatedByIdIn(e.createdByIdIn):e.createdById&&this.whereCreatedById(e.createdById),e.actionedByIdIn?.length?this.whereActionedByIdIn(e.actionedByIdIn):e.actionedById&&this.whereActionedById(e.actionedById),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.id&&this.where("id",e.id),void 0!==e.minAmount||void 0!==e.maxAmount){const t=void 0!==e.minAmount&&null!==e.minAmount,a=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:n}=e,s=n||"TZS";if(!r.CurrencyHelpers.isCode(s))return console.warn("Amount filter requires a valid currency code"),this;if(t&&a){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=r.Amount.from(e.minAmount,s),a=r.Amount.from(e.maxAmount,s);t&&a&&this.whereAmountBetween(t,a)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):a&&this.whereLessThanOrEqual("amount",e.maxAmount)}return e.search&&this.whereSearch(e.search),e.relations?.length&&this.with(e.relations),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,payeeName:e.payeeName,msisdn:e.msisdn,msisdnIn:e.msisdnIn,profileId:e.profileId,createdById:e.createdById,createdByIdIn:e.createdByIdIn,actionedById:e.actionedById,actionedByIdIn:e.actionedByIdIn,id:e.id,partnerReference:e.partnerReference,channel:e.channel,channelIn:e.channelIn,status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),approvalStatus:this.isValidApprovalStatus(e.approvalStatus)?e.approvalStatus:void 0,approvalStatusIn:this.getValidApprovalStatuses(e.approvalStatusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search,relations:this.options.includes?.length?[...this.options.includes]:void 0}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&("relations"===e&&Array.isArray(r)?r.length>0&&(t.eager=`[${r.join(",")}]`):Array.isArray(r)?r.length>0&&(t[e]=r.join(",")):t[e]=String(r))}),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}withStatusIn(e){const t=this.clone();return e?.length&&t.whereStatusIn(e),t}withApprovalStatus(e){const t=this.clone();return e&&t.whereApprovalStatus(e),t}withApprovalStatusIn(e){const t=this.clone();return e?.length&&t.whereApprovalStatusIn(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}withChannelIn(e){const t=this.clone();return e?.length&&t.whereChannelIn(e),t}withMsisdnIn(e){const t=this.clone();return e?.length&&t.whereMsisdnIn(e),t}withCreatedById(e){const t=this.clone();return e&&t.whereCreatedById(e),t}withCreatedByIdIn(e){const t=this.clone();return e?.length&&t.whereCreatedByIdIn(e),t}withActionedById(e){const t=this.clone();return e&&t.whereActionedById(e),t}withActionedByIdIn(e){const t=this.clone();return e?.length&&t.whereActionedByIdIn(e),t}includeDefaultRelations(){return this.with(["createdBy","actionedBy"])}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.payeeName||e.msisdn||e.msisdnIn?.length||e.profileId||e.createdById||e.createdByIdIn?.length||e.actionedById||e.actionedByIdIn?.length||e.id||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.approvalStatus||e.approvalStatusIn?.length||e.minAmount||e.maxAmount||e.search)}describeFilters(e){const t=[],a=this.toFilters(),n=e?.formatDate??(e=>e);if(a.sortBy){const e="asc"===a.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(a.sortBy)} (${e})`})}if(a.startDate&&a.endDate?t.push({label:"Date Range",value:`${n(a.startDate)} — ${n(a.endDate)}`}):a.startDate?t.push({label:"From",value:n(a.startDate)}):a.endDate&&t.push({label:"Until",value:n(a.endDate)}),a.statusIn?.length?t.push({label:"Status",value:a.statusIn.join(", ")}):a.status&&t.push({label:"Status",value:a.status}),a.approvalStatusIn?.length?t.push({label:"Approval Status",value:a.approvalStatusIn.join(", ")}):a.approvalStatus&&t.push({label:"Approval Status",value:a.approvalStatus}),a.channelIn?.length?t.push({label:"Channel",value:a.channelIn.join(", ")}):a.channel&&t.push({label:"Channel",value:a.channel}),void 0!==a.minAmount&&void 0!==a.maxAmount){const e=Number(a.minAmount),n=Number(a.maxAmount);if(Number.isFinite(e)&&Number.isFinite(n)){const a=r.Amount.from(e,"TZS"),s=r.Amount.from(n,"TZS");a&&s&&t.push({label:"Amount Range",value:`${a.label} — ${s.label}`})}}else if(void 0!==a.minAmount){const e=Number(a.minAmount);if(Number.isFinite(e)){const a=r.Amount.from(e,"TZS");a&&t.push({label:"Minimum Amount",value:a.label})}}else if(void 0!==a.maxAmount){const e=Number(a.maxAmount);if(Number.isFinite(e)){const a=r.Amount.from(e,"TZS");a&&t.push({label:"Maximum Amount",value:a.label})}}return a.search&&t.push({label:"Search",value:`"${a.search}"`}),a.payeeName&&t.push({label:"Beneficiary Name",value:a.payeeName}),a.msisdnIn?.length?t.push({label:"MSISDN",value:a.msisdnIn.join(", ")}):a.msisdn&&t.push({label:"MSISDN",value:a.msisdn}),a.profileId&&t.push({label:"Profile",value:a.profileId}),a.createdByIdIn?.length?t.push({label:"Created By ID",value:a.createdByIdIn.join(", ")}):a.createdById&&t.push({label:"Created By ID",value:a.createdById}),a.actionedByIdIn?.length?t.push({label:"Actioned By ID",value:a.actionedByIdIn.join(", ")}):a.actionedById&&t.push({label:"Actioned By ID",value:a.actionedById}),a.partnerReference&&t.push({label:"Reference",value:a.partnerReference}),t}describeFiltersAsText(){return this.describeFilters().map(e=>`${e.label}: ${e.value}`)}formatSortField(e){return{createdAt:"Date Created",updatedAt:"Date Updated",amount:"Amount",payeeName:"Beneficiary Name",approvalStatus:"Approval Status",status:"Status",channel:"Channel",msisdn:"MSISDN",createdById:"Created By ID",actionedById:"Actioned By ID"}[e]??e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=Xr.toStringList(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"payeeName":case"msisdn":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}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}whereInValues(e,t){const r=Xr.toStringList(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Xr.toStringList(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidApprovalStatuses(e){const t=Xr.toStringList(e).filter(e=>this.isValidApprovalStatus(e));return t.length>0?t:void 0}isValidStatus(e){return Object.values(exports.PayoutStatus).includes(e)}isValidApprovalStatus(e){return Object.values(exports.PayoutApprovalStatus).includes(e)}}const ea=wt().router({getPayouts:{method:"GET",path:"",query:t.z.object({}),responses:{200:t.z.object({results:t.z.array(Hr.PayoutDTO),total:t.z.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:t.z.object({rangeStart:t.z.number(),rangeEnd:t.z.number(),eager:t.z.string(),approvalStatus:Hr.PayoutApprovalStatus,orderByDesc:t.z.string()}),responses:{200:t.z.object({results:t.z.array(Hr.PayoutDTO),total:t.z.number()})}},postPayout:{method:"POST",path:"",body:Hr.PayoutInputDTO,responses:{201:Hr.PayoutDTO,400:Bt.schema}},approve:{method:"POST",path:"/:id/approve",body:t.z.object({action:t.z.enum(["Approve","Reject"]),notes:t.z.string().optional()}),responses:{201:Hr.PayoutDTO,400:Bt.schema,401:Bt.schema,404:t.z.object({}),409:t.z.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Hr.PayoutDTO,404:t.z.object({})}}}),ta="MOBILE TRANSFER ",ra="PAYOUT",aa="PAYOUT TO BANK",na="TO_BANK",sa="PAYOUT TO MOBILE",ia="TO_MOMO",oa=i.default.object({text:i.default.string(),_version:i.default.string().optional().default("2.0")});class ca{text;constructor(e){this.text=e}get mediumText(){return this.text.length>50?this.text.substring(0,47)+"...":this.text}get shortText(){return this.text.length>35?this.text.substring(0,32)+"...":this.text}static generateDefaultPayoutNarration(e){return Or.is(e)?ca.generateMobilePayoutNarrationV2(e):Cr.is(e)?ca.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${ra.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:a}=e;return`${ra.toUpperCase()} ${t.bic.trim()} ${a.trim()} ${r.trim()}`.toUpperCase()}getBeneficiaryDetails=()=>{const e=this.getBankBeneficiaryDetails(),t=this.getMobileBeneficiaryDetails();return e||(t||void 0)};getBankBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(ta)&&(e=e.substring(16));try{if(e.startsWith(ra)){const t=e.replace(ra,"").trim().split(" ");if(t.length>=3){const e=t[0],a=t[1],n=t.slice(2).map(da).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=r.BankHelpers.getCountryFromSwiftCode(e);if(t){if(r.BankHelpers.validateSwiftCode(e,t)){const s=r.Bank.fromBIC(e,t);if(a&&n&&s)return new Cr(n,s,a)}}}}}if(e.startsWith(na)){const t=e.split("=>")[1].trim(),a=JSON.parse(t),n=a.account_number,s=a.account_name,i=a.swift_code,o=r.BankHelpers.getCountryFromSwiftCode(i);if(!o)return;if(!r.BankHelpers.validateSwiftCode(i,o))return;const c=r.Bank.fromBIC(i,o);if(n&&s&&c)return new Cr(s,c,n)}if(e.startsWith(aa)){const t=e.replace(aa,"").trim().split(" "),a=r.BankRegistry.getInstance().searchBanks("TZ",t[0]),n=a.length>0?a[0]:void 0,s=t[1],i=t.slice(2).map(da).join(" ");if(i&&s&&n)return new Cr(i,n,s)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(ta)&&(e=e.substring(16));try{if(e.startsWith(ra)){const t=e.replace(ra,"").trim().split(" ");if(t.length>=2){const e=t[0],a=t.slice(1).map(da).join(" ");if(e.startsWith("+")){const t=r.PhoneNumber.from(e);if(t&&a)return new Or(a,t)}}}if(e.startsWith(ia)){const t=e.split("=>")[1].trim(),a=JSON.parse(t),n=r.PhoneNumber.from(a.phone_number,{defaultCountry:"TZ"});let s=a.username;void 0===s&&(s="");let i=s.split(" ");if(i=i.filter(e=>e.trim().length>0),s=i.map(da).join(" "),n&&s)return new Or(s,n)}if(e.startsWith(sa)){const t=e.replace(sa,"").trim().split(" "),a=r.PhoneNumber.from(t[0],{defaultCountry:"TZ"}),n=t.slice(1).map(da).join(" ");if(a&&n)return new Or(n,a)}}catch(e){return}};static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return"string"==typeof t.text&&"function"==typeof t.getBeneficiaryDetails&&"function"==typeof t.toJson}catch(e){return!1}}toJSON(){return{text:this.text,_version:"2.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=oa.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const a=r.data;return new ca(a.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return oa.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return ca.fromJSON(e)}}function da(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const ua=["TZ","KE"],la={TZ:exports.PayoutChannel.TZ_BANK_B2C,KE:exports.PayoutChannel.KE_BANK_B2C},pa={TIGO:exports.PayoutChannel.TZ_TIGO_B2C,VODACOM:exports.PayoutChannel.TZ_TIGO_B2C,AIRTEL:exports.PayoutChannel.TZ_AIRTEL_B2C,HALOTEL:exports.PayoutChannel.TZ_HALOTEL_B2C},ha="Invalid bank beneficiary info",ma="Invalid phone number",fa="The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",ya="Wallet country does not match beneficiary country",ga="Wallet currency does not match payout amount currency",va="Payout amount currency does not match the payout country currency",_a="Only TZ and KE bank payout channels are supported for now",ba="Only TZ and KE mobile money payout channels are supported for now",Na="Mobile money provider is not supported for payouts in this country",wa=e=>ua.includes(e);class Ia{static processNotes(e){if(!e)return;const t=e.trim();return t.length>0?t:void 0}static isPhoneEligibleForPayout(e){const t=e.getNumberType();return t===r.PhoneNumberType.MOBILE||t===r.PhoneNumberType.FIXED_LINE_OR_MOBILE}}class Sa{static resolve(e){const{wallet:t,receiver:r,amount:a}=e;return Sa.assertCompatibleWalletReceiverAndAmount(t,r,a),Or.is(r)?Sa.forMobile(r.phoneNumber,r.mnoId,t):Sa.forBank(r,t)}static forBank(e,t){if(!Cr.is(e))throw new Error(ha);if(!wa(t.countryCode))throw new Error(_a);if(t.countryCode!==e.countryCode)throw new Error(ya);return la[t.countryCode]}static forMobile(e,t,a){if(!r.PhoneNumber.is(e))throw new Error(ma);if(!wa(a.countryCode)||!wa(e.countryCode))throw new Error(ba);if(a.countryCode!==e.countryCode)throw new Error(ya);if(!Ia.isPhoneEligibleForPayout(e))throw new Error(fa);if("KE"===a.countryCode)return exports.PayoutChannel.KE_SAFARICOM_B2C;const n=r.MobileMoneyProviderHelpers.findById(t,e.countryCode);if(!n||!n.supportsDirection(r.TransactionDirection.PAYOUT))throw new Error(Na);const s=pa[n.id];if(!s)throw new Error(Na);return s}static getChannelType(e){return Sa.isBankChannel(e)?r.ChannelType.BANK:r.ChannelType.MOBILE_MONEY}static getCountryCode(e){return e.slice(0,2)}static getProviderId(e){if(!Sa.isBankChannel(e))return e.split("-")[1]}static isBankChannel(e){return e.endsWith("-BANK-B2C")}static isMobileMoneyChannel(e){return!Sa.isBankChannel(e)}static assertCompatibleWalletReceiverAndAmount(e,t,a){if(e.countryCode!==t.countryCode)throw new Error(ya);if(e.currencyCode!==a.currencyCode)throw new Error(ga);const n=r.Country.fromCode(e.countryCode)?.currencyCode;if(n&&a.currencyCode!==n)throw new Error(va)}}class Aa{getPayoutInput(e,t){const r=Sa.resolve({...e,wallet:t});if(Or.is(e.receiver))return this.createMobileInput(e.receiver,e.amount,r,e.notes);if(Cr.is(e.receiver))return this.createBankInput(e.receiver,e.amount,r,e.notes);throw new Error("Cannot create payout input for unknown beneficiary info")}createMobileInput(e,t,a,n){const s=Ia.processNotes(n);return{channel:a,msisdn:e.phoneNumber.getWithFormat(r.PhoneNumberFormat.INTERNATIONAL_NUMERIC),description:s??ca.generateDefaultPayoutNarration(e),payeeName:e.name,notes:s,amount:t.numericValue}}createBankInput(e,t,r,a){const n=Ia.processNotes(a);return{channel:r,msisdn:`${e.bank.bic}:${e.accNo}`,description:n??ca.generateDefaultPayoutNarration(e),payeeName:e.accName,notes:n,amount:t.numericValue}}}const Oa={bank:Sa.forBank.bind(Sa),mobile:Sa.forMobile.bind(Sa)};const Ca=wt().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:Yt.schema}}});const xa=e=>e.optional().transform(e=>e??void 0),Pa={walletDTO:t.z.object({id:t.z.string().min(1,{message:"Wallet ID is required."}),profileId:t.z.string().min(1,{message:"Profile ID is required."}),accountNo:t.z.string().min(1,{message:"Account number is required."}),accountName:t.z.string().min(1,{message:"Account name is required."}),channel:t.z.string().min(1,{message:"Channel is required."}),countryCode:t.z.string().default("TZ").refine(e=>r.CountryHelpers.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.z.string().default("TZS").refine(e=>r.CurrencyHelpers.isCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:t.z.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:t.z.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:t.z.object({id:t.z.string().optional(),profileId:t.z.string().optional(),accountNo:t.z.string().optional(),accountName:t.z.string().optional(),channel:t.z.string().optional(),countryCode:t.z.string().default("TZ").refine(e=>r.ISO2CountryCodesSet.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:t.z.string().default("TZS").refine(e=>{const t=r.Currency.fromCode(e);return void 0!==t&&r.CurrencyCodesSet.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:t.z.object({accountNo:xa(t.z.string()),debitOrCredit:t.z.string().min(1,"Transaction type is required"),tranRefNo:t.z.string().min(1,"Transaction reference is required"),narration:t.z.string().min(1,"Transaction description is required"),txnDate:t.z.coerce.date({error:()=>({message:"Invalid transaction date format"})}),valueDate:t.z.coerce.date({error:()=>({message:"Invalid value date format"})}),amountCredited:t.z.number().min(0,"Credited amount must be non-negative"),amountDebited:t.z.number().min(0,"Debited amount must be non-negative"),balance:t.z.number(),currencyCode:xa(t.z.string().min(3,"Currency code must be at least 3 characters")).default("TZS")}),plainDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/,{message:"Date must be in YYYY-MM-DD format (no time component)."})},Ta=i.default.object({accountNo:i.default.string().optional(),debitOrCredit:i.default.string(),tranRefNo:i.default.string(),narration:oa,txnDate:i.default.string(),valueDate:i.default.string(),amountCredited:r.AmountJSONSchema,amountDebited:r.AmountJSONSchema,balance:r.AmountJSONSchema,currencyCode:i.default.string(),_version:i.default.string().optional().default("2.0")});class za{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return Pa.statementEntry}constructor(e,t){this._accountNo=e.accountNo,this._debitOrCredit=e.debitOrCredit,this._tranRefNo=e.tranRefNo,this._narration=t,this._txnDate=e.txnDate,this._valueDate=e.valueDate,this._currencyCode=e.currencyCode;const a=r.Currency.fromCode(e.currencyCode);if(!a)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=r.Amount.from(e.amountCredited,a.code),s=r.Amount.from(e.amountDebited,a.code),i=r.Amount.from(e.balance,a.code);if(!n||!s||!i)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=s,this._balance=i}static create(e){const t="string"==typeof e.narration?new ca(e.narration):e.narration,r={...e,narration:t.text},a=za.schema.safeParse(r);if(a.success)try{const{narration:e,...r}=a.data;return new za(r,t)}catch(e){return void console.error("Failed to create WalletStatementEntry:",e)}else console.error("WalletStatementEntry data validation failed:",a.error.flatten())}get accountNo(){return this._accountNo}get debitOrCredit(){return this._debitOrCredit}get tranRefNo(){return this._tranRefNo}get narration(){return this._narration}get txnDate(){return this._txnDate}get valueDate(){return this._valueDate}get amountCredited(){return this._amountCredited}get amountDebited(){return this._amountDebited}get balance(){return this._balance}get currencyCode(){return this._currencyCode}validate(){const e={accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.text,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode},t=za.schema.safeParse(e);return t.success||console.warn("WalletStatementEntry instance validation failed:",t.error.flatten()),t.success}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;try{return("string"==typeof t._accountNo||void 0===t._accountNo)&&"string"==typeof t._debitOrCredit&&"string"==typeof t._tranRefNo&&ca.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&r.Amount.is(t._amountCredited)&&r.Amount.is(t._amountDebited)&&r.Amount.is(t._balance)&&"string"==typeof t._currencyCode}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return za.create({accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration,txnDate:this._txnDate,valueDate:this._valueDate,amountCredited:this._amountCredited.numericValue,amountDebited:this._amountDebited.numericValue,balance:this._balance.numericValue,currencyCode:this._currencyCode})}toString(){return`WalletStatementEntry(${this._tranRefNo}: ${this._debitOrCredit} ${this._amountCredited.isPositive()?this._amountCredited.label:this._amountDebited.label} on ${this._txnDate.toISOString().split("T")[0]}${this._narration})`}static from(e){if(e&&"object"==typeof e)try{let t,a,n,s,i=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const s=r.Amount.fromJSON(e.amountCredited),o=r.Amount.fromJSON(e.amountDebited),c=r.Amount.fromJSON(e.balance);if(!s||!o||!c)return void console.error("Failed to deserialize Amount objects from JSON");t=s.numericValue,a=o.numericValue,n=c.numericValue,e.currencyCode||(i=s.currencyCode)}else if(t=Number(e.amountCredited),a=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(a)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)s=e.narration;else if(ca.is(e.narration))s=e.narration;else{if(!ca.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=ca.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");s=t}}return za.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:s,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:a,balance:n,currencyCode:i})}catch(e){return void console.error("Error in WalletStatementEntry.from:",e)}else console.error("Invalid data provided to WalletStatementEntry.from: not an object or null.")}toJSON(){return{accountNo:this._accountNo,debitOrCredit:this._debitOrCredit,tranRefNo:this._tranRefNo,narration:this._narration.toJSON(),txnDate:this._txnDate.toISOString(),valueDate:this._valueDate.toISOString(),amountCredited:this._amountCredited.toJSON(),amountDebited:this._amountDebited.toJSON(),balance:this._balance.toJSON(),currencyCode:this._currencyCode,_version:"2.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,a=Ta.safeParse(t);if(!a.success)return void console.error("Invalid WalletStatementEntryJSON:",a.error.flatten());const n=a.data,s=ca.fromJSON(n.narration);if(!s)return void console.warn("Failed to deserialize narration");const i=r.Amount.fromJSON(n.amountCredited),o=r.Amount.fromJSON(n.amountDebited),c=r.Amount.fromJSON(n.balance);return i&&o&&c?i.currencyCode!==n.currencyCode||o.currencyCode!==n.currencyCode||c.currencyCode!==n.currencyCode?void console.warn("Currency code mismatch"):za.create({accountNo:n.accountNo,debitOrCredit:n.debitOrCredit,tranRefNo:n.tranRefNo,narration:s,txnDate:n.txnDate,valueDate:n.valueDate,amountCredited:i.numericValue,amountDebited:o.numericValue,balance:c.numericValue,currencyCode:n.currencyCode}):void console.warn("Failed to deserialize Amount objects")}catch(e){return void console.error("Error parsing WalletStatementEntryJSON:",e)}}static isWalletStatementEntryJSON(e){return Ta.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>za.fromJSON(e)).filter(e=>void 0!==e):(console.warn("fromJSONArray expects an array"),[])}catch(e){return console.error("Error parsing WalletStatementEntry JSON array:",e),[]}}static toJSONArray(e){return e.map(e=>e.toJSON())}toJson(){return this.toJSON()}static fromJson(e){return za.fromJSON(e)}static fromJsonArray(e){return za.fromJSONArray(e)}static toJsonArray(e){return za.toJSONArray(e)}}const Ea=i.default.object({id:i.default.string(),profileId:i.default.string(),accountNo:i.default.string(),accountName:i.default.string(),channel:i.default.string(),countryCode:i.default.string(),currencyCode:i.default.string(),createdAt:i.default.string(),updatedAt:i.default.string(),_version:i.default.string().optional().default("1.0")});class Ba{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return Pa.walletDTO}constructor(e){this._id=e.id,this._profileId=e.profileId,this._accountNo=e.accountNo,this._accountName=e.accountName,this._channel=e.channel,this._countryCode=e.countryCode,this._currencyCode=e.currencyCode,this._createdAt=e.createdAt,this._updatedAt=e.updatedAt}static create(e){const t=Ba.schema.safeParse(e);if(t.success)return new Ba(t.data);console.error("Wallet data validation failed:",t.error.flatten())}get id(){return this._id}get profileId(){return this._profileId}get accountNo(){return this._accountNo}get accountName(){return this._accountName}get channel(){return this._channel}get countryCode(){return this._countryCode}get currencyCode(){return this._currencyCode}get createdAt(){return this._createdAt}get updatedAt(){return this._updatedAt}get createdAtDate(){return new Date(this._createdAt)}get updatedAtDate(){return new Date(this._updatedAt)}validate(){const e=Ba.schema.safeParse(this.toJSON());return e.success||console.warn("Wallet instance validation failed:",e.error.flatten()),e.success}static from(e){if(e&&"object"==typeof e)return Ba.create({id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt,currencyCode:e.currencyCode});console.error("Invalid data provided to Wallet.from: Input must be an object.")}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t._id&&"string"==typeof t._profileId&&"string"==typeof t._accountNo&&"string"==typeof t._accountName&&"string"==typeof t._channel&&"string"==typeof t._countryCode&&r.CountryHelpers.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&r.CurrencyHelpers.isCode(t._currencyCode)&&"string"==typeof t._createdAt&&"string"==typeof t._updatedAt}toJSON(){return{id:this._id,profileId:this._profileId,accountNo:this._accountNo,accountName:this._accountName,channel:this._channel,countryCode:this._countryCode,currencyCode:this._currencyCode,createdAt:this._createdAt,updatedAt:this._updatedAt,_version:"1.0"}}toJSONString(){return JSON.stringify(this.toJSON())}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Ea.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const a=r.data;return Ba.create(a)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return Ea.safeParse(e).success}}const ka=wt().router({getWallets:{method:"GET",path:"/",query:Pa.walletQuery,responses:{200:t.z.array(Ba.schema)}},getBalance:{method:"POST",path:"/balance",body:t.z.object({accountNo:t.z.string().optional()}),responses:{201:t.z.object({availableBalance:t.z.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:t.z.object({endDate:Pa.plainDate,startDate:Pa.plainDate,accountNo:t.z.string().optional()}),responses:{201:t.z.array(za.schema)}}});class Da extends Ut{static create(){return new Da}static fromFilters(e){return(new Da).applyFilters(e)}static fromUrlParams(e){try{const t=Pa.walletQuery.parse(e);return Da.fromFilters(t)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){const t=Object.fromEntries(e.entries());return Da.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Da.fromSearchParams(t)}static from(e){try{return null==e?new Da:Ut.is(e)?new Da(e.options):e instanceof URLSearchParams?Da.fromSearchParams(e):Da.isStringRecord(e)?Da.fromUrlParams(e):Da.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a WalletQuery instance.")}}static isStringRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e)}whereId(e){return this.where("id",e)}whereProfileId(e){return this.where("profileId",e)}whereAccountNo(e){return this.where("accountNo",e)}whereAccountName(e){return this.whereContains("accountName",e)}whereChannel(e){return this.where("channel",e)}whereCountryCode(e){return this.where("countryCode",e)}whereCurrencyCode(e){return this.where("currencyCode",e)}applyFilters(e){return e.id&&this.whereId(e.id),e.profileId&&this.whereProfileId(e.profileId),e.accountNo&&this.whereAccountNo(e.accountNo),e.accountName&&this.whereAccountName(e.accountName),e.channel&&this.whereChannel(e.channel),e.countryCode&&this.whereCountryCode(e.countryCode),e.currencyCode&&this.whereCurrencyCode(e.currencyCode),this}toFilters(){const e=this.extractFilterValues();return{id:e.id,profileId:e.profileId,accountNo:e.accountNo,accountName:e.accountName,channel:e.channel,countryCode:e.countryCode,currencyCode:e.currencyCode}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withId(e){const t=this.clone();return t.whereId(e),t}withProfileId(e){const t=this.clone();return t.whereProfileId(e),t}withAccountNo(e){const t=this.clone();return t.whereAccountNo(e),t}withCountryCode(e){const t=this.clone();return t.whereCountryCode(e),t}withCurrencyCode(e){const t=this.clone();return t.whereCurrencyCode(e),t}hasFilters(){const e=this.toFilters();return!!(e.id||e.profileId||e.accountNo||e.accountName||e.channel||e.countryCode||e.currencyCode)}getActiveFilters(){const e=[],t=this.toFilters();return t.id&&e.push(`ID: ${t.id}`),t.profileId&&e.push(`Profile: ${t.profileId}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.accountName&&e.push(`Name: ${t.accountName}`),t.channel&&e.push(`Channel: ${t.channel}`),t.countryCode&&e.push(`Country: ${t.countryCode}`),t.currencyCode&&e.push(`Currency: ${t.currencyCode}`),e}build(){return super.build()}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters)"eq"===t.operator?e[t.field]=t.value:"likeLower"===t.operator&&"string"==typeof t.value&&(e[t.field]=t.value.replace(/%/g,""));return e}}const Ra="Africa/Nairobi";function ja(e,t){const[r,a,n]=e.split("-").map(Number),s=Date.UTC(r,a-1,n,12)+864e5*t,i=new Date(s);return`${String(i.getUTCFullYear()).padStart(4,"0")}-${String(i.getUTCMonth()+1).padStart(2,"0")}-${String(i.getUTCDate()).padStart(2,"0")}`}function Ma(e){return{startDate:ja(e.startDate,-1),endDate:ja(e.endDate,1)}}function Ja(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}function Za(e){return!e||e===Ra}const La={getUniqueCountries(e){const t=new Set;return e.forEach(e=>{e.countryCode&&t.add(e.countryCode)}),Array.from(t)},getWalletsByCountry:(e,t)=>e.filter(e=>e.countryCode===t)};exports.APIError=Bt,exports.AuthDTOSchemas=Wt,exports.AuthRepository=class extends Dt{constructor(e){super("auth",fr,e)}async logIn(e,t){const r={type:"password",identity:e,password:t},a=await this.client.logIn({body:r});if(400===a.status)throw new Bt({message:"Invalid email or password",statusCode:400});if(201===a.status){const e=a.body.token,t=new ir({token:e}),r=await t.getIdentity(),n=Gt.from(r);if(!n)throw new Bt({message:"Failed to construct login credentials",statusCode:502});const s=a.body.profile,i=Yt.from(s);if(!i)throw new Bt({message:"Failed to construct user profile",statusCode:502});let o;if(n.can(Rt.Role.ViewRole))try{const t=new mr({token:e});o=await t.getRole(n.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const c=nr.from({logIn:n,companyProfile:i,role:o});if(!c)throw new Bt({message:"Failed to construct user session",statusCode:502});return{token:e,user:c}}throw new Bt({message:"An error occurred while trying to log in",statusCode:502})}async updatePassword(e,t){const r=await this.client.resetPassword({body:{currentPassword:e,newPassword:t}});if(200===r.status)return!0;if(400===r.status)throw new Bt({message:"Invalid current password",statusCode:400});throw new Bt({message:"An error occurred while trying to update password",statusCode:502})}async getAccessList(){const e=await this.client.access();if(200===e.status)return e.body;throw new Error(`Failed to get access list. Status: ${e.status}`)}},exports.BANK_NARR_PREFIX=aa,exports.BankBeneficiaryInfo=Cr,exports.BankBeneficiaryJSONSchema=wr,exports.BaseRepository=Dt,exports.Beneficiary=zr,exports.BeneficiaryDTOSchemas=_r,exports.BeneficiaryError=Sr,exports.BeneficiaryInfo=Pr,exports.BeneficiaryInfoFactory=xr,exports.BeneficiaryInfoJSONSchema=Ir,exports.BeneficiaryJSONSchema=Tr,exports.BeneficiaryRepository=class extends Dt{constructor(e){super("contact",br,e)}async create(e){const t=(new kr).resolve(e),r=await this.client.createBeneficiary({body:t}),a=this.handleResponse(r,201);return zr.create(a)}async edit(e,t){const r=(new kr).resolve(t),a=await this.client.editBeneficiary({params:{id:e},body:r}),n=this.handleResponse(a,200);return zr.create(n)}async remove(e){const t=await this.client.deleteBeneficiary({params:{id:e},body:{}});this.handleResponse(t,200)}async getAll(){const e=await this.client.getBeneficiaries({query:{orderByDesc:"createdAt"}}),t=this.handleResponse(e,200);return zr.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return zr.create(r)}},exports.CompanyMembership=rr,exports.CompanyMembershipJSONSchema=tr,exports.EAT_TIMEZONE=Ra,exports.ECOBANK_PREFIX=ta,exports.IdentityRepository=ir,exports.LEGACY_BANK_NARR_PREFIX=na,exports.LEGACY_MOBILE_NARR_PREFIX=ia,exports.LogIn=Gt,exports.LogInJSONSchema=Ht,exports.LogInSchemas=Kt,exports.MOBILE_NARR_PREFIX=sa,exports.MobileBeneficiaryInfo=Or,exports.MobileBeneficiaryJSONSchema=Nr,exports.NARR_V2_PREFIX=ra,exports.Narration=ca,exports.NarrationJSONSchema=oa,exports.Pagination=Mt,exports.PaginationParamsSchema=Jt,exports.PaginationSchema=Zt,exports.Payout=Qr,exports.PayoutChannelResolver=Sa,exports.PayoutDTOSchemas=Hr,exports.PayoutInputFactory=Aa,exports.PayoutJSONSchema=Gr,exports.PayoutQuery=Xr,exports.PayoutRepository=class extends Dt{constructor(e){super("payout",ea,e)}async getPayouts(e){try{const t=Xr.from(e),r=t.build(),a=await this.client.getPayouts({query:r}),n=this.handleResponse(a,200),s=t.toFilters(),i=new Mt(s.page??1,s.limit??10,n.total);return{results:Qr.createMany(n.results),pagination:i}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=Xr.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),a=this.handleResponse(r,200);return Qr.createMany(a)}catch(e){throw console.log("error: ",e),new Error(`Failed to fetch all payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Xr.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,receiver:a,amount:n,notes:s}=e,i=Sa.resolve({wallet:t,receiver:a,amount:n}),o=r.TemboCoverage.getTransactionLimits({countryCode:t.countryCode,currencyCode:n.currencyCode,direction:r.TransactionDirection.PAYOUT,channelType:Sa.getChannelType(i)});if(!o)throw new Bt({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${n.currencyCode} ${i} payouts`});const{min:c,max:d}=o;if(n.lessThan(c)||n.greaterThan(d))throw new Bt({statusCode:400,message:`Please make sure the amount is between ${c.label} - ${d.label}`});const u=(new Aa).getPayoutInput({receiver:a,amount:n,notes:s},t),l=await this.client.postPayout({body:u});if(201===l.status)return Qr.create(l.body);if(400===l.status)throw new Bt(l.body);throw Bt.unknown()}async approve(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Approve",notes:e.notes}});if(201===t.status)return Qr.create(t.body);if(401===t.status)throw new Bt({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new Bt({message:"Payout not found",statusCode:404});if(409===t.status)throw new Bt({message:"Payout already approved",statusCode:409});throw Bt.unknown()}async reject(e){const t=await this.client.approve({params:{id:e.id},body:{action:"Reject",notes:e.notes}});if(201===t.status)return Qr.create(t.body);if(401===t.status)throw new Bt({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new Bt({message:"Payout not found",statusCode:404});if(409===t.status)throw new Bt({message:"Payout already rejected",statusCode:409});throw Bt.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return Qr.create(t.body);if(404===t.status)throw new Bt({message:"Payout not found",statusCode:404});throw Bt.unknown()}async count(e){const t=Xr.from(e).build(),r=await this.client.getPayouts({query:t});return this.handleResponse(r,200).total}async exists(e){return await this.count(e)>0}},exports.PermissionError=jt,exports.Permissions=Rt,exports.Profile=Yt,exports.ProfileDTOSchemas=Vt,exports.ProfileJSONSchema=Qt,exports.ProfileRepository=class extends Dt{constructor(e){super("profile",Ca,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=Yt.from(e.body);if(t)return t;throw new Error("Invalid profile data received from server")}throw new Error(`Failed to get current profile. Status: ${e.status}`)}},exports.QUERY_BUILDER_TYPE=$t,exports.QueryBuilder=Ut,exports.Role=er,exports.RoleJSONSchema=Xt,exports.TeamManagementDTOSchemas=ur,exports.TeamMember=hr,exports.TeamMemberJSONSchema=pr,exports.TeamMemberRepository=mr,exports.User=nr,exports.UserJSONSchema=ar,exports.ValidatedBeneficiaryInputFactory=kr,exports.Wallet=Ba,exports.WalletDTOSchemas=Pa,exports.WalletJSONSchema=Ea,exports.WalletRepository=class extends Dt{constructor(e){super("wallet",ka,e)}async getBalance(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");if(e.wallet){const t=await this.client.getBalance({body:{accountNo:e.wallet.accountNo}});if(201===t.status){const a=t.body.availableBalance,n=r.Amount.from(a,e.wallet.currencyCode);if(n)return n}}if(e.accountNo){const t=await this.getWallets({accountNo:e.accountNo});if(0===t.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);const a=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=r.Amount.from(e,a.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=Da.from(e).build(),r=await this.client.getWallets({query:t});if(200===r.status){const e=r.body;try{return e.map(e=>{const t=Ba.from(e);if(!t)throw new Error(`Invalid wallet data: ${JSON.stringify(e)}`);return t})}catch(e){throw console.error("[WalletRepository] Error processing wallet data:",e),new Error("Failed to process wallet data from API")}}throw new Error(`Failed to fetch wallets. Status: ${r.status}`)}async getByID(e){const t=Da.create().whereId(e),r=await this.getWallets(t);return r.length>0?r[0]:void 0}async getStatement(e){if(!e.wallet&&!e.accountNo)throw new Error("Either wallet or accountNo must be provided");let t,r;if(e.wallet)t=e.wallet,r=e.wallet.accountNo;else{if(!e.accountNo)throw new Error("Either wallet or accountNo must be provided");{const a=await this.getWallets({accountNo:e.accountNo});if(0===a.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);t=a[0],r=e.accountNo}}const a=!Za(e.timezone),n={...a?Ma(e.range):e.range,accountNo:r},s=await this.client.getStatement({body:n});if(201===s.status){const r=s.body.map(e=>({...e,currencyCode:t.currencyCode})).reduce((e,t)=>{const r=za.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[]);if(!a)return r;const n=e.timezone,{startDate:i,endDate:o}=e.range;return r.filter(e=>{const t=Ja(e.valueDate,n);return t>=i&&t<=o})}throw console.warn("[WalletRepository] Failed to fetch statement:",s),new Error(`Failed to fetch statement. Status: ${s.status}`)}async exists(e){return(await this.getWallets(e)).length>0}async count(e){return(await this.getWallets(e)).length}},exports.WalletStatementEntry=za,exports.WalletStatementEntryJSONSchema=Ta,exports.WalletUtils=La,exports.contract=br,exports.createPaginatedResponse=function(e,t,r,a){return{results:e,pagination:new Mt(t,r,a)}},exports.createPaginatedResponseSchema=function(e){return t.z.object({results:t.z.array(e),pagination:Zt})},exports.createPayoutChannelCode=Oa,exports.emptyPaginatedResponse=function(e=1,t=10){return{results:[],pagination:new Mt(e,t,0)}},exports.isEatTimezone=Za,exports.isError=function(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message},exports.localDateInZone=Ja,exports.padEatRange=Ma,exports.setGlobalTokenGetter=e=>{kt=e},exports.shiftPlainDate=ja,exports.toPlainDate=function(e){return`${String(e.getFullYear()).padStart(4,"0")}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|