@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.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -207
  3. package/dist/index.cjs.js +1 -1
  4. package/dist/index.cjs.js.map +1 -1
  5. package/dist/index.d.ts +5 -4
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.esm.js +1 -1
  8. package/dist/index.esm.js.map +1 -1
  9. package/dist/lib/api/base-repository.d.ts +2 -2
  10. package/dist/lib/api/base-repository.d.ts.map +1 -0
  11. package/dist/lib/api/index.d.ts +1 -0
  12. package/dist/lib/api/index.d.ts.map +1 -0
  13. package/dist/lib/error/error.api.d.ts +3 -2
  14. package/dist/lib/error/error.api.d.ts.map +1 -0
  15. package/dist/lib/error/error.permission.d.ts +2 -1
  16. package/dist/lib/error/error.permission.d.ts.map +1 -0
  17. package/dist/lib/error/error.utils.d.ts +1 -0
  18. package/dist/lib/error/error.utils.d.ts.map +1 -0
  19. package/dist/lib/error/index.d.ts +1 -0
  20. package/dist/lib/error/index.d.ts.map +1 -0
  21. package/dist/lib/query/index.d.ts +3 -2
  22. package/dist/lib/query/index.d.ts.map +1 -0
  23. package/dist/lib/query/pagination/pagination.d.ts +1 -0
  24. package/dist/lib/query/pagination/pagination.d.ts.map +1 -0
  25. package/dist/lib/query/pagination/pagination.schemas.d.ts +8 -61
  26. package/dist/lib/query/pagination/pagination.schemas.d.ts.map +1 -0
  27. package/dist/lib/query/query.builder.d.ts +10 -3
  28. package/dist/lib/query/query.builder.d.ts.map +1 -0
  29. package/dist/lib/query/query.types.d.ts +1 -0
  30. package/dist/lib/query/query.types.d.ts.map +1 -0
  31. package/dist/modules/auth/auth.contract.d.ts +10 -69
  32. package/dist/modules/auth/auth.contract.d.ts.map +1 -0
  33. package/dist/modules/auth/auth.dtos.d.ts +8 -67
  34. package/dist/modules/auth/auth.dtos.d.ts.map +1 -0
  35. package/dist/modules/auth/auth.repository.d.ts +1 -0
  36. package/dist/modules/auth/auth.repository.d.ts.map +1 -0
  37. package/dist/modules/auth/company-membership.model.d.ts +7 -86
  38. package/dist/modules/auth/company-membership.model.d.ts.map +1 -0
  39. package/dist/modules/auth/index.d.ts +3 -2
  40. package/dist/modules/auth/index.d.ts.map +1 -0
  41. package/dist/modules/auth/user.model.d.ts +26 -163
  42. package/dist/modules/auth/user.model.d.ts.map +1 -0
  43. package/dist/modules/beneficiary/beneficiary-info.model.d.ts +30 -67
  44. package/dist/modules/beneficiary/beneficiary-info.model.d.ts.map +1 -0
  45. package/dist/modules/beneficiary/beneficiary-input-handler.d.ts +3 -2
  46. package/dist/modules/beneficiary/beneficiary-input-handler.d.ts.map +1 -0
  47. package/dist/modules/beneficiary/beneficiary.api-contract.d.ts +16 -115
  48. package/dist/modules/beneficiary/beneficiary.api-contract.d.ts.map +1 -0
  49. package/dist/modules/beneficiary/beneficiary.dtos.d.ts +6 -34
  50. package/dist/modules/beneficiary/beneficiary.dtos.d.ts.map +1 -0
  51. package/dist/modules/beneficiary/beneficiary.model.d.ts +5 -27
  52. package/dist/modules/beneficiary/beneficiary.model.d.ts.map +1 -0
  53. package/dist/modules/beneficiary/beneficiary.repository.d.ts +2 -1
  54. package/dist/modules/beneficiary/beneficiary.repository.d.ts.map +1 -0
  55. package/dist/modules/beneficiary/index.d.ts +5 -4
  56. package/dist/modules/beneficiary/index.d.ts.map +1 -0
  57. package/dist/modules/login/index.d.ts +1 -0
  58. package/dist/modules/login/index.d.ts.map +1 -0
  59. package/dist/modules/login/login.api-contract.d.ts +3 -28
  60. package/dist/modules/login/login.api-contract.d.ts.map +1 -0
  61. package/dist/modules/login/login.dtos.d.ts +5 -56
  62. package/dist/modules/login/login.dtos.d.ts.map +1 -0
  63. package/dist/modules/login/login.model.d.ts +7 -34
  64. package/dist/modules/login/login.model.d.ts.map +1 -0
  65. package/dist/modules/login/login.repository.d.ts +2 -1
  66. package/dist/modules/login/login.repository.d.ts.map +1 -0
  67. package/dist/modules/login/permission.type.d.ts +1 -0
  68. package/dist/modules/login/permission.type.d.ts.map +1 -0
  69. package/dist/modules/payout/index.d.ts +3 -2
  70. package/dist/modules/payout/index.d.ts.map +1 -0
  71. package/dist/modules/payout/payout-channel-handler.d.ts +5 -4
  72. package/dist/modules/payout/payout-channel-handler.d.ts.map +1 -0
  73. package/dist/modules/payout/payout.api-contract.d.ts +78 -666
  74. package/dist/modules/payout/payout.api-contract.d.ts.map +1 -0
  75. package/dist/modules/payout/payout.dtos.d.ts +99 -506
  76. package/dist/modules/payout/payout.dtos.d.ts.map +1 -0
  77. package/dist/modules/payout/payout.model.d.ts +8 -85
  78. package/dist/modules/payout/payout.model.d.ts.map +1 -0
  79. package/dist/modules/payout/payout.query.d.ts +3 -2
  80. package/dist/modules/payout/payout.query.d.ts.map +1 -0
  81. package/dist/modules/payout/payout.repository.d.ts +7 -6
  82. package/dist/modules/payout/payout.repository.d.ts.map +1 -0
  83. package/dist/modules/profile/index.d.ts +1 -0
  84. package/dist/modules/profile/index.d.ts.map +1 -0
  85. package/dist/modules/profile/profile.api-contract.d.ts +2 -19
  86. package/dist/modules/profile/profile.api-contract.d.ts.map +1 -0
  87. package/dist/modules/profile/profile.dtos.d.ts +3 -38
  88. package/dist/modules/profile/profile.dtos.d.ts.map +1 -0
  89. package/dist/modules/profile/profile.model.d.ts +5 -42
  90. package/dist/modules/profile/profile.model.d.ts.map +1 -0
  91. package/dist/modules/profile/profile.repository.d.ts +1 -0
  92. package/dist/modules/profile/profile.repository.d.ts.map +1 -0
  93. package/dist/modules/team-member/index.d.ts +3 -2
  94. package/dist/modules/team-member/index.d.ts.map +1 -0
  95. package/dist/modules/team-member/role.model.d.ts +6 -21
  96. package/dist/modules/team-member/role.model.d.ts.map +1 -0
  97. package/dist/modules/team-member/team-member.contract.d.ts +74 -615
  98. package/dist/modules/team-member/team-member.contract.d.ts.map +1 -0
  99. package/dist/modules/team-member/team-member.dtos.d.ts +15 -162
  100. package/dist/modules/team-member/team-member.dtos.d.ts.map +1 -0
  101. package/dist/modules/team-member/team-member.model.d.ts +7 -66
  102. package/dist/modules/team-member/team-member.model.d.ts.map +1 -0
  103. package/dist/modules/team-member/team-member.repository.d.ts +3 -2
  104. package/dist/modules/team-member/team-member.repository.d.ts.map +1 -0
  105. package/dist/modules/wallet/index.d.ts +4 -2
  106. package/dist/modules/wallet/index.d.ts.map +1 -0
  107. package/dist/modules/wallet/narration.model.d.ts +3 -8
  108. package/dist/modules/wallet/narration.model.d.ts.map +1 -0
  109. package/dist/modules/wallet/statement-entry.model.d.ts +14 -131
  110. package/dist/modules/wallet/statement-entry.model.d.ts.map +1 -0
  111. package/dist/modules/wallet/wallet.contract.d.ts +17 -90
  112. package/dist/modules/wallet/wallet.contract.d.ts.map +1 -0
  113. package/dist/modules/wallet/wallet.dtos.d.ts +33 -138
  114. package/dist/modules/wallet/wallet.dtos.d.ts.map +1 -0
  115. package/dist/modules/wallet/wallet.model.d.ts +5 -26
  116. package/dist/modules/wallet/wallet.model.d.ts.map +1 -0
  117. package/dist/modules/wallet/wallet.query.d.ts +2 -1
  118. package/dist/modules/wallet/wallet.query.d.ts.map +1 -0
  119. package/dist/modules/wallet/wallet.repository.d.ts +49 -25
  120. package/dist/modules/wallet/wallet.repository.d.ts.map +1 -0
  121. package/dist/modules/wallet/wallet.timezone.d.ts +87 -0
  122. package/dist/modules/wallet/wallet.timezone.d.ts.map +1 -0
  123. package/dist/modules/wallet/wallet.utils.d.ts +3 -2
  124. package/dist/modules/wallet/wallet.utils.d.ts.map +1 -0
  125. package/package.json +40 -29
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import e,{z as t}from"zod";import{v4 as r}from"uuid";import{MobileMoneyProviderIdSchema as n,E164PhoneNumberFormatSchema as a,ISO2CountryCodeSchema as s,TZBankSWIFTCodeSchema as o,KEBankSWIFTCodeSchema as i,MobileMoneyProviderHelpers as c,PhoneNumber as u,CountryHelpers as d,PhoneNumberFormat as l,BankHelpers as h,Bank as m,CurrencyHelpers as p,Amount as y,BankRegistry as f,TransactionDirection as g,ChannelType as b,Country as N,PhoneNumberType as w,TemboCoverage as v,Currency as I,CurrencyCodesSet as A,ISO2CountryCodesSet as _,AmountJSONSchema as S}from"@temboplus/frontend-core";class O 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 O.schema.safeParse(e).success}static unknown(e){return new O({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.object({message:t.string(),statusCode:t.number().int(),error:t.string().optional(),details:t.object({}).optional()})}}const C={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 P 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.union([t.enum(Object.values(C.Profile)),t.enum(Object.values(C.Beneficiary)),t.enum(Object.values(C.Payment)),t.enum(Object.values(C.Payout)),t.enum(Object.values(C.Transfer)),t.enum(Object.values(C.Wallet))]);return t.object({name:t.literal("PermissionError").nullish(),message:t.string(),requiredPermissions:t.array(r)}).safeParse(e).success}}function B(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}const D=e=>"function"==typeof(null==e?void 0:e.passthrough);t.object({name:t.literal("ZodError"),issues:t.array(t.object({path:t.array(t.union([t.string(),t.number()])),message:t.string().optional(),code:t.nativeEnum(t.ZodIssueCode)}).catchall(t.any()))});const E=Symbol("ContractNoBody"),T=e=>"method"in e&&"path"in e,R=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s,o,i;return T(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:(o=null==t?void 0:t.baseHeaders,i=r.headers,D(o)?D(i)?o.merge(i):o:D(i)?i:Object.assign({},o,i)),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(a=r.validateResponseOnClient)&&void 0!==a?a:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,R(r,t)]})),J=Symbol("ContractPlainType"),j=()=>({router:(e,t)=>R(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>J,body:()=>J,type:()=>J,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>E}),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("&"):"",L=e=>e?Object.keys(e).flatMap(t=>x(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",x=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>x(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>x(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class F extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const k=async({route:e,path:t,method:r,headers:n,body:a,validateResponse:s,fetchOptions:o})=>{const i=await fetch(t,{...o,method:r,headers:n,body:a}),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!=s?s: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}},$=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},q=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),U=(e,t,r,n,a)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),o=((e,t=!1)=>{const r=t?M(e):L(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return`${t}${s}${o}`},V=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:s,headers:o,extraHeaders:i,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c};return{path:U(n,m.baseUrl,a,e,!!m.jsonQuery),clientArgs:m,route:e,body:s,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...i,...o}}})(e,t,n),s=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:s,extraInputArgs:o,headers:i,fetchOptions:c}=e,u=r.api||k,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&q(d),...q(i)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let h={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:a,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:a instanceof FormData?a:$(a)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(a)})),u({...h,...o})})(a);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new F(s,r)}},W=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>T(r)?[e,V(r,t)]:[e,W(r,t)]));let K;const Z=e=>{K=e};class G{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(K){const e=K();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":r()}};return W(this.contract,e)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(t,r){if(t.status===r)return t.body;if(400===t.status){const r=e.object({statusCode:e.number(),message:e.string(),error:e.string(),details:e.record(e.string()).optional()}).safeParse(t.body);if(r.success)throw new O(r.data);throw new O({message:"Bad request",statusCode:400,error:"BAD_REQUEST"})}if(401===t.status)throw new O({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===t.status)throw new O({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===t.status)throw new O({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});const n=t.status||502;throw new O({message:`We encountered an error trying to process your request. Please try again later (upstream status ${n}).`,statusCode:n,error:"UNKNOWN_ERROR"})}}var Q,H;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(Q||(Q={})),function(e){e.ASC="asc",e.DESC="desc"}(H||(H={}));const z=Symbol("query-builder-type");class Y{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}}[z]="query-builder";static is(e){return null!==e&&"object"==typeof e&&z in e&&"query-builder"===e[z]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:Q.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:Q.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:Q.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:Q.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:Q.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:Q.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:Q.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:Q.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:Q.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:Q.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:Q.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:Q.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:Q.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:Q.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=H.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,H.ASC)}orderByDesc(e){return this.orderBy(e,H.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 Q.IS_NULL:e[`${t.field}:isNull`]=1;break;case Q.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case Q.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case Q.LIKE:e[`${t.field}:like`]=t.value;break;case Q.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case Q.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case Q.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===H.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 Y(e)}}const X=t.object({page:t.coerce.number().int().min(1).default(1),limit:t.coerce.number().int().min(1).max(100).default(10)}),ee=t.object({page:t.number().int().min(1),limit:t.number().int().min(1),total:t.number().int().min(0),totalPages:t.number().int().min(0),hasNext:t.boolean(),hasPrev:t.boolean()});function te(e){return t.object({results:t.array(e),pagination:ee})}class re{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 re(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new re(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}}}function ne(e,t,r,n){return{results:e,pagination:new re(t,r,n)}}function ae(e=1,t=10){return{results:[],pagination:new re(e,t,0)}}const se={profileDTOSchema:t.object({id:t.string(),firstName:t.string().nullish(),lastName:t.string().nullish(),displayName:t.string(),phone:t.string().nullish(),accountNo:t.string().min(1),email:t.string().email().nullish(),autoApprove:t.boolean().nullish()})},oe=t.object({id:t.string(),firstName:t.string().nullable().optional(),lastName:t.string().nullable().optional(),displayName:t.string(),phone:t.string().nullable().optional(),accountNo:t.string(),email:t.string().nullable().optional(),autoApprove:t.boolean().nullable().optional(),_version:t.string().optional().default("1.0")});class ie{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return se.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 ie({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 ie.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?ie.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=oe.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return ie.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return oe.safeParse(e).success}}const ce={loginDTO:e.object({id:e.string().min(1,"ID is required"),profileId:e.string().min(1,"Profile ID is required"),name:e.string().min(1,"Name is required"),identity:e.string().email("Identity must be a valid email address"),type:e.string().min(1,"Type is required"),roleId:e.string().min(1,"Role ID is required"),isActive:e.boolean(),isArchived:e.boolean(),resetPassword:e.boolean(),createdAt:e.string().datetime("Invalid creation timestamp"),updatedAt:e.string().datetime("Invalid update timestamp"),access:e.array(e.string())})},ue=t.object({id:t.string(),profileId:t.string(),name:t.string(),identity:t.string(),type:t.string(),roleId:t.string(),isActive:t.boolean(),isArchived:t.boolean(),resetPassword:t.boolean(),createdAt:t.string(),updatedAt:t.string(),access:t.array(t.string()),_version:t.string().optional().default("1.0")});class de{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;_permissionMap;constructor(e,t,r,n,a,s,o,i,c,u,d,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=a,this._roleId=s,this._isActive=o,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=ce.loginDTO.parse(e);return new de(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=ue.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const n=r.data;return de.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 ue.safeParse(e).success}}const le=e.object({id:e.string(),name:e.string(),description:e.string().nullable().optional(),access:e.array(e.string()),createdAt:e.string(),updatedAt:e.string(),_version:e.string().optional().default("1.0")});class he{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 he(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=le.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const n=r.data;return he.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 le.safeParse(e).success}}const me=e.object({companyProfile:oe,role:le.optional(),_version:e.string().optional().default("1.0")});class pe{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return ie.is(e.companyProfile)?new pe(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=me.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,a=ie.fromJSON(n.companyProfile),s=n.role?he.fromJSON(n.role):void 0;return a?pe.from({companyProfile:a,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 me.safeParse(e).success}}const ye=e.object({logIn:ue,companyProfile:oe,role:le.optional(),_version:e.string().optional().default("1.0")});class fe{_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=pe.from({companyProfile:e.companyProfile,role:e.role});return t?new fe({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=ye.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,a=de.fromJSON(n.logIn),s=ie.fromJSON(n.companyProfile),o=n.role?he.fromJSON(n.role):void 0;if(!a||!s)return void console.error("Failed to reconstruct nested objects from UserJSON");const i=pe.from({companyProfile:s,role:o});return i?new fe({logIn:a,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 ye.safeParse(e).success}}const ge={logInRequestDTO:t.object({type:t.string().default("password"),identity:t.string().email(),password:t.string()}),logInResponseDTO:t.object({profile:se.profileDTOSchema,token:t.string(),access:t.array(t.string()),resetPassword:t.boolean()}),accessResponseDTO:t.array(t.string()),resetPasswordRequestDTO:t.object({currentPassword:t.string(),newPassword:t.string()}),emptyResponseDTO:t.object({})},be=j().router({logIn:{method:"POST",path:"/login",body:ge.logInRequestDTO,responses:{201:ge.logInResponseDTO,400:ge.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:ge.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:ge.resetPasswordRequestDTO,responses:{200:ge.emptyResponseDTO,400:ge.emptyResponseDTO}}}),Ne=j().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:ce.loginDTO}}});class we extends G{constructor(e){super("login",Ne,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 ve=t.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"),Ie=t.object({id:t.string().min(1),name:t.string().min(1,"Role name is required"),description:t.string().nullable().optional(),access:t.array(t.string()),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),Ae=t.object({id:t.string().min(1),name:t.string().min(1,"Team member name is required"),identity:t.string().email("Invalid email address"),type:t.string().min(1,"Team member type is required"),profileId:t.string().min(1,"Profile ID is required"),roleId:t.string().min(1,"Role ID is required"),resetPassword:t.boolean(),isActive:t.boolean(),isArchived:t.boolean(),role:Ie.optional(),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp")}),_e={role:Ie,teamMember:Ae,teamMemberQueryParams:t.object({id:t.string().min(1).optional(),name:t.string().min(1).optional(),identity:t.string().email("Invalid email address").optional(),type:t.string().min(1).optional(),profileId:t.string().min(1).optional(),roleId:t.string().min(1).optional(),resetPassword:t.number().optional(),isActive:t.number().optional(),isArchived:t.number().optional(),createdAt:t.string().datetime("Invalid creation timestamp").optional(),updatedAt:t.string().datetime("Invalid update timestamp").optional(),eager:t.string().optional()}),createTeamMemberRequest:t.object({name:t.string().min(1,"Team member name is required"),identity:t.string().email("Valid email address is required"),password:ve.optional(),roleId:t.string().optional(),resetPassword:t.boolean().optional()}),updateTeamMemberRequest:t.object({name:t.string().min(1,"Team member name cannot be empty").optional(),roleId:t.string().min(1,"Role ID cannot be empty").optional(),password:ve.optional(),resetPassword:t.boolean().optional(),isActive:t.boolean().optional()}),resetPasswordRequest:t.object({newPassword:ve.optional(),sendNotification:t.boolean().optional()}),createTeamMemberResponse:t.object({id:t.string(),name:t.string(),identity:t.string(),type:t.string(),profileId:t.string(),resetPassword:t.boolean(),roleId:t.string(),isActive:t.boolean(),isArchived:t.boolean(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}),password:ve},Se=j().router({getTeamMembers:{method:"GET",path:"/login",query:_e.teamMemberQueryParams,responses:{200:t.array(_e.teamMember),401:t.object({message:t.string().optional()}),403:t.object({message:t.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.object({id:t.string()}),query:_e.teamMemberQueryParams,responses:{200:_e.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:_e.createTeamMemberRequest,responses:{201:_e.createTeamMemberResponse,400:t.object({message:t.string().optional(),errors:t.array(t.string()).optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),409:t.object({message:t.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.object({id:t.string()}),body:_e.updateTeamMemberRequest,responses:{200:_e.teamMember,400:t.object({message:t.string().optional(),errors:t.array(t.string()).optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.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.object({id:t.string()}),body:t.object({}),responses:{201:_e.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:t.object({id:t.string()}),body:t.object({}),responses:{201:_e.teamMember,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:t.object({id:t.string()}),body:_e.resetPasswordRequest,responses:{201:t.object({success:t.boolean()}),400:t.object({message:t.string().optional()}),401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.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.array(_e.role),401:t.object({message:t.string().optional()}),403:t.object({message:t.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.object({id:t.string()}),responses:{200:_e.role,401:t.object({message:t.string().optional()}),403:t.object({message:t.string().optional()}),404:t.object({message:t.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),Oe=e.object({id:e.string(),name:e.string(),identity:e.string(),type:e.string(),profileId:e.string(),roleId:e.string(),resetPassword:e.boolean(),isActive:e.boolean(),isArchived:e.boolean(),role:le.optional(),createdAt:e.string(),updatedAt:e.string(),_version:e.string().optional().default("1.0")});class Ce{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 he(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new Ce(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 Ce.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>Ce.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=Oe.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,a=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 Ce.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:a,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return Oe.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Ce.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 Pe extends G{constructor(e){super("admin",Se,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),a=Ce.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e},body:{}}),r=this.handleResponse(t,201),n=Ce.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=Ce.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 Ce.createMany(r)}async getTeamMember(e,t={eager:"roleId"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),a=Ce.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=he.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=he.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}class Be extends G{constructor(e){super("auth",be,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 O({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new we({token:e}),r=await t.getIdentity(),a=de.from(r);if(!a)throw new O({message:"Failed to construct login credentials",statusCode:502});const s=n.body.profile,o=ie.from(s);if(!o)throw new O({message:"Failed to construct user profile",statusCode:502});let i;if(a.can(C.Role.ViewRole))try{const t=new Pe({token:e});i=await t.getRole(a.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const c=fe.from({logIn:a,companyProfile:o,role:i});if(!c)throw new O({message:"Failed to construct user session",statusCode:502});return{token:e,user:c}}throw new O({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 O({message:"Invalid current password",statusCode:400});throw new O({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}`)}}var De;!function(e){e.BANK="Bank",e.MOBILE="Mobile"}(De||(De={}));const Ee=t.nativeEnum(De),Te=t.object({displayName:t.string().min(1,"Display name is required"),accountNo:t.string().min(1,"Account number is required"),channel:t.string().min(1,"Channel is required"),type:Ee}),Re={beneficiaryDTO:t.object({id:t.string().min(1,"Beneficiary id is required"),profileId:t.string(),createdAt:t.string().datetime(),updatedAt:t.string().datetime()}).merge(Te),beneficiaryInputDTO:Te,beneficiaryType:Ee},Je=t.object({type:t.literal(De.MOBILE),name:t.string().min(1),phoneNumber:a,mnoId:n,_version:t.string().optional().default("1.0")}),je=t.object({type:t.literal(De.BANK),accName:t.string().min(1),swiftCode:t.union([o,i]),countryCode:s,accNo:t.string().min(1),_version:t.string().optional().default("1.0")}),Me=t.discriminatedUnion("type",[Je,je]);class Le extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class xe{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===De.MOBILE}get isBank(){return this.type===De.BANK}get displayName(){return this.accountName}}class Fe extends xe{name;phoneNumber;mnoId;constructor(e,t,r){super(De.MOBILE,t.countryCode),this.name=e,this.phoneNumber=t;const n=Fe.resolveMnoId(t,r),a=Fe.checkInputs(e,t,n);if(!a.isValid)throw new Le(a.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:n});this.mnoId=n}static resolveMnoId(e,t){return c.requiresExplicitProvider(e.countryCode)?t:c.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,r){const n=[];return e?.trim()||n.push("Name is required and cannot be empty"),t?.validate()||n.push("Invalid phone number"),r?c.validateProviderForPhoneNumber(t,r)||n.push(`Invalid MNO ${r} for phone number ${t.e164Format}`):n.push(c.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 r=Fe.pickMnoIdFromPayoutChannel(e.countryCode,t);if(r)return r;if(c.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return c.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const n=c.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[r,n,a]=t.split("-");return"B2C"===a&&"BANK"!==n&&r===e&&c.isProviderSupported(e,n)?n:void 0}static from(e){try{return new Fe(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==De.MOBILE)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,r=u.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const n=Fe.pickMnoIdFromDTO(r,e.channel);return n?Fe.from({name:e.displayName,phoneNumber:r,mnoId:n}):void 0}static fromBeneficiaryDTO(e){return Fe.fromInputDTO(e)}static fromPayoutDTO(e){if(!d.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=u.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);const r=Fe.pickMnoIdFromDTO(t,e.channel);return r?Fe.from({name:e.payeeName,phoneNumber:t,mnoId:r}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===De.MOBILE&&(!("string"!=typeof t.name||!t.name.trim())&&(!!u.is(t.phoneNumber)&&("string"==typeof t.mnoId&&c.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return Fe.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return Fe.checkInputs(this.name,this.phoneNumber,this.mnoId)}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(l.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=c.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return c.findById(this.mnoId,this.countryCode)}toJSON(){return{type:De.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,r=Je.safeParse(t);if(!r.success)return void console.error("Invalid MobileBeneficiaryJSON:",r.error.flatten());const n=u.from(r.data.phoneNumber);if(!n)return;return Fe.from({name:r.data.name,phoneNumber:n,mnoId:r.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return Fe.fromJSON(e)}static isJSON(e){return Je.safeParse(e).success}}class ke extends xe{accName;bank;accNo;constructor(e,t,r){super(De.BANK,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=ke.checkInputs(e,t,r);if(!n.isValid)throw new Le(n.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,r){const n=[];return h.validateAccountName(e)||n.push("Invalid account name"),m.is(t)?h.validateAccountNumber(r,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 ke(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==De.BANK)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const r=h.getCountryFromSwiftCode(t);if(!r)return void console.error(`Could not identify country from SWIFT code: ${t}`);const n=m.fromBIC(t,r);if(n)return ke.from({accName:e.displayName,bank:n,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromBeneficiaryDTO(e){return ke.fromInputDTO(e)}static fromPayoutDTO(e){if(!d.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[r,n]=t,a=m.fromBIC(r,e.countryCode);if(a)return ke.from({accName:e.payeeName,bank:a,accNo:n});console.error(`Bank with SWIFT code ${r} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===De.BANK&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!m.is(t.bank)&&(h.validateAccountName(t.accName)&&h.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return ke.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return ke.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:De.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,r=je.safeParse(t);if(!r.success)return void console.error("Invalid BankBeneficiaryJSON:",r.error.flatten());const n=r.data;if(!d.isISO2Code(n.countryCode))return;const a=m.fromBIC(n.swiftCode,n.countryCode);if(!a)return;return ke.from({accName:n.accName,bank:a,accNo:n.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return ke.fromJSON(e)}static isJSON(e){return je.safeParse(e).success}}class $e{static fromInputDTO(e){return $e.fromDTO(e)}static fromBeneficiaryDTO(e){return $e.fromDTO(e)}static fromPayoutDTO(e){return e.msisdn.includes(":")?ke.fromPayoutDTO(e):Fe.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Me.safeParse(t);if(!r.success)return;return r.data.type===De.MOBILE?Fe.fromJSON(r.data):ke.fromJSON(r.data)}catch{return}}static fromJSONString(e){return $e.fromJSON(e)}static is(e){return Fe.is(e)||ke.is(e)}static isJSON(e){return Me.safeParse(e).success}static fromDTO(e){return e.type===De.MOBILE?Fe.fromInputDTO(e):ke.fromInputDTO(e)}}const qe={fromInputDTO:e=>$e.fromInputDTO(e),fromBeneficiaryDTO:e=>$e.fromBeneficiaryDTO(e),fromPayoutDTO:e=>$e.fromPayoutDTO(e),fromJSON:e=>$e.fromJSON(e),fromJSONString:e=>$e.fromJSONString(e),is:e=>$e.is(e),isJSON:e=>$e.isJSON(e)},Ue=Re.beneficiaryDTO.extend({_version:t.string().optional().default("1.0")});class Ve{_id;_profileId;_displayName;_accountNo;_channel;_type;_createdAt;_updatedAt;_info;_infoComputed=!1;constructor(e){const t=Re.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=$e.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===De.MOBILE?"Phone Number":this.type===De.BANK?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===De.MOBILE?"Channel":this.type===De.BANK?"Bank":"Channel"}get accNameLabel(){return this.type===De.MOBILE?"Full Name":this.type===De.BANK?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new Ve(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new Ve(e)}static createMany(e){return e.map(e=>new Ve(e))}static createSafe(e){return Ve.from(e)??null}static canConstruct(e){return Re.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 Ue.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=Ue.safeParse(r);if(!n.success)return void console.error("Invalid BeneficiaryJSON:",n.error.flatten());const a=n.data,{_version:s,...o}=a;return Ve.from(o)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return Ve.fromJSON(e)}static isBeneficiaryJSON(e){return Ue.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 We{canHandle(e){return e.type===De.MOBILE&&Fe.is(e)}createInput(e){if(Fe.is(e))return{type:De.MOBILE,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class Ke{canHandle(e){return e.type===De.BANK&&ke.is(e)}createInput(e){if(ke.is(e))return{type:De.BANK,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class Ze{handlers=[new We,new Ke];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 Ge=j().router({createBeneficiary:{method:"POST",path:"/",body:Re.beneficiaryInputDTO,responses:{201:Re.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:Re.beneficiaryInputDTO,responses:{200:Re.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:t.object({orderByDesc:t.string()}),responses:{200:t.array(Re.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:Re.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:t.object({}),responses:{200:t.object({})}}});class Qe extends G{constructor(e){super("contact",Ge,e)}async create(e){const t=(new Ze).resolve(e),r=await this.client.createBeneficiary({body:t}),n=this.handleResponse(r,201);return Ve.create(n)}async edit(e,t){const r=(new Ze).resolve(t),n=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(n,200);return Ve.create(a)}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 Ve.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return Ve.create(r)}}var He,ze,Ye;!function(e){e.TZ_TIGO_B2C="TZ-TIGO-B2C",e.TZ_VODACOM_B2C="TZ-VODACOM-B2C",e.TZ_AIRTEL_B2C="TZ-AIRTEL-B2C",e.TZ_HALOTEL_B2C="TZ-HALOTEL-B2C",e.KE_SAFARICOM_B2C="KE-SAFARICOM-B2C",e.TZ_BANK_B2C="TZ-BANK-B2C",e.KE_BANK_B2C="KE-BANK-B2C"}(He||(He={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED",e.QUEUED="QUEUED"}(ze||(ze={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}(Ye||(Ye={}));const Xe=t.object({id:t.string(),name:t.string(),identity:t.string()}),et=t.nativeEnum(ze),tt=t.nativeEnum(Ye),rt=t.nativeEnum(He),nt=t.union([t.string(),t.array(t.string())]).transform(e=>(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(e=>e.length>0)),at=nt.pipe(t.array(et)),st=nt.pipe(t.array(tt)),ot=t.object({channel:rt,msisdn:t.string(),amount:t.coerce.number(),description:t.string(),notes:t.string().nullish()}),it=ot.extend({payeeName:t.string()}),ct=ot.extend({id:t.string(),profileId:t.string(),payeeName:t.string(),countryCode:t.string().default("TZ").refine(e=>d.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>p.isCode(e),{message:"Provided currency code is not a valid currency code."}),channel:t.string(),status:et,statusMessage:t.string(),partnerReference:t.string().nullish(),createdAt:t.coerce.date(),updatedAt:t.coerce.date(),actionedAt:t.coerce.date().nullish(),approvalStatus:tt.nullish(),createdById:t.string().nullish(),actionedById:t.string().nullish(),createdBy:Xe.nullish(),actionedBy:Xe.nullish()}),ut=t.object({page:t.number().int().positive().default(1),limit:t.number().int().positive().max(100).default(10),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().datetime().nullish(),endDate:t.string().datetime().nullish(),payeeName:t.string().nullish(),msisdn:t.string().nullish(),msisdnIn:nt.nullish(),profileId:t.string().nullish(),id:t.string().nullish(),partnerReference:t.string().nullish(),channel:t.string().nullish(),channelIn:nt.nullish(),currencyCode:t.string().nullish(),status:et.nullish(),statusIn:at.nullish(),approvalStatus:tt.nullish(),approvalStatusIn:st.nullish(),createdById:t.string().nullish(),createdByIdIn:nt.nullish(),actionedById:t.string().nullish(),actionedByIdIn:nt.nullish(),minAmount:t.number().min(0).nullish(),maxAmount:t.number().min(0).nullish(),search:t.string().nullish(),relations:t.array(t.string()).nullish()}),dt={PayoutDTO:ct,PayoutInputDTO:it,PayoutStatus:et,PayoutApprovalStatus:tt,PayoutChannel:rt,PayoutAuthorizer:Xe,PayoutFilters:ut,PayoutURLQueryParams:t.object({page:t.string().transform(e=>parseInt(e)||1).optional(),limit:t.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.string().default("createdAt"),sortOrder:t.enum(["asc","desc"]).default("desc"),startDate:t.string().optional(),endDate:t.string().optional(),payeeName:t.string().optional(),msisdn:t.string().optional(),msisdnIn:nt.optional(),profileId:t.string().optional(),id:t.string().optional(),partnerReference:t.string().optional(),channel:t.string().optional(),channelIn:nt.optional(),status:t.string().refine(e=>Object.values(ze).includes(e)).transform(e=>e).optional(),statusIn:at.optional(),approvalStatus:t.string().refine(e=>Object.values(Ye).includes(e)).transform(e=>e).optional(),approvalStatusIn:st.optional(),createdById:t.string().optional(),createdByIdIn:nt.optional(),actionedById:t.string().optional(),actionedByIdIn:nt.optional(),minAmount:t.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.string().transform(e=>parseFloat(e)).optional(),search:t.string().optional(),relations:t.array(t.string()).optional()})},lt=e.object({id:e.string(),profileId:e.string(),payeeName:e.string(),channel:e.string(),msisdn:e.string(),amount:e.number(),currencyCode:e.string(),countryCode:e.string(),description:e.string(),notes:e.string().nullish(),status:dt.PayoutStatus,statusMessage:e.string(),partnerReference:e.string().nullish(),createdAt:e.string(),updatedAt:e.string(),actionedAt:e.string().nullish(),approvalStatus:dt.PayoutApprovalStatus.nullish(),createdById:e.string().nullish(),actionedById:e.string().nullish(),createdBy:dt.PayoutAuthorizer.nullish(),actionedBy:dt.PayoutAuthorizer.nullish(),_version:e.string().optional().default("1.0")});class ht{_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=dt.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 y.from(this._amount,this._currencyCode)}get description(){return this._description}get notes(){return this._notes}get status(){return this._approvalStatus===Ye.REJECTED?ze.REJECTED:this._approvalStatus===Ye.APPROVED?"FAILED"===this._status?ze.FAILED:ze.PAID:this._approvalStatus===Ye.PENDING?ze.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 $e.fromPayoutDTO(this.toDTO())}get contactInfo(){return this.beneficiaryInfo}static create(e){return new ht(e)}static createMany(e){return e.map(e=>new ht(e))}static createSafe(e){try{return new ht(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=dt.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==ht.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 lt.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,r=lt.safeParse(t);if(!r.success)return void console.error("Invalid PayoutJSON:",r.error.flatten());const n=r.data,a=n.currencyCode;if(!p.isCode(a))return void console.error("Invalid currency code:",a);const s=n.countryCode;if(!d.isISO2Code(s))return void console.error("Invalid country code:",s);const o={id:n.id,profileId:n.profileId,payeeName:n.payeeName,channel:n.channel,msisdn:n.msisdn,amount:n.amount,currencyCode:a,countryCode:s,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 ht.create(o)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return lt.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ht.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 mt="MOBILE TRANSFER ",pt="PAYOUT",yt="PAYOUT TO BANK",ft="TO_BANK",gt="PAYOUT TO MOBILE",bt="TO_MOMO",Nt=e.object({text:e.string(),_version:e.string().optional().default("2.0")});class wt{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 Fe.is(e)?wt.generateMobilePayoutNarrationV2(e):ke.is(e)?wt.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${pt.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${pt.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(mt)&&(e=e.substring(16));try{if(e.startsWith(pt)){const t=e.replace(pt,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(vt).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=h.getCountryFromSwiftCode(e);if(t){if(h.validateSwiftCode(e,t)){const a=m.fromBIC(e,t);if(r&&n&&a)return new ke(n,a,r)}}}}}if(e.startsWith(ft)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,a=r.account_name,s=r.swift_code,o=h.getCountryFromSwiftCode(s);if(!o)return;if(!h.validateSwiftCode(s,o))return;const i=m.fromBIC(s,o);if(n&&a&&i)return new ke(a,i,n)}if(e.startsWith(yt)){const t=e.replace(yt,"").trim().split(" "),r=f.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,a=t[1],s=t.slice(2).map(vt).join(" ");if(s&&a&&n)return new ke(s,n,a)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(mt)&&(e=e.substring(16));try{if(e.startsWith(pt)){const t=e.replace(pt,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(vt).join(" ");if(e.startsWith("+")){const t=u.from(e);if(t&&r)return new Fe(r,t)}}}if(e.startsWith(bt)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=u.from(r.phone_number,{defaultCountry:"TZ"});let a=r.username;void 0===a&&(a="");let s=a.split(" ");if(s=s.filter(e=>e.trim().length>0),a=s.map(vt).join(" "),n&&a)return new Fe(a,n)}if(e.startsWith(gt)){const t=e.replace(gt,"").trim().split(" "),r=u.from(t[0],{defaultCountry:"TZ"}),n=t.slice(1).map(vt).join(" ");if(r&&n)return new Fe(n,r)}}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=Nt.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new wt(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return Nt.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return wt.fromJSON(e)}}function vt(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const It=["TZ","KE"],At={TZ:He.TZ_BANK_B2C,KE:He.KE_BANK_B2C},_t={TIGO:He.TZ_TIGO_B2C,VODACOM:He.TZ_TIGO_B2C,AIRTEL:He.TZ_AIRTEL_B2C,HALOTEL:He.TZ_HALOTEL_B2C},St="Invalid bank beneficiary info",Ot="Invalid phone number",Ct="The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",Pt="Wallet country does not match beneficiary country",Bt="Wallet currency does not match payout amount currency",Dt="Payout amount currency does not match the payout country currency",Et="Only TZ and KE bank payout channels are supported for now",Tt="Only TZ and KE mobile money payout channels are supported for now",Rt="Mobile money provider is not supported for payouts in this country",Jt=e=>It.includes(e);class jt{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===w.MOBILE||t===w.FIXED_LINE_OR_MOBILE}}class Mt{static resolve(e){const{wallet:t,receiver:r,amount:n}=e;return this.assertCompatibleWalletReceiverAndAmount(t,r,n),Fe.is(r)?this.forMobile(r.phoneNumber,r.mnoId,t):this.forBank(r,t)}static forBank(e,t){if(!ke.is(e))throw new Error(St);if(!Jt(t.countryCode))throw new Error(Et);if(t.countryCode!==e.countryCode)throw new Error(Pt);return At[t.countryCode]}static forMobile(e,t,r){if(!u.is(e))throw new Error(Ot);if(!Jt(r.countryCode)||!Jt(e.countryCode))throw new Error(Tt);if(r.countryCode!==e.countryCode)throw new Error(Pt);if(!jt.isPhoneEligibleForPayout(e))throw new Error(Ct);if("KE"===r.countryCode)return He.KE_SAFARICOM_B2C;const n=c.findById(t,e.countryCode);if(!n||!n.supportsDirection(g.PAYOUT))throw new Error(Rt);const a=_t[n.id];if(!a)throw new Error(Rt);return a}static getChannelType(e){return this.isBankChannel(e)?b.BANK:b.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,r){if(e.countryCode!==t.countryCode)throw new Error(Pt);if(e.currencyCode!==r.currencyCode)throw new Error(Bt);const n=N.fromCode(e.countryCode)?.currencyCode;if(n&&r.currencyCode!==n)throw new Error(Dt)}}class Lt{getPayoutInput(e,t){const r=Mt.resolve({...e,wallet:t});if(Fe.is(e.receiver))return this.createMobileInput(e.receiver,e.amount,r,e.notes);if(ke.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,r,n){const a=jt.processNotes(n);return{channel:r,msisdn:e.phoneNumber.getWithFormat(l.INTERNATIONAL_NUMERIC),description:a??wt.generateDefaultPayoutNarration(e),payeeName:e.name,notes:a,amount:t.numericValue}}createBankInput(e,t,r,n){const a=jt.processNotes(n);return{channel:r,msisdn:`${e.bank.bic}:${e.accNo}`,description:a??wt.generateDefaultPayoutNarration(e),payeeName:e.accName,notes:a,amount:t.numericValue}}}const xt={bank:Mt.forBank.bind(Mt),mobile:Mt.forMobile.bind(Mt)},Ft=j().router({getPayouts:{method:"GET",path:"",query:t.object({}),responses:{200:t.object({results:t.array(dt.PayoutDTO),total:t.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:t.object({rangeStart:t.number(),rangeEnd:t.number(),eager:t.string(),approvalStatus:dt.PayoutApprovalStatus,orderByDesc:t.string()}),responses:{200:t.object({results:t.array(dt.PayoutDTO),total:t.number()})}},postPayout:{method:"POST",path:"",body:dt.PayoutInputDTO,responses:{201:dt.PayoutDTO,400:O.schema}},approve:{method:"POST",path:"/:id/approve",body:t.object({action:t.enum(["Approve","Reject"]),notes:t.string().optional()}),responses:{201:dt.PayoutDTO,400:O.schema,401:O.schema,404:t.object({}),409:t.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:dt.PayoutDTO,404:t.object({})}}}),kt=["approvalStatus","status","channel","msisdn","createdById","actionedById"];class $t extends Y{static create(){return new $t}static fromFilters(e){return(new $t).applyFilters(e)}static fromUrlParams(e){try{const t=dt.PayoutURLQueryParams.parse(this.normalizeUrlParams(e)),r=dt.PayoutFilters.parse(t);return $t.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return $t.fromUrlParams(this.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return $t.fromSearchParams(t)}static from(e){try{return null==e?new $t:Y.is(e)?new $t(e.options):e instanceof URLSearchParams?$t.fromSearchParams(e):this.isUrlParamsRecord(e)?$t.fromUrlParams(e):$t.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 kt){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,o=`${e}In[]`,i=t[r],c=$t.toStringList([t[n],t[a],t[s],t[o],Array.isArray(i)?i:void 0]);c.length>0&&(t[n]=c),Array.isArray(i)&&delete t[r],delete t[a],delete t[s],delete t[o]}return t}static toStringList(e){const t=Array.isArray(e)?e.flatMap(e=>$t.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(Ye.PENDING)}whereApproved(){return this.whereApprovalStatus(Ye.APPROVED)}whereRejected(){return this.whereApprovalStatus(Ye.REJECTED)}wherePaid(){return this.whereStatus(ze.PAID)}whereFailed(){return this.whereStatus(ze.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,r=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:n}=e,a=n||"TZS";if(!p.isCode(a))return console.warn("Amount filter requires a valid currency code"),this;if(t&&r){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=y.from(e.minAmount,a),r=y.from(e.maxAmount,a);t&&r&&this.whereAmountBetween(t,r)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):r&&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=[],r=this.toFilters(),n=e?.formatDate??(e=>e);if(r.sortBy){const e="asc"===r.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(r.sortBy)} (${e})`})}if(r.startDate&&r.endDate?t.push({label:"Date Range",value:`${n(r.startDate)} — ${n(r.endDate)}`}):r.startDate?t.push({label:"From",value:n(r.startDate)}):r.endDate&&t.push({label:"Until",value:n(r.endDate)}),r.statusIn?.length?t.push({label:"Status",value:r.statusIn.join(", ")}):r.status&&t.push({label:"Status",value:r.status}),r.approvalStatusIn?.length?t.push({label:"Approval Status",value:r.approvalStatusIn.join(", ")}):r.approvalStatus&&t.push({label:"Approval Status",value:r.approvalStatus}),r.channelIn?.length?t.push({label:"Channel",value:r.channelIn.join(", ")}):r.channel&&t.push({label:"Channel",value:r.channel}),void 0!==r.minAmount&&void 0!==r.maxAmount){const e=Number(r.minAmount),n=Number(r.maxAmount);if(Number.isFinite(e)&&Number.isFinite(n)){const r=y.from(e,"TZS"),a=y.from(n,"TZS");r&&a&&t.push({label:"Amount Range",value:`${r.label} — ${a.label}`})}}else if(void 0!==r.minAmount){const e=Number(r.minAmount);if(Number.isFinite(e)){const r=y.from(e,"TZS");r&&t.push({label:"Minimum Amount",value:r.label})}}else if(void 0!==r.maxAmount){const e=Number(r.maxAmount);if(Number.isFinite(e)){const r=y.from(e,"TZS");r&&t.push({label:"Maximum Amount",value:r.label})}}return r.search&&t.push({label:"Search",value:`"${r.search}"`}),r.payeeName&&t.push({label:"Beneficiary Name",value:r.payeeName}),r.msisdnIn?.length?t.push({label:"MSISDN",value:r.msisdnIn.join(", ")}):r.msisdn&&t.push({label:"MSISDN",value:r.msisdn}),r.profileId&&t.push({label:"Profile",value:r.profileId}),r.createdByIdIn?.length?t.push({label:"Created By ID",value:r.createdByIdIn.join(", ")}):r.createdById&&t.push({label:"Created By ID",value:r.createdById}),r.actionedByIdIn?.length?t.push({label:"Actioned By ID",value:r.actionedByIdIn.join(", ")}):r.actionedById&&t.push({label:"Actioned By ID",value:r.actionedById}),r.partnerReference&&t.push({label:"Reference",value:r.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=$t.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=$t.toStringList(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=$t.toStringList(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidApprovalStatuses(e){const t=$t.toStringList(e).filter(e=>this.isValidApprovalStatus(e));return t.length>0?t:void 0}isValidStatus(e){return Object.values(ze).includes(e)}isValidApprovalStatus(e){return Object.values(Ye).includes(e)}}class qt extends G{constructor(e){super("payout",Ft,e)}async getPayouts(e){try{const t=$t.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),o=new re(s.page??1,s.limit??10,a.total);return{results:ht.createMany(a.results),pagination:o}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getAllPayouts(e){try{const t=$t.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return ht.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=$t.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,receiver:r,amount:n,notes:a}=e,s=Mt.resolve({wallet:t,receiver:r,amount:n}),o=v.getTransactionLimits({countryCode:t.countryCode,currencyCode:n.currencyCode,direction:g.PAYOUT,channelType:Mt.getChannelType(s)});if(!o)throw new O({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${n.currencyCode} ${s} payouts`});const{min:i,max:c}=o;if(n.lessThan(i)||n.greaterThan(c))throw new O({statusCode:400,message:`Please make sure the amount is between ${i.label} - ${c.label}`});const u=(new Lt).getPayoutInput({receiver:r,amount:n,notes:a},t),d=await this.client.postPayout({body:u});if(201===d.status)return ht.create(d.body);if(400===d.status)throw new O(d.body);throw O.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 ht.create(t.body);if(401===t.status)throw new O({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new O({message:"Payout not found",statusCode:404});if(409===t.status)throw new O({message:"Payout already approved",statusCode:409});throw O.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 ht.create(t.body);if(401===t.status)throw new O({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new O({message:"Payout not found",statusCode:404});if(409===t.status)throw new O({message:"Payout already rejected",statusCode:409});throw O.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return ht.create(t.body);if(404===t.status)throw new O({message:"Payout not found",statusCode:404});throw O.unknown()}async count(e){const t=$t.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}}const Ut=e=>e.optional().transform(e=>e??void 0),Vt={walletDTO:t.object({id:t.string().min(1,{message:"Wallet ID is required."}),profileId:t.string().min(1,{message:"Profile ID is required."}),accountNo:t.string().min(1,{message:"Account number is required."}),accountName:t.string().min(1,{message:"Account name is required."}),channel:t.string().min(1,{message:"Channel is required."}),countryCode:t.string().default("TZ").refine(e=>d.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:t.string().default("TZS").refine(e=>p.isCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:t.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:t.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:t.object({id:t.string().optional(),profileId:t.string().optional(),accountNo:t.string().optional(),accountName:t.string().optional(),channel:t.string().optional(),countryCode:t.string().default("TZ").refine(e=>_.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:t.string().default("TZS").refine(e=>{const t=I.fromCode(e);return void 0!==t&&A.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:t.object({accountNo:Ut(t.string()),debitOrCredit:t.string().min(1,"Transaction type is required"),tranRefNo:t.string().min(1,"Transaction reference is required"),narration:t.string().min(1,"Transaction description is required"),txnDate:t.coerce.date({errorMap:()=>({message:"Invalid transaction date format"})}),valueDate:t.coerce.date({errorMap:()=>({message:"Invalid value date format"})}),amountCredited:t.number().min(0,"Credited amount must be non-negative"),amountDebited:t.number().min(0,"Debited amount must be non-negative"),balance:t.number(),currencyCode:Ut(t.string().min(3,"Currency code must be at least 3 characters")).default("TZS")})},Wt=e.object({id:e.string(),profileId:e.string(),accountNo:e.string(),accountName:e.string(),channel:e.string(),countryCode:e.string(),currencyCode:e.string(),createdAt:e.string(),updatedAt:e.string(),_version:e.string().optional().default("1.0")});class Kt{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return Vt.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=Kt.schema.safeParse(e);if(t.success)return new Kt(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=Kt.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 Kt.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&&d.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&p.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=Wt.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const n=r.data;return Kt.create(n)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return Wt.safeParse(e).success}}const Zt=e.object({accountNo:e.string().optional(),debitOrCredit:e.string(),tranRefNo:e.string(),narration:Nt,txnDate:e.string(),valueDate:e.string(),amountCredited:S,amountDebited:S,balance:S,currencyCode:e.string(),_version:e.string().optional().default("2.0")});class Gt{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return Vt.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 r=I.fromCode(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=y.from(e.amountCredited,r.code),a=y.from(e.amountDebited,r.code),s=y.from(e.balance,r.code);if(!n||!a||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=a,this._balance=s}static create(e){const t="string"==typeof e.narration?new wt(e.narration):e.narration,r={...e,narration:t.text},n=Gt.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new Gt(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=Gt.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&&wt.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&y.is(t._amountCredited)&&y.is(t._amountDebited)&&y.is(t._balance)&&"string"==typeof t._currencyCode}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return Gt.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,r,n,a,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const a=y.fromJSON(e.amountCredited),o=y.fromJSON(e.amountDebited),i=y.fromJSON(e.balance);if(!a||!o||!i)return void console.error("Failed to deserialize Amount objects from JSON");t=a.numericValue,r=o.numericValue,n=i.numericValue,e.currencyCode||(s=a.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)a=e.narration;else if(wt.is(e.narration))a=e.narration;else{if(!wt.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=wt.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return Gt.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:a,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,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,r=Zt.safeParse(t);if(!r.success)return void console.error("Invalid WalletStatementEntryJSON:",r.error.flatten());const n=r.data,a=wt.fromJSON(n.narration);if(!a)return void console.warn("Failed to deserialize narration");const s=y.fromJSON(n.amountCredited),o=y.fromJSON(n.amountDebited),i=y.fromJSON(n.balance);return s&&o&&i?s.currencyCode!==n.currencyCode||o.currencyCode!==n.currencyCode||i.currencyCode!==n.currencyCode?void console.warn("Currency code mismatch"):Gt.create({accountNo:n.accountNo,debitOrCredit:n.debitOrCredit,tranRefNo:n.tranRefNo,narration:a,txnDate:n.txnDate,valueDate:n.valueDate,amountCredited:s.numericValue,amountDebited:o.numericValue,balance:i.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 Zt.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Gt.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 Gt.fromJSON(e)}static fromJsonArray(e){return Gt.fromJSONArray(e)}static toJsonArray(e){return Gt.toJSONArray(e)}}const Qt=j().router({getWallets:{method:"GET",path:"/",query:Vt.walletQuery,responses:{200:t.array(Kt.schema)}},getBalance:{method:"POST",path:"/balance",body:t.object({accountNo:t.string().optional()}),responses:{201:t.object({availableBalance:t.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:t.object({endDate:t.date(),startDate:t.date(),accountNo:t.string().optional()}),responses:{201:t.array(Gt.schema)}}});class Ht extends Y{static create(){return new Ht}static fromFilters(e){return(new Ht).applyFilters(e)}static fromUrlParams(e){try{const t=Vt.walletQuery.parse(e);return Ht.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 Ht.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Ht.fromSearchParams(t)}static from(e){try{return null==e?new Ht:Y.is(e)?new Ht(e.options):e instanceof URLSearchParams?Ht.fromSearchParams(e):this.isStringRecord(e)?Ht.fromUrlParams(e):Ht.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}}class zt extends G{constructor(e){super("wallet",Qt,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 r=t.body.availableBalance,n=y.from(r,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 r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=y.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=Ht.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=Kt.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=Ht.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),a=e.range??{startDate:r,endDate:n};let s,o;if(e.wallet)s=e.wallet,o=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}`);s=t[0],o=e.accountNo}}const i={...a,accountNo:o},c=await this.client.getStatement({body:i});if(201===c.status){return c.body.map(e=>({...e,currencyCode:s.currencyCode})).reduce((e,t)=>{const r=Gt.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}}const Yt={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)},Xt=j().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:ie.schema}}});class er extends G{constructor(e){super("profile",Xt,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=ie.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}`)}}export{O as APIError,ge as AuthDTOSchemas,Be as AuthRepository,yt as BANK_NARR_PREFIX,ke as BankBeneficiaryInfo,je as BankBeneficiaryJSONSchema,G as BaseRepository,Ve as Beneficiary,Re as BeneficiaryDTOSchemas,Le as BeneficiaryError,qe as BeneficiaryInfo,$e as BeneficiaryInfoFactory,Me as BeneficiaryInfoJSONSchema,Ue as BeneficiaryJSONSchema,Qe as BeneficiaryRepository,De as BeneficiaryType,pe as CompanyMembership,me as CompanyMembershipJSONSchema,mt as ECOBANK_PREFIX,Q as FilterOperator,we as IdentityRepository,ft as LEGACY_BANK_NARR_PREFIX,bt as LEGACY_MOBILE_NARR_PREFIX,de as LogIn,ue as LogInJSONSchema,ce as LogInSchemas,gt as MOBILE_NARR_PREFIX,Fe as MobileBeneficiaryInfo,Je as MobileBeneficiaryJSONSchema,pt as NARR_V2_PREFIX,wt as Narration,Nt as NarrationJSONSchema,re as Pagination,X as PaginationParamsSchema,ee as PaginationSchema,ht as Payout,Ye as PayoutApprovalStatus,He as PayoutChannel,Mt as PayoutChannelResolver,dt as PayoutDTOSchemas,Lt as PayoutInputFactory,lt as PayoutJSONSchema,$t as PayoutQuery,qt as PayoutRepository,ze as PayoutStatus,P as PermissionError,C as Permissions,ie as Profile,se as ProfileDTOSchemas,oe as ProfileJSONSchema,er as ProfileRepository,z as QUERY_BUILDER_TYPE,Y as QueryBuilder,he as Role,le as RoleJSONSchema,H as SortDirection,_e as TeamManagementDTOSchemas,Ce as TeamMember,Oe as TeamMemberJSONSchema,Pe as TeamMemberRepository,fe as User,ye as UserJSONSchema,Ze as ValidatedBeneficiaryInputFactory,Kt as Wallet,Vt as WalletDTOSchemas,Wt as WalletJSONSchema,zt as WalletRepository,Gt as WalletStatementEntry,Zt as WalletStatementEntryJSONSchema,Yt as WalletUtils,Ge as contract,ne as createPaginatedResponse,te as createPaginatedResponseSchema,xt as createPayoutChannelCode,ae as emptyPaginatedResponse,B as isError,Z as setGlobalTokenGetter};
1
+ import{v4 as e}from"uuid";import t,{z as r}from"zod";import{MobileMoneyProviderIdSchema as n,E164PhoneNumberFormatSchema as a,ISO2CountryCodeSchema as s,TZBankSWIFTCodeSchema as i,KEBankSWIFTCodeSchema as o,MobileMoneyProviderHelpers as c,PhoneNumber as d,CountryHelpers as u,PhoneNumberFormat as l,BankHelpers as h,Bank as p,CurrencyHelpers as m,Amount as f,BankRegistry as y,TransactionDirection as g,ChannelType as v,Country as _,PhoneNumberType as b,TemboCoverage as w,Currency as N,CurrencyCodesSet as I,ISO2CountryCodesSet as S,AmountJSONSchema as A}from"@temboplus/frontend-core";var O,C;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(O||(O={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(C||(C={}));const P=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T=e=>{switch(typeof e){case"undefined":return P.undefined;case"string":return P.string;case"number":return isNaN(e)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(e)?P.array:null===e?P.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?P.promise:"undefined"!=typeof Map&&e instanceof Map?P.map:"undefined"!=typeof Set&&e instanceof Set?P.set:"undefined"!=typeof Date&&e instanceof Date?P.date:P.object;default:return P.unknown}},x=O.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 E extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,n=0;for(;n<a.path.length;){const r=a.path[n];n===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}E.create=e=>new E(e);const k=(e,t)=>{let r;switch(e.code){case x.invalid_type:r=e.received===P.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,O.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:r=`Unrecognized key(s) in object: ${O.joinValues(e.keys,", ")}`;break;case x.invalid_union:r="Invalid input";break;case x.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${O.joinValues(e.options)}`;break;case x.invalid_enum_value:r=`Invalid enum value. Expected ${O.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:r="Invalid function arguments";break;case x.invalid_return_type:r="Invalid function return type";break;case x.invalid_date:r="Invalid date";break;case x.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}"`:O.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case x.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 x.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 x.custom:r="Invalid input";break;case x.invalid_intersection_types:r="Intersection results could not be merged";break;case x.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:r="Number must be finite";break;default:r=t.defaultError,O.assertNever(e)}return{message:r}};let B=k;function D(){return B}const j=e=>{const{data:t,path:r,errorMaps:n,issueData:a}=e,s=[...r,...a.path||[]],i={...a,path:s};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...a,path:s,message:a.message||o}};function R(e,t){const r=j({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,D(),k].filter(e=>!!e)});e.common.issues.push(r)}class J{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return M;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t)r.push({key:await e.key,value:await e.value});return J.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:a}=n;if("aborted"===t.status)return M;if("aborted"===a.status)return M;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"===t.value||void 0===a.value&&!n.alwaysSet||(r[t.value]=a.value)}return{status:e.value,value:r}}}const M=Object.freeze({status:"aborted"}),Z=e=>({status:"dirty",value:e}),L=e=>({status:"valid",value:e}),$=e=>"aborted"===e.status,F=e=>"dirty"===e.status,U=e=>"valid"===e.status,q=e=>"undefined"!=typeof Promise&&e instanceof Promise;var V;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(V||(V={}));class W{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const K=(e,t)=>{if(U(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 E(e.common.issues);return this._error=t,this._error}}};function z(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:a};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=n?n:t.defaultError}:{message:null!=r?r:t.defaultError},description:a}}class G{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 T(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:T(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new J,ctx:{common:e.parent.common,data:e.data,parsedType:T(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(q(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T(e)},a=this._parseSync({data:e,path:n.path,parent:n});return K(n,a)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:T(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(q(n)?n:Promise.resolve(n));return K(r,a)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const a=e(t),s=()=>n.addIssue({code:x.custom,...r(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(e=>!!e||(s(),!1)):!!a||(s(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new Me({schema:this,typeName:He.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Ze.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _e.create(this,this._def)}promise(){return Je.create(this,this._def)}or(e){return Ne.create([this,e],this._def)}and(e){return Oe.create(this,e,this._def)}transform(e){return new Me({...z(this._def),schema:this,typeName:He.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new $e({...z(this._def),innerType:this,defaultValue:t,typeName:He.ZodDefault})}brand(){return new Ve({typeName:He.ZodBranded,type:this,...z(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Fe({...z(this._def),innerType:this,catchValue:t,typeName:He.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return We.create(this,e)}readonly(){return Ke.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const H=/^c[^\s-]{8,}$/i,Q=/^[a-z][a-z0-9]*$/,Y=/[0-9A-HJKMNP-TV-Z]{26}/,X=/^[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,ee=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,te=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,re=/^(((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}))$/,ne=/^(([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})))$/,ae=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 se(e,t){return!("v4"!==t&&t||!re.test(e))||!("v6"!==t&&t||!ne.test(e))}class ie extends G{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:x.invalid_string,...V.errToObj(r)}),this.nonempty=e=>this.min(1,V.errToObj(e)),this.trim=()=>new ie({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new ie({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new ie({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==P.string){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.string,received:t.parsedType}),M}const t=new J;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),R(r,{code:x.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),R(r,{code:x.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const a=e.data.length>n.value,s=e.data.length<n.value;(a||s)&&(r=this._getOrReturnCtx(e,r),a?R(r,{code:x.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):s&&R(r,{code:x.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)ee.test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"email",code:x.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)te.test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"emoji",code:x.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)X.test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"uuid",code:x.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)H.test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"cuid",code:x.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)Q.test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"cuid2",code:x.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)Y.test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"ulid",code:x.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(a){r=this._getOrReturnCtx(e,r),R(r,{validation:"url",code:x.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"regex",code:x.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),R(r,{code:x.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),R(r,{code:x.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),R(r,{code:x.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){ae(n).test(e.data)||(r=this._getOrReturnCtx(e,r),R(r,{code:x.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else"ip"===n.kind?se(e.data,n.version)||(r=this._getOrReturnCtx(e,r),R(r,{validation:"ip",code:x.invalid_string,message:n.message}),t.dirty()):O.assertNever(n);return{status:t.value,value:e.data}}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.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,...V.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...V.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...V.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...V.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...V.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...V.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 oe(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n;return parseInt(e.toFixed(a).replace(".",""))%parseInt(t.toFixed(a).replace(".",""))/Math.pow(10,a)}ie.create=e=>{var t;return new ie({checks:[],typeName:He.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...z(e)})};class ce extends G{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)!==P.number){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.number,received:t.parsedType}),M}let t;const r=new J;for(const n of this._def.checks)if("int"===n.kind)O.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),R(t,{code:x.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:x.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:x.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==oe(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:x.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),R(t,{code:x.not_finite,message:n.message}),r.dirty()):O.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(e,t,r,n){return new ce({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:V.toString(n)}]})}_addCheck(e){return new ce({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.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&&O.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)}}ce.create=e=>new ce({checks:[],typeName:He.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...z(e)});class de extends G{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)!==P.bigint){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.bigint,received:t.parsedType}),M}let t;const r=new J;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:x.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),R(t,{code:x.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),R(t,{code:x.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):O.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(e,t,r,n){return new de({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:V.toString(n)}]})}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.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}}de.create=e=>{var t;return new de({checks:[],typeName:He.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...z(e)})};class ue extends G{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==P.boolean){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.boolean,received:t.parsedType}),M}return L(e.data)}}ue.create=e=>new ue({typeName:He.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...z(e)});class le extends G{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==P.date){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.date,received:t.parsedType}),M}if(isNaN(e.data.getTime())){return R(this._getOrReturnCtx(e),{code:x.invalid_date}),M}const t=new J;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),R(r,{code:x.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),R(r,{code:x.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):O.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new le({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:V.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}}le.create=e=>new le({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:He.ZodDate,...z(e)});class he extends G{_parse(e){if(this._getType(e)!==P.symbol){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.symbol,received:t.parsedType}),M}return L(e.data)}}he.create=e=>new he({typeName:He.ZodSymbol,...z(e)});class pe extends G{_parse(e){if(this._getType(e)!==P.undefined){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.undefined,received:t.parsedType}),M}return L(e.data)}}pe.create=e=>new pe({typeName:He.ZodUndefined,...z(e)});class me extends G{_parse(e){if(this._getType(e)!==P.null){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.null,received:t.parsedType}),M}return L(e.data)}}me.create=e=>new me({typeName:He.ZodNull,...z(e)});class fe extends G{constructor(){super(...arguments),this._any=!0}_parse(e){return L(e.data)}}fe.create=e=>new fe({typeName:He.ZodAny,...z(e)});class ye extends G{constructor(){super(...arguments),this._unknown=!0}_parse(e){return L(e.data)}}ye.create=e=>new ye({typeName:He.ZodUnknown,...z(e)});class ge extends G{_parse(e){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.never,received:t.parsedType}),M}}ge.create=e=>new ge({typeName:He.ZodNever,...z(e)});class ve extends G{_parse(e){if(this._getType(e)!==P.undefined){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.void,received:t.parsedType}),M}return L(e.data)}}ve.create=e=>new ve({typeName:He.ZodVoid,...z(e)});class _e extends G{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==P.array)return R(t,{code:x.invalid_type,expected:P.array,received:t.parsedType}),M;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(e||a)&&(R(t,{code:e?x.too_big:x.too_small,minimum:a?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(R(t,{code:x.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(R(t,{code:x.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new W(t,e,t.path,r)))).then(e=>J.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new W(t,e,t.path,r)));return J.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new _e({...this._def,minLength:{value:e,message:V.toString(t)}})}max(e,t){return new _e({...this._def,maxLength:{value:e,message:V.toString(t)}})}length(e,t){return new _e({...this._def,exactLength:{value:e,message:V.toString(t)}})}nonempty(e){return this.min(1,e)}}function be(e){if(e instanceof we){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Ze.create(be(n))}return new we({...e._def,shape:()=>t})}return e instanceof _e?new _e({...e._def,type:be(e.element)}):e instanceof Ze?Ze.create(be(e.unwrap())):e instanceof Le?Le.create(be(e.unwrap())):e instanceof Ce?Ce.create(e.items.map(e=>be(e))):e}_e.create=(e,t)=>new _e({type:e,minLength:null,maxLength:null,exactLength:null,typeName:He.ZodArray,...z(t)});class we extends G{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=O.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==P.object){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.object,received:t.parsedType}),M}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof ge&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||s.push(e);const i=[];for(const e of a){const t=n[e],a=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new W(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ge){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(R(r,{code:x.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new W(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>J.mergeObjectSync(t,e)):J.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new we({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,a,s,i;const o=null!==(s=null===(a=(n=this._def).errorMap)||void 0===a?void 0:a.call(n,t,r).message)&&void 0!==s?s:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=V.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new we({...this._def,unknownKeys:"strip"})}passthrough(){return new we({...this._def,unknownKeys:"passthrough"})}extend(e){return new we({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new we({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:He.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new we({...this._def,catchall:e})}pick(e){const t={};return O.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new we({...this._def,shape:()=>t})}omit(e){const t={};return O.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new we({...this._def,shape:()=>t})}deepPartial(){return be(this)}partial(e){const t={};return O.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new we({...this._def,shape:()=>t})}required(e){const t={};return O.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Ze;)e=e._def.innerType;t[r]=e}}),new we({...this._def,shape:()=>t})}keyof(){return De(O.objectKeys(this.shape))}}we.create=(e,t)=>new we({shape:()=>e,unknownKeys:"strip",catchall:ge.create(),typeName:He.ZodObject,...z(t)}),we.strictCreate=(e,t)=>new we({shape:()=>e,unknownKeys:"strict",catchall:ge.create(),typeName:He.ZodObject,...z(t)}),we.lazycreate=(e,t)=>new we({shape:e,unknownKeys:"strip",catchall:ge.create(),typeName:He.ZodObject,...z(t)});class Ne extends G{_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 E(e.ctx.common.issues));return R(t,{code:x.invalid_union,unionErrors:r}),M});{let e;const n=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const a=n.map(e=>new E(e));return R(t,{code:x.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}}Ne.create=(e,t)=>new Ne({options:e,typeName:He.ZodUnion,...z(t)});const Ie=e=>e instanceof ke?Ie(e.schema):e instanceof Me?Ie(e.innerType()):e instanceof Be?[e.value]:e instanceof je?e.options:e instanceof Re?Object.keys(e.enum):e instanceof $e?Ie(e._def.innerType):e instanceof pe?[void 0]:e instanceof me?[null]:null;class Se extends G{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.object)return R(t,{code:x.invalid_type,expected:P.object,received:t.parsedType}),M;const r=this.discriminator,n=t.data[r],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(R(t,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=Ie(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of t){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,r)}}return new Se({typeName:He.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...z(r)})}}function Ae(e,t){const r=T(e),n=T(t);if(e===t)return{valid:!0,data:e};if(r===P.object&&n===P.object){const r=O.objectKeys(t),n=O.objectKeys(e).filter(e=>-1!==r.indexOf(e)),a={...e,...t};for(const r of n){const n=Ae(e[r],t[r]);if(!n.valid)return{valid:!1};a[r]=n.data}return{valid:!0,data:a}}if(r===P.array&&n===P.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const a=Ae(e[n],t[n]);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}return r===P.date&&n===P.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class Oe extends G{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if($(e)||$(n))return M;const a=Ae(e.value,n.value);return a.valid?((F(e)||F(n))&&t.dirty(),{status:t.value,value:a.data}):(R(r,{code:x.invalid_intersection_types}),M)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Oe.create=(e,t,r)=>new Oe({left:e,right:t,typeName:He.ZodIntersection,...z(r)});class Ce extends G{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.array)return R(r,{code:x.invalid_type,expected:P.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return R(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(R(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new W(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>J.mergeArray(t,e)):J.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new Ce({...this._def,rest:e})}}Ce.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:e,typeName:He.ZodTuple,rest:null,...z(t)})};class Pe extends G{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!==P.object)return R(r,{code:x.invalid_type,expected:P.object,received:r.parsedType}),M;const n=[],a=this._def.keyType,s=this._def.valueType;for(const e in r.data)n.push({key:a._parse(new W(r,e,r.path,e)),value:s._parse(new W(r,r.data[e],r.path,e))});return r.common.async?J.mergeObjectAsync(t,n):J.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new Pe(t instanceof G?{keyType:e,valueType:t,typeName:He.ZodRecord,...z(r)}:{keyType:ie.create(),valueType:e,typeName:He.ZodRecord,...z(t)})}}class Te extends G{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!==P.map)return R(r,{code:x.invalid_type,expected:P.map,received:r.parsedType}),M;const n=this._def.keyType,a=this._def.valueType,s=[...r.data.entries()].map(([e,t],s)=>({key:n._parse(new W(r,e,r.path,[s,"key"])),value:a._parse(new W(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const n=await r.key,a=await r.value;if("aborted"===n.status||"aborted"===a.status)return M;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const n=r.key,a=r.value;if("aborted"===n.status||"aborted"===a.status)return M;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}}}}Te.create=(e,t,r)=>new Te({valueType:t,keyType:e,typeName:He.ZodMap,...z(r)});class xe extends G{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.set)return R(r,{code:x.invalid_type,expected:P.set,received:r.parsedType}),M;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(R(r,{code:x.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(R(r,{code:x.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function s(e){const r=new Set;for(const n of e){if("aborted"===n.status)return M;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>a._parse(new W(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>s(e)):s(i)}min(e,t){return new xe({...this._def,minSize:{value:e,message:V.toString(t)}})}max(e,t){return new xe({...this._def,maxSize:{value:e,message:V.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}xe.create=(e,t)=>new xe({valueType:e,minSize:null,maxSize:null,typeName:He.ZodSet,...z(t)});class Ee extends G{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.function)return R(t,{code:x.invalid_type,expected:P.function,received:t.parsedType}),M;function r(e,r){return j({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D(),k].filter(e=>!!e),issueData:{code:x.invalid_arguments,argumentsError:r}})}function n(e,r){return j({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D(),k].filter(e=>!!e),issueData:{code:x.invalid_return_type,returnTypeError:r}})}const a={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Je){const e=this;return L(async function(...t){const i=new E([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(s,this,o);return await e._def.returns._def.type.parseAsync(c,a).catch(e=>{throw i.addIssue(n(c,e)),i})})}{const e=this;return L(function(...t){const i=e._def.args.safeParse(t,a);if(!i.success)throw new E([r(t,i.error)]);const o=Reflect.apply(s,this,i.data),c=e._def.returns.safeParse(o,a);if(!c.success)throw new E([n(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ee({...this._def,args:Ce.create(e).rest(ye.create())})}returns(e){return new Ee({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Ee({args:e||Ce.create([]).rest(ye.create()),returns:t||ye.create(),typeName:He.ZodFunction,...z(r)})}}class ke extends G{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})}}ke.create=(e,t)=>new ke({getter:e,typeName:He.ZodLazy,...z(t)});class Be extends G{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return R(t,{received:t.data,code:x.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}}function De(e,t){return new je({values:e,typeName:He.ZodEnum,...z(t)})}Be.create=(e,t)=>new Be({value:e,typeName:He.ZodLiteral,...z(t)});class je extends G{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return R(t,{expected:O.joinValues(r),received:t.parsedType,code:x.invalid_type}),M}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return R(t,{received:t.data,code:x.invalid_enum_value,options:r}),M}return L(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 je.create(e)}exclude(e){return je.create(this.options.filter(t=>!e.includes(t)))}}je.create=De;class Re extends G{_parse(e){const t=O.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==P.string&&r.parsedType!==P.number){const e=O.objectValues(t);return R(r,{expected:O.joinValues(e),received:r.parsedType,code:x.invalid_type}),M}if(-1===t.indexOf(e.data)){const e=O.objectValues(t);return R(r,{received:r.data,code:x.invalid_enum_value,options:e}),M}return L(e.data)}get enum(){return this._def.values}}Re.create=(e,t)=>new Re({values:e,typeName:He.ZodNativeEnum,...z(t)});class Je extends G{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.promise&&!1===t.common.async)return R(t,{code:x.invalid_type,expected:P.promise,received:t.parsedType}),M;const r=t.parsedType===P.promise?t.data:Promise.resolve(t.data);return L(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Je.create=(e,t)=>new Je({type:e,typeName:He.ZodPromise,...z(t)});class Me extends G{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===He.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:e=>{R(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){const e=n.transform(r.data,a);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(e).then(e=>this._def.schema._parseAsync({data:e,path:r.path,parent:r})):this._def.schema._parseSync({data:e,path:r.path,parent:r})}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?M:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?M:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!U(e))return e;const s=n.transform(e.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>U(e)?Promise.resolve(n.transform(e.value,a)).then(e=>({status:t.value,value:e})):e)}O.assertNever(n)}}Me.create=(e,t,r)=>new Me({schema:e,typeName:He.ZodEffects,effect:t,...z(r)}),Me.createWithPreprocess=(e,t,r)=>new Me({schema:t,effect:{type:"preprocess",transform:e},typeName:He.ZodEffects,...z(r)});class Ze extends G{_parse(e){return this._getType(e)===P.undefined?L(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ze.create=(e,t)=>new Ze({innerType:e,typeName:He.ZodOptional,...z(t)});class Le extends G{_parse(e){return this._getType(e)===P.null?L(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(e,t)=>new Le({innerType:e,typeName:He.ZodNullable,...z(t)});class $e extends G{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===P.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}$e.create=(e,t)=>new $e({innerType:e,typeName:He.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...z(t)});class Fe extends G{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return q(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Fe.create=(e,t)=>new Fe({innerType:e,typeName:He.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...z(t)});class Ue extends G{_parse(e){if(this._getType(e)!==P.nan){const t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:P.nan,received:t.parsedType}),M}return{status:"valid",value:e.data}}}Ue.create=e=>new Ue({typeName:He.ZodNaN,...z(e)});const qe=Symbol("zod_brand");class Ve extends G{_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 We extends G{_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?M:"dirty"===e.status?(t.dirty(),Z(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?M:"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 We({in:e,out:t,typeName:He.ZodPipeline})}}class Ke extends G{_parse(e){const t=this._def.innerType._parse(e);return U(t)&&(t.value=Object.freeze(t.value)),t}}Ke.create=(e,t)=>new Ke({innerType:e,typeName:He.ZodReadonly,...z(t)});const ze=(e,t={},r)=>e?fe.create().superRefine((n,a)=>{var s,i;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(i=null!==(s=e.fatal)&&void 0!==s?s:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;a.addIssue({code:"custom",...c,fatal:o})}}):fe.create(),Ge={object:we.lazycreate};var He;!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"}(He||(He={}));const Qe=ie.create,Ye=ce.create,Xe=Ue.create,et=de.create,tt=ue.create,rt=le.create,nt=he.create,at=pe.create,st=me.create,it=fe.create,ot=ye.create,ct=ge.create,dt=ve.create,ut=_e.create,lt=we.create,ht=we.strictCreate,pt=Ne.create,mt=Se.create,ft=Oe.create,yt=Ce.create,gt=Pe.create,vt=Te.create,_t=xe.create,bt=Ee.create,wt=ke.create,Nt=Be.create,It=je.create,St=Re.create,At=Je.create,Ot=Me.create,Ct=Ze.create,Pt=Le.create,Tt=Me.createWithPreprocess,xt=We.create,Et={string:e=>ie.create({...e,coerce:!0}),number:e=>ce.create({...e,coerce:!0}),boolean:e=>ue.create({...e,coerce:!0}),bigint:e=>de.create({...e,coerce:!0}),date:e=>le.create({...e,coerce:!0})},kt=M;var Bt=Object.freeze({__proto__:null,defaultErrorMap:k,setErrorMap:function(e){B=e},getErrorMap:D,makeIssue:j,EMPTY_PATH:[],addIssueToContext:R,ParseStatus:J,INVALID:M,DIRTY:Z,OK:L,isAborted:$,isDirty:F,isValid:U,isAsync:q,get util(){return O},get objectUtil(){return C},ZodParsedType:P,getParsedType:T,ZodType:G,ZodString:ie,ZodNumber:ce,ZodBigInt:de,ZodBoolean:ue,ZodDate:le,ZodSymbol:he,ZodUndefined:pe,ZodNull:me,ZodAny:fe,ZodUnknown:ye,ZodNever:ge,ZodVoid:ve,ZodArray:_e,ZodObject:we,ZodUnion:Ne,ZodDiscriminatedUnion:Se,ZodIntersection:Oe,ZodTuple:Ce,ZodRecord:Pe,ZodMap:Te,ZodSet:xe,ZodFunction:Ee,ZodLazy:ke,ZodLiteral:Be,ZodEnum:je,ZodNativeEnum:Re,ZodPromise:Je,ZodEffects:Me,ZodTransformer:Me,ZodOptional:Ze,ZodNullable:Le,ZodDefault:$e,ZodCatch:Fe,ZodNaN:Ue,BRAND:qe,ZodBranded:Ve,ZodPipeline:We,ZodReadonly:Ke,custom:ze,Schema:G,ZodSchema:G,late:Ge,get ZodFirstPartyTypeKind(){return He},coerce:Et,any:it,array:ut,bigint:et,boolean:tt,date:rt,discriminatedUnion:mt,effect:Ot,enum:It,function:bt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>ze(t=>t instanceof e,t),intersection:ft,lazy:wt,literal:Nt,map:vt,nan:Xe,nativeEnum:St,never:ct,null:st,nullable:Pt,number:Ye,object:lt,oboolean:()=>tt().optional(),onumber:()=>Ye().optional(),optional:Ct,ostring:()=>Qe().optional(),pipeline:xt,preprocess:Tt,promise:At,record:gt,set:_t,strictObject:ht,string:Qe,symbol:nt,transformer:Ot,tuple:yt,undefined:at,union:pt,unknown:ot,void:dt,NEVER:kt,ZodIssueCode:x,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:E});const Dt=e=>"function"==typeof(null==e?void 0:e.passthrough),jt=Bt.object({name:Bt.literal("ZodError"),issues:Bt.array(Bt.object({path:Bt.array(Bt.union([Bt.string(),Bt.number()])),message:Bt.string().optional(),code:Bt.nativeEnum(Bt.ZodIssueCode)}).catchall(Bt.any()))});class Rt 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}}Bt.object({message:Bt.literal("Request validation failed"),pathParameterErrors:jt.nullable(),headerErrors:jt.nullable(),queryParameterErrors:jt.nullable(),bodyErrors:jt.nullable()}),Bt.object({pathParameterErrors:jt.nullable(),headerErrors:jt.nullable(),queryParameterErrors:jt.nullable(),bodyErrors:jt.nullable()}),Bt.object({paramsResult:jt.nullable(),headersResult:jt.nullable(),queryResult:jt.nullable(),bodyResult:jt.nullable()});const Jt="zod-ts-rest-polyfill",Mt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof we&&t instanceof we){return n=t,Dt(r=e)?Dt(n)?r.merge(n):r:Dt(n)?n:Object.assign({},r,n)}var r,n;return{...e,...t}},Zt=Symbol("ContractNoBody"),Lt=e=>"method"in e&&"path"in e,$t=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s;return Lt(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:Mt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(a=r.validateResponseOnClient)&&void 0!==a?a:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,$t(r,t)]})),Ft=Symbol("ContractPlainType"),Ut=()=>({router:(e,t)=>$t(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Ft,body:()=>Ft,type:()=>Ft,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>Zt}),qt=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("&"):"",Vt=e=>e?Object.keys(e).flatMap(t=>Wt(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",Wt=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>Wt(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>Wt(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Kt extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const zt=async({route:e,path:t,method:r,headers:n,body:a,validateResponse:s,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:n,body:a}),c=o.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t=e.responses[o.status],r={status:o.status,body:t===Zt?void 0:await o.json(),headers:o.headers},n=(e=>{if((e=>{if(!e)return!1;const t=null==e?void 0:e["~standard"];return!!t&&1===t.version&&"function"==typeof t.validate})(e))return e;if("function"==typeof(null==(t=e)?void 0:t.safeParse)){const t={vendor:Jt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(n&&(null!=s?s:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const n=t["~standard"].validate(e);if(n instanceof Promise)throw new Error("Schema validation must be synchronous");return n.issues?t["~standard"].vendor===Jt?{error:new E(n.issues)}:{error:new Rt(n.issues)}:r&&"object"==typeof e&&n.value?{value:{...e,...n.value}}:{value:n.value}})(r.body,n);if(e.error)throw e.error;return{...r,body:e.value}}return r}return(null==c?void 0:c.includes("text/"))?{status:o.status,body:await o.text(),headers:o.headers}:{status:o.status,body:await o.blob(),headers:o.headers}},Gt=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},Ht=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),Qt=(e,t,r,n,a)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?qt(e):Vt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return t.endsWith("/")&&s.startsWith("/")?`${t}${s.substring(1)}${i}`:`${t}${s}${i}`},Yt=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:s,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:d,cache:u,next:l,...h}=r||{},p={...t,...c},m="object"==typeof a?Object.fromEntries(Object.entries(a).map(([e,t])=>[e,String(t)])):{};return{path:Qt(n,p.baseUrl,m,e,!!p.jsonQuery),clientArgs:p,route:e,body:s,query:n,extraInputArgs:h,fetchOptions:{...u&&{cache:u},...l&&{next:l},...d},headers:{...o,...i}}})(e,t,n),s=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:s,extraInputArgs:i,headers:o,fetchOptions:c}=e,d=r.api||zt,u=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...u&&Ht(u),...Ht(o)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let h={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:a,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:a instanceof FormData?a:Gt(a)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(a)})),d({...h,...i})})(a);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new Kt(s,r)}},Xt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>Lt(r)?[e,Yt(r,t)]:[e,Xt(r,t)]));class er 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 er.schema.safeParse(e).success}static unknown(e){return new er({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return r.object({message:r.string(),statusCode:r.number().int(),error:r.string().optional(),details:r.object({}).optional()})}}let tr;const rr=e=>{tr=e};class nr{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(tr){const e=tr();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()}};return Xt(this.contract,t)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,r){if(e.status===r)return e.body;if(401===e.status)throw new er({message:"You are not authenticated to perform this action. Please login again",statusCode:401,error:"UNAUTHORIZED"});if(403===e.status)throw new er({message:"You are not authorized to perform this action.",statusCode:403,error:"FORBIDDEN"});if(404===e.status)throw new er({message:"The requested resource was not found.",statusCode:404,error:"NOT_FOUND"});const n=t.object({statusCode:t.number(),message:t.string(),error:t.string(),details:t.record(t.string(),t.string()).optional()}).safeParse(e.body);if(n.success)throw new er(n.data);const a=e.status||502;throw new er({message:`We encountered an error trying to process your request. Please try again later (upstream status ${a}).`,statusCode:a,error:"UNKNOWN_ERROR"})}}const ar={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 sr 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 t=r.union([r.enum(Object.values(ar.Profile)),r.enum(Object.values(ar.Beneficiary)),r.enum(Object.values(ar.Payment)),r.enum(Object.values(ar.Payout)),r.enum(Object.values(ar.Transfer)),r.enum(Object.values(ar.Wallet))]);return r.object({name:r.literal("PermissionError").nullish(),message:r.string(),requiredPermissions:r.array(t)}).safeParse(e).success}}function ir(e){const t=e;return t&&"string"==typeof t.stack&&"string"==typeof t.message}class or{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 or(this.page+1,this.limit,this.total):null}prevPage(){return this.hasPrev?new or(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}}}function cr(e,t,r,n){return{results:e,pagination:new or(t,r,n)}}function dr(e=1,t=10){return{results:[],pagination:new or(e,t,0)}}const ur=r.object({page:r.coerce.number().int().min(1).default(1),limit:r.coerce.number().int().min(1).max(100).default(10)}),lr=r.object({page:r.number().int().min(1),limit:r.number().int().min(1),total:r.number().int().min(0),totalPages:r.number().int().min(0),hasNext:r.boolean(),hasPrev:r.boolean()});function hr(e){return r.object({results:r.array(e),pagination:lr})}var pr,mr;!function(e){e.EQUALS="eq",e.NOT_EQUALS="neq",e.LESS_THAN="lt",e.LESS_THAN_OR_EQUAL="lte",e.GREATER_THAN="gt",e.GREATER_THAN_OR_EQUAL="gte",e.LIKE="like",e.LIKE_LOWER="likeLower",e.IS_NULL="isNull",e.IS_NOT_NULL="isNotNull",e.IN="in"}(pr||(pr={})),function(e){e.ASC="asc",e.DESC="desc"}(mr||(mr={}));const fr=Symbol("query-builder-type");class yr{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}}[fr]="query-builder";static is(e){return null!==e&&"object"==typeof e&&fr in e&&"query-builder"===e[fr]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:pr.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:pr.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:pr.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:pr.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:pr.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:pr.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:pr.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:pr.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:pr.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:pr.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:pr.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:pr.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:pr.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:pr.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=gr(e);this.whereGreaterThanOrEqual("createdAt",t)}if(t){const e=gr(t);this.whereLessThanOrEqual("createdAt",e)}return this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=mr.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,mr.ASC)}orderByDesc(e){return this.orderBy(e,mr.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 pr.IS_NULL:e[`${t.field}:isNull`]=1;break;case pr.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case pr.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case pr.LIKE:e[`${t.field}:like`]=t.value;break;case pr.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case pr.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case pr.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===mr.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 yr(e)}}function gr(e){return"string"==typeof e?e:new Date(e.getTime()).toISOString()}const vr={profileDTOSchema:r.object({id:r.string(),firstName:r.string().nullish(),lastName:r.string().nullish(),displayName:r.string(),phone:r.string().nullish(),accountNo:r.string().min(1),email:r.string().email().nullish(),autoApprove:r.boolean().nullish()})},_r={logInRequestDTO:r.object({type:r.string().default("password"),identity:r.string().email(),password:r.string()}),logInResponseDTO:r.object({profile:vr.profileDTOSchema,token:r.string(),access:r.array(r.string()),resetPassword:r.boolean()}),accessResponseDTO:r.array(r.string()),resetPasswordRequestDTO:r.object({currentPassword:r.string(),newPassword:r.string()}),emptyResponseDTO:r.object({})},br={loginDTO:t.object({id:t.string().min(1,"ID is required"),profileId:t.string().min(1,"Profile ID is required"),name:t.string().min(1,"Name is required"),identity:t.string().email("Identity must be a valid email address"),type:t.string().min(1,"Type is required"),roleId:t.string().min(1,"Role ID is required"),isActive:t.boolean(),isArchived:t.boolean(),resetPassword:t.boolean(),createdAt:t.string().datetime("Invalid creation timestamp"),updatedAt:t.string().datetime("Invalid update timestamp"),access:t.array(t.string())})},wr=r.object({id:r.string(),profileId:r.string(),name:r.string(),identity:r.string(),type:r.string(),roleId:r.string(),isActive:r.boolean(),isArchived:r.boolean(),resetPassword:r.boolean(),createdAt:r.string(),updatedAt:r.string(),access:r.array(r.string()),_version:r.string().optional().default("1.0")});class Nr{_id;_profileId;_name;_identity;_type;_roleId;_isActive;_isArchived;_resetPassword;_createdAt;_updatedAt;_access;_permissionMap;constructor(e,t,r,n,a,s,i,o,c,d,u,l){this._id=e,this._profileId=t,this._name=r,this._identity=n,this._type=a,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=br.loginDTO.parse(e);return new Nr(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=wr.safeParse(t);if(!r.success)return void console.error("Invalid LogInJSON:",r.error.flatten());const n=r.data;return Nr.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 wr.safeParse(e).success}}const Ir=r.object({id:r.string(),firstName:r.string().nullable().optional(),lastName:r.string().nullable().optional(),displayName:r.string(),phone:r.string().nullable().optional(),accountNo:r.string(),email:r.string().nullable().optional(),autoApprove:r.boolean().nullable().optional(),_version:r.string().optional().default("1.0")});class Sr{_id;_firstName;_lastName;_displayName;_phone;_accountNo;_email;_autoApprove;static get schema(){return vr.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 Sr({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 Sr.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?Sr.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=Ir.safeParse(t);if(!r.success)return void console.error("Invalid ProfileJSON:",r.error.flatten());const n=r.data;return Sr.from(n)}catch(e){return void console.error("Error parsing ProfileJSON:",e)}}static isProfileJSON(e){return Ir.safeParse(e).success}}const Ar=t.object({id:t.string(),name:t.string(),description:t.string().nullable().optional(),access:t.array(t.string()),createdAt:t.string(),updatedAt:t.string(),_version:t.string().optional().default("1.0")});class Or{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 Or(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=Ar.safeParse(t);if(!r.success)return void console.error("Invalid RoleJSON:",r.error.flatten());const n=r.data;return Or.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 Ar.safeParse(e).success}}const Cr=t.object({companyProfile:Ir,role:Ar.optional(),_version:t.string().optional().default("1.0")});class Pr{_companyProfile;_role;constructor(e){this._companyProfile=e.companyProfile,this._role=e.role}static from(e){try{return Sr.is(e.companyProfile)?new Pr(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=Cr.safeParse(t);if(!r.success)return void console.error("Invalid CompanyMembershipJSON:",r.error.flatten());const n=r.data,a=Sr.fromJSON(n.companyProfile),s=n.role?Or.fromJSON(n.role):void 0;return a?Pr.from({companyProfile:a,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 Cr.safeParse(e).success}}const Tr=t.object({logIn:wr,companyProfile:Ir,role:Ar.optional(),_version:t.string().optional().default("1.0")});class xr{_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=Pr.from({companyProfile:e.companyProfile,role:e.role});return t?new xr({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=Tr.safeParse(t);if(!r.success)return void console.error("Invalid UserJSON:",r.error.flatten());const n=r.data,a=Nr.fromJSON(n.logIn),s=Sr.fromJSON(n.companyProfile),i=n.role?Or.fromJSON(n.role):void 0;if(!a||!s)return void console.error("Failed to reconstruct nested objects from UserJSON");const o=Pr.from({companyProfile:s,role:i});return o?new xr({logIn:a,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 Tr.safeParse(e).success}}const Er=Ut().router({getUserCredentials:{method:"GET",path:"/me",responses:{200:br.loginDTO}}});class kr extends nr{constructor(e){super("login",Er,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 Br=r.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"),Dr=r.object({id:r.string().min(1),name:r.string().min(1,"Role name is required"),description:r.string().nullable().optional(),access:r.array(r.string()),createdAt:r.string().datetime("Invalid creation timestamp"),updatedAt:r.string().datetime("Invalid update timestamp")}),jr=r.object({id:r.string().min(1),name:r.string().min(1,"Team member name is required"),identity:r.string().email("Invalid email address"),type:r.string().min(1,"Team member type is required"),profileId:r.string().min(1,"Profile ID is required"),roleId:r.string().min(1,"Role ID is required"),resetPassword:r.boolean(),isActive:r.boolean(),isArchived:r.boolean(),role:Dr.optional(),createdAt:r.string().datetime("Invalid creation timestamp"),updatedAt:r.string().datetime("Invalid update timestamp")}),Rr={role:Dr,teamMember:jr,teamMemberQueryParams:r.object({id:r.string().min(1).optional(),name:r.string().min(1).optional(),identity:r.string().email("Invalid email address").optional(),type:r.string().min(1).optional(),profileId:r.string().min(1).optional(),roleId:r.string().min(1).optional(),resetPassword:r.number().optional(),isActive:r.number().optional(),isArchived:r.number().optional(),createdAt:r.string().datetime("Invalid creation timestamp").optional(),updatedAt:r.string().datetime("Invalid update timestamp").optional(),eager:r.string().optional()}),createTeamMemberRequest:r.object({name:r.string().min(1,"Team member name is required"),identity:r.string().email("Valid email address is required"),password:Br.optional(),roleId:r.string().optional(),resetPassword:r.boolean().optional()}),updateTeamMemberRequest:r.object({name:r.string().min(1,"Team member name cannot be empty").optional(),roleId:r.string().min(1,"Role ID cannot be empty").optional(),password:Br.optional(),resetPassword:r.boolean().optional(),isActive:r.boolean().optional()}),resetPasswordRequest:r.object({newPassword:Br.optional(),sendNotification:r.boolean().optional()}),createTeamMemberResponse:r.object({id:r.string(),name:r.string(),identity:r.string(),type:r.string(),profileId:r.string(),resetPassword:r.boolean(),roleId:r.string(),isActive:r.boolean(),isArchived:r.boolean(),createdAt:r.string().datetime(),updatedAt:r.string().datetime()}),password:Br},Jr=Ut().router({getTeamMembers:{method:"GET",path:"/login",query:Rr.teamMemberQueryParams,responses:{200:r.array(Rr.teamMember),401:r.object({message:r.string().optional()}),403:r.object({message:r.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:r.object({id:r.string()}),query:Rr.teamMemberQueryParams,responses:{200:Rr.teamMember,401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()}),404:r.object({message:r.string().optional()})},summary:"Get team member details",description:"Retrieve detailed information about a specific team member"},createTeamMember:{method:"POST",path:"/login",body:Rr.createTeamMemberRequest,responses:{201:Rr.createTeamMemberResponse,400:r.object({message:r.string().optional(),errors:r.array(r.string()).optional()}),401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()}),409:r.object({message:r.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:r.object({id:r.string()}),body:Rr.updateTeamMemberRequest,responses:{200:Rr.teamMember,400:r.object({message:r.string().optional(),errors:r.array(r.string()).optional()}),401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()}),404:r.object({message:r.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:r.object({id:r.string()}),body:r.object({}),responses:{201:Rr.teamMember,401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()}),404:r.object({message:r.string().optional()}),409:r.object({message:r.string().optional()})},summary:"Archive team member",description:"Archive (soft delete) a team member account"},unArchiveTeamMember:{method:"POST",path:"/login/:id/unarchive",pathParams:r.object({id:r.string()}),body:r.object({}),responses:{201:Rr.teamMember,401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()}),404:r.object({message:r.string().optional()}),409:r.object({message:r.string().optional()})},summary:"Unarchive team member",description:"Unarchive a previously archived team member account"},resetPassword:{method:"POST",path:"/login/:id/reset-password",pathParams:r.object({id:r.string()}),body:Rr.resetPasswordRequest,responses:{201:r.object({success:r.boolean()}),400:r.object({message:r.string().optional()}),401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()}),404:r.object({message:r.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:r.array(Rr.role),401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()})},summary:"List all roles",description:"Retrieve a list of all available roles in the system"},getRole:{method:"GET",path:"/role/:id",pathParams:r.object({id:r.string()}),responses:{200:Rr.role,401:r.object({message:r.string().optional()}),403:r.object({message:r.string().optional()}),404:r.object({message:r.string().optional()})},summary:"Get role details",description:"Retrieve detailed information about a specific role"}}),Mr=t.object({id:t.string(),name:t.string(),identity:t.string(),type:t.string(),profileId:t.string(),roleId:t.string(),resetPassword:t.boolean(),isActive:t.boolean(),isArchived:t.boolean(),role:Ar.optional(),createdAt:t.string(),updatedAt:t.string(),_version:t.string().optional().default("1.0")});class Zr{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 Or(e.role)}catch(e){}}static from(e){try{return e?.id&&e?.name&&e?.identity&&e?.roleId?new Zr(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 Zr.from(t)}catch(e){return void console.error("Error parsing TeamMember JSON:",e)}}static createMany(e){return e.map(e=>Zr.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=Mr.safeParse(t);if(!r.success)return void console.error("Invalid TeamMemberJSON:",r.error.flatten());const n=r.data,a=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 Zr.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:a,createdAt:n.createdAt,updatedAt:n.updatedAt})}catch(e){return void console.error("Error parsing TeamMemberJSON:",e)}}static isTeamMemberJSON(e){return Mr.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>Zr.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 Lr extends nr{constructor(e){super("admin",Jr,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),a=Zr.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async archiveTeamMember(e){const t=await this.client.archiveTeamMember({params:{id:e},body:{}}),r=this.handleResponse(t,201),n=Zr.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=Zr.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 Zr.createMany(r)}async getTeamMember(e,t={eager:"roleId"}){const r=await this.client.getTeamMember({params:{id:e},query:t}),n=this.handleResponse(r,200),a=Zr.from(n);if(!a)throw new Error("Invalid team member data received from server");return a}async getAllRoles(){const e=await this.client.getRoles();return this.handleResponse(e,200).map(e=>{const t=Or.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=Or.from(r);if(!n)throw new Error("Invalid role data received from server");return n}}const $r=Ut().router({logIn:{method:"POST",path:"/login",body:_r.logInRequestDTO,responses:{201:_r.logInResponseDTO,400:_r.emptyResponseDTO}},access:{method:"GET",path:"/access",responses:{200:_r.accessResponseDTO}},resetPassword:{method:"PUT",path:"/password",body:_r.resetPasswordRequestDTO,responses:{200:_r.emptyResponseDTO,400:_r.emptyResponseDTO}}});class Fr extends nr{constructor(e){super("auth",$r,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 er({message:"Invalid email or password",statusCode:400});if(201===n.status){const e=n.body.token,t=new kr({token:e}),r=await t.getIdentity(),a=Nr.from(r);if(!a)throw new er({message:"Failed to construct login credentials",statusCode:502});const s=n.body.profile,i=Sr.from(s);if(!i)throw new er({message:"Failed to construct user profile",statusCode:502});let o;if(a.can(ar.Role.ViewRole))try{const t=new Lr({token:e});o=await t.getRole(a.roleId)}catch(e){console.warn("Failed to fetch role details:",e)}const c=xr.from({logIn:a,companyProfile:i,role:o});if(!c)throw new er({message:"Failed to construct user session",statusCode:502});return{token:e,user:c}}throw new er({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 er({message:"Invalid current password",statusCode:400});throw new er({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}`)}}var Ur;!function(e){e.BANK="Bank",e.MOBILE="Mobile"}(Ur||(Ur={}));const qr=r.nativeEnum(Ur),Vr=r.object({displayName:r.string().min(1,"Display name is required"),accountNo:r.string().min(1,"Account number is required"),channel:r.string().min(1,"Channel is required"),type:qr}),Wr={beneficiaryDTO:r.object({id:r.string().min(1,"Beneficiary id is required"),profileId:r.string(),createdAt:r.string().datetime(),updatedAt:r.string().datetime()}).merge(Vr),beneficiaryInputDTO:Vr,beneficiaryType:qr},Kr=Ut().router({createBeneficiary:{method:"POST",path:"/",body:Wr.beneficiaryInputDTO,responses:{201:Wr.beneficiaryDTO}},editBeneficiary:{method:"PATCH",path:"/:id",body:Wr.beneficiaryInputDTO,responses:{200:Wr.beneficiaryDTO}},getBeneficiaries:{method:"GET",path:"/",query:r.object({orderByDesc:r.string()}),responses:{200:r.array(Wr.beneficiaryDTO)}},getByID:{method:"GET",path:"/:id",responses:{200:Wr.beneficiaryDTO}},deleteBeneficiary:{method:"DELETE",path:"/:id",body:r.object({}),responses:{200:r.object({})}}}),zr=r.object({type:r.literal(Ur.MOBILE),name:r.string().min(1),phoneNumber:a,mnoId:n,_version:r.string().optional().default("1.0")}),Gr=r.object({type:r.literal(Ur.BANK),accName:r.string().min(1),swiftCode:r.union([i,o]),countryCode:s,accNo:r.string().min(1),_version:r.string().optional().default("1.0")}),Hr=r.discriminatedUnion("type",[zr,Gr]);class Qr extends Error{context;constructor(e,t={}){super(e),this.context=t,this.name="BeneficiaryError"}}class Yr{type;countryCode;constructor(e,t){this.type=e,this.countryCode=t}toJSONString(){return JSON.stringify(this.toJSON())}get isMobile(){return this.type===Ur.MOBILE}get isBank(){return this.type===Ur.BANK}get displayName(){return this.accountName}}class Xr extends Yr{name;phoneNumber;mnoId;constructor(e,t,r){super(Ur.MOBILE,t.countryCode),this.name=e,this.phoneNumber=t;const n=Xr.resolveMnoId(t,r),a=Xr.checkInputs(e,t,n);if(!a.isValid)throw new Qr(a.errors[0],{operation:"constructor",countryCode:t.countryCode,phoneNumber:t.e164Format,mnoId:n});this.mnoId=n}static resolveMnoId(e,t){return c.requiresExplicitProvider(e.countryCode)?t:c.detectProviderByPhoneNumber(e)?.id}static checkInputs(e,t,r){const n=[];return e?.trim()||n.push("Name is required and cannot be empty"),t?.validate()||n.push("Invalid phone number"),r?c.validateProviderForPhoneNumber(t,r)||n.push(`Invalid MNO ${r} for phone number ${t.e164Format}`):n.push(c.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 r=Xr.pickMnoIdFromPayoutChannel(e.countryCode,t);if(r)return r;if(c.requiresExplicitProvider(e.countryCode)){if("string"!=typeof t)return;return c.isProviderSupported(e.countryCode,t)?t:void console.warn(`Invalid MNO ${t} for country ${e.countryCode}`)}const n=c.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[r,n,a]=t.split("-");return"B2C"===a&&"BANK"!==n&&r===e&&c.isProviderSupported(e,n)?n:void 0}static from(e){try{return new Xr(e.name,e.phoneNumber,e.mnoId)}catch(e){return void console.error("Failed to create MobileBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==Ur.MOBILE)return;const t=e.accountNo.startsWith("+")?e.accountNo:`+${e.accountNo}`,r=d.from(t);if(!r)return void console.error(`Failed to parse phone number ${t}`);const n=Xr.pickMnoIdFromDTO(r,e.channel);return n?Xr.from({name:e.displayName,phoneNumber:r,mnoId:n}):void 0}static fromBeneficiaryDTO(e){return Xr.fromInputDTO(e)}static fromPayoutDTO(e){if(!u.isISO2Code(e.countryCode))return void console.error(`Invalid country code: ${e.countryCode}`);const t=d.from(e.msisdn,{defaultCountry:e.countryCode});if(!t)return void console.error(`Failed to parse phone number: ${e.msisdn}`);const r=Xr.pickMnoIdFromDTO(t,e.channel);return r?Xr.from({name:e.payeeName,phoneNumber:t,mnoId:r}):void 0}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===Ur.MOBILE&&(!("string"!=typeof t.name||!t.name.trim())&&(!!d.is(t.phoneNumber)&&("string"==typeof t.mnoId&&c.isProviderSupported(t.phoneNumber.countryCode,t.mnoId))))}validate(){return Xr.checkInputs(this.name,this.phoneNumber,this.mnoId).isValid}getValidationDetails(){return Xr.checkInputs(this.name,this.phoneNumber,this.mnoId)}get accountName(){return this.name}get accountNumber(){return this.phoneNumber.getWithFormat(l.E164)}get accountNameLabel(){return"Name"}get accountNumberLabel(){return"Phone Number"}get channelLabel(){return"Channel"}get channelId(){return this.mnoId}get channelName(){const e=c.findById(this.mnoId,this.countryCode);return e?.mobileMoneyServiceName??e?.displayName??this.mnoId}get mobileMoneyProvider(){return c.findById(this.mnoId,this.countryCode)}toJSON(){return{type:Ur.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,r=zr.safeParse(t);if(!r.success)return void console.error("Invalid MobileBeneficiaryJSON:",r.error.flatten());const n=d.from(r.data.phoneNumber);if(!n)return;return Xr.from({name:r.data.name,phoneNumber:n,mnoId:r.data.mnoId})}catch(e){return void console.error("Error parsing MobileBeneficiaryJSON:",e)}}static fromJSONString(e){return Xr.fromJSON(e)}static isJSON(e){return zr.safeParse(e).success}}class en extends Yr{accName;bank;accNo;constructor(e,t,r){super(Ur.BANK,t.countryCode),this.accName=e,this.bank=t,this.accNo=r;const n=en.checkInputs(e,t,r);if(!n.isValid)throw new Qr(n.errors[0],{operation:"constructor",countryCode:t.countryCode})}static checkInputs(e,t,r){const n=[];return h.validateAccountName(e)||n.push("Invalid account name"),p.is(t)?h.validateAccountNumber(r,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 en(e.accName,e.bank,e.accNo)}catch(e){return void console.error("Failed to create BankBeneficiaryInfo:",e)}}static fromInputDTO(e){if(e.type!==Ur.BANK)return;const t=e.channel;if(!t||"string"!=typeof t)return void console.error("SWIFT code is required for bank beneficiaries");const r=h.getCountryFromSwiftCode(t);if(!r)return void console.error(`Could not identify country from SWIFT code: ${t}`);const n=p.fromBIC(t,r);if(n)return en.from({accName:e.displayName,bank:n,accNo:e.accountNo});console.error(`Bank with SWIFT code ${t} not found`)}static fromBeneficiaryDTO(e){return en.fromInputDTO(e)}static fromPayoutDTO(e){if(!u.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[r,n]=t,a=p.fromBIC(r,e.countryCode);if(a)return en.from({accName:e.payeeName,bank:a,accNo:n});console.error(`Bank with SWIFT code ${r} not found`)}static is(e){if(!e||"object"!=typeof e)return!1;const t=e;return t.type===Ur.BANK&&("string"==typeof t.accName&&("string"==typeof t.accNo&&(!!p.is(t.bank)&&(h.validateAccountName(t.accName)&&h.validateAccountNumber(t.accNo,t.bank.countryCode)))))}validate(){return en.checkInputs(this.accName,this.bank,this.accNo).isValid}getValidationDetails(){return en.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:Ur.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,r=Gr.safeParse(t);if(!r.success)return void console.error("Invalid BankBeneficiaryJSON:",r.error.flatten());const n=r.data;if(!u.isISO2Code(n.countryCode))return;const a=p.fromBIC(n.swiftCode,n.countryCode);if(!a)return;return en.from({accName:n.accName,bank:a,accNo:n.accNo})}catch(e){return void console.error("Error parsing BankBeneficiaryJSON:",e)}}static fromJSONString(e){return en.fromJSON(e)}static isJSON(e){return Gr.safeParse(e).success}}class tn{static fromInputDTO(e){return tn.fromDTO(e)}static fromBeneficiaryDTO(e){return tn.fromDTO(e)}static fromPayoutDTO(e){return e.msisdn.includes(":")?en.fromPayoutDTO(e):Xr.fromPayoutDTO(e)}static fromJSON(e){try{const t="string"==typeof e?JSON.parse(e):e,r=Hr.safeParse(t);if(!r.success)return;return r.data.type===Ur.MOBILE?Xr.fromJSON(r.data):en.fromJSON(r.data)}catch{return}}static fromJSONString(e){return tn.fromJSON(e)}static is(e){return Xr.is(e)||en.is(e)}static isJSON(e){return Hr.safeParse(e).success}static fromDTO(e){return e.type===Ur.MOBILE?Xr.fromInputDTO(e):en.fromInputDTO(e)}}const rn={fromInputDTO:e=>tn.fromInputDTO(e),fromBeneficiaryDTO:e=>tn.fromBeneficiaryDTO(e),fromPayoutDTO:e=>tn.fromPayoutDTO(e),fromJSON:e=>tn.fromJSON(e),fromJSONString:e=>tn.fromJSONString(e),is:e=>tn.is(e),isJSON:e=>tn.isJSON(e)},nn=Wr.beneficiaryDTO.extend({_version:r.string().optional().default("1.0")});class an{_id;_profileId;_displayName;_accountNo;_channel;_type;_createdAt;_updatedAt;_info;_infoComputed=!1;constructor(e){const t=Wr.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=tn.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===Ur.MOBILE?"Phone Number":this.type===Ur.BANK?"Bank Account Number":"Account Number"}get channelLabel(){return this.type===Ur.MOBILE?"Channel":this.type===Ur.BANK?"Bank":"Channel"}get accNameLabel(){return this.type===Ur.MOBILE?"Full Name":this.type===Ur.BANK?"Bank Account Name":"Display Name"}get channelName(){return this.info?.channelName??""}static from(e){try{return new an(e)}catch(e){return void console.error("Failed to create Beneficiary:",e)}}static create(e){return new an(e)}static createMany(e){return e.map(e=>new an(e))}static createSafe(e){return an.from(e)??null}static canConstruct(e){return Wr.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 nn.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=nn.safeParse(r);if(!n.success)return void console.error("Invalid BeneficiaryJSON:",n.error.flatten());const a=n.data,{_version:s,...i}=a;return an.from(i)}catch(e){return void console.error("Error parsing BeneficiaryJSON:",e)}}static fromJSONString(e){return an.fromJSON(e)}static isBeneficiaryJSON(e){return nn.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 sn{canHandle(e){return e.type===Ur.MOBILE&&Xr.is(e)}createInput(e){if(Xr.is(e))return{type:Ur.MOBILE,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Mobile BeneficiaryInfo Info")}}class on{canHandle(e){return e.type===Ur.BANK&&en.is(e)}createInput(e){if(en.is(e))return{type:Ur.BANK,displayName:e.accountName,accountNo:e.accountNumber,channel:e.channelId};throw new Error("Expected Bank BeneficiaryInfo Info")}}class cn{handlers=[new sn,new on];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)}}class dn extends nr{constructor(e){super("contact",Kr,e)}async create(e){const t=(new cn).resolve(e),r=await this.client.createBeneficiary({body:t}),n=this.handleResponse(r,201);return an.create(n)}async edit(e,t){const r=(new cn).resolve(t),n=await this.client.editBeneficiary({params:{id:e},body:r}),a=this.handleResponse(n,200);return an.create(a)}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 an.createMany(t)}async getByID(e){const t=await this.client.getByID({params:{id:e}}),r=this.handleResponse(t,200);return an.create(r)}}var un,ln,hn;!function(e){e.TZ_TIGO_B2C="TZ-TIGO-B2C",e.TZ_VODACOM_B2C="TZ-VODACOM-B2C",e.TZ_AIRTEL_B2C="TZ-AIRTEL-B2C",e.TZ_HALOTEL_B2C="TZ-HALOTEL-B2C",e.KE_SAFARICOM_B2C="KE-SAFARICOM-B2C",e.TZ_BANK_B2C="TZ-BANK-B2C",e.KE_BANK_B2C="KE-BANK-B2C"}(un||(un={})),function(e){e.CREATED="CREATED",e.PENDING="PENDING",e.PAID="PAID",e.FAILED="FAILED",e.REJECTED="REJECTED",e.REVERSED="REVERSED",e.QUEUED="QUEUED"}(ln||(ln={})),function(e){e.PENDING="Pending",e.APPROVED="Approved",e.REJECTED="Rejected"}(hn||(hn={}));const pn=r.object({id:r.string(),name:r.string(),identity:r.string()}),mn=r.nativeEnum(ln),fn=r.nativeEnum(hn),yn=r.nativeEnum(un),gn=r.union([r.string(),r.array(r.string())]).transform(e=>(Array.isArray(e)?e:[e]).flatMap(e=>e.split(",")).map(e=>e.trim()).filter(e=>e.length>0)),vn=gn.pipe(r.array(mn)),_n=gn.pipe(r.array(fn)),bn=r.object({channel:yn,msisdn:r.string(),amount:r.coerce.number(),description:r.string(),notes:r.string().nullish()}),wn=bn.extend({payeeName:r.string()}),Nn=bn.extend({id:r.string(),profileId:r.string(),payeeName:r.string(),countryCode:r.string().default("TZ").refine(e=>u.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:r.string().default("TZS").refine(e=>m.isCode(e),{message:"Provided currency code is not a valid currency code."}),channel:r.string(),status:mn,statusMessage:r.string(),partnerReference:r.string().nullish(),createdAt:r.coerce.date(),updatedAt:r.coerce.date(),actionedAt:r.coerce.date().nullish(),approvalStatus:fn.nullish(),createdById:r.string().nullish(),actionedById:r.string().nullish(),createdBy:pn.nullish(),actionedBy:pn.nullish()}),In=r.object({page:r.number().int().positive().default(1),limit:r.number().int().positive().max(100).default(10),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().datetime().nullish(),endDate:r.string().datetime().nullish(),payeeName:r.string().nullish(),msisdn:r.string().nullish(),msisdnIn:gn.nullish(),profileId:r.string().nullish(),id:r.string().nullish(),partnerReference:r.string().nullish(),channel:r.string().nullish(),channelIn:gn.nullish(),currencyCode:r.string().nullish(),status:mn.nullish(),statusIn:vn.nullish(),approvalStatus:fn.nullish(),approvalStatusIn:_n.nullish(),createdById:r.string().nullish(),createdByIdIn:gn.nullish(),actionedById:r.string().nullish(),actionedByIdIn:gn.nullish(),minAmount:r.number().min(0).nullish(),maxAmount:r.number().min(0).nullish(),search:r.string().nullish(),relations:r.array(r.string()).nullish()}),Sn={PayoutDTO:Nn,PayoutInputDTO:wn,PayoutStatus:mn,PayoutApprovalStatus:fn,PayoutChannel:yn,PayoutAuthorizer:pn,PayoutFilters:In,PayoutURLQueryParams:r.object({page:r.string().transform(e=>parseInt(e)||1).optional(),limit:r.string().transform(e=>parseInt(e)||20).optional(),sortBy:r.string().default("createdAt"),sortOrder:r.enum(["asc","desc"]).default("desc"),startDate:r.string().optional(),endDate:r.string().optional(),payeeName:r.string().optional(),msisdn:r.string().optional(),msisdnIn:gn.optional(),profileId:r.string().optional(),id:r.string().optional(),partnerReference:r.string().optional(),channel:r.string().optional(),channelIn:gn.optional(),status:r.string().refine(e=>Object.values(ln).includes(e)).transform(e=>e).optional(),statusIn:vn.optional(),approvalStatus:r.string().refine(e=>Object.values(hn).includes(e)).transform(e=>e).optional(),approvalStatusIn:_n.optional(),createdById:r.string().optional(),createdByIdIn:gn.optional(),actionedById:r.string().optional(),actionedByIdIn:gn.optional(),minAmount:r.string().transform(e=>parseFloat(e)).optional(),maxAmount:r.string().transform(e=>parseFloat(e)).optional(),search:r.string().optional(),relations:r.array(r.string()).optional()})},An=t.object({id:t.string(),profileId:t.string(),payeeName:t.string(),channel:t.string(),msisdn:t.string(),amount:t.number(),currencyCode:t.string(),countryCode:t.string(),description:t.string(),notes:t.string().nullish(),status:Sn.PayoutStatus,statusMessage:t.string(),partnerReference:t.string().nullish(),createdAt:t.string(),updatedAt:t.string(),actionedAt:t.string().nullish(),approvalStatus:Sn.PayoutApprovalStatus.nullish(),createdById:t.string().nullish(),actionedById:t.string().nullish(),createdBy:Sn.PayoutAuthorizer.nullish(),actionedBy:Sn.PayoutAuthorizer.nullish(),_version:t.string().optional().default("1.0")});class On{_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=Sn.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 f.from(this._amount,this._currencyCode)}get description(){return this._description}get notes(){return this._notes}get status(){return this._approvalStatus===hn.REJECTED?ln.REJECTED:this._approvalStatus===hn.APPROVED?"FAILED"===this._status?ln.FAILED:ln.PAID:this._approvalStatus===hn.PENDING?ln.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 tn.fromPayoutDTO(this.toDTO())}get contactInfo(){return this.beneficiaryInfo}static create(e){return new On(e)}static createMany(e){return e.map(e=>new On(e))}static createSafe(e){try{return new On(e)}catch{return null}}static canConstruct(e){if(!e||"object"!=typeof e)return!1;const t=Sn.PayoutDTO.safeParse(e);if(!t.success)return!1;return null!==On.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 An.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,r=An.safeParse(t);if(!r.success)return void console.error("Invalid PayoutJSON:",r.error.flatten());const n=r.data,a=n.currencyCode;if(!m.isCode(a))return void console.error("Invalid currency code:",a);const s=n.countryCode;if(!u.isISO2Code(s))return void console.error("Invalid country code:",s);const i={id:n.id,profileId:n.profileId,payeeName:n.payeeName,channel:n.channel,msisdn:n.msisdn,amount:n.amount,currencyCode:a,countryCode:s,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 On.create(i)}catch(e){return void console.error("Error parsing PayoutJSON:",e)}}static isPayoutJSON(e){return An.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>On.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 Cn=["approvalStatus","status","channel","msisdn","createdById","actionedById"];class Pn extends yr{static create(){return new Pn}static fromFilters(e){return(new Pn).applyFilters(e)}static fromUrlParams(e){try{const t=Sn.PayoutURLQueryParams.parse(Pn.normalizeUrlParams(e)),r=Sn.PayoutFilters.parse(t);return Pn.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Pn.fromUrlParams(Pn.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Pn.fromSearchParams(t)}static from(e){try{return null==e?new Pn:yr.is(e)?new Pn(e.options):e instanceof URLSearchParams?Pn.fromSearchParams(e):Pn.isUrlParamsRecord(e)?Pn.fromUrlParams(e):Pn.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 Cn){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Pn.toStringList([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}return t}static toStringList(e){const t=Array.isArray(e)?e.flatMap(e=>Pn.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(hn.PENDING)}whereApproved(){return this.whereApprovalStatus(hn.APPROVED)}whereRejected(){return this.whereApprovalStatus(hn.REJECTED)}wherePaid(){return this.whereStatus(ln.PAID)}whereFailed(){return this.whereStatus(ln.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,r=void 0!==e.maxAmount&&null!==e.maxAmount,{currencyCode:n}=e,a=n||"TZS";if(!m.isCode(a))return console.warn("Amount filter requires a valid currency code"),this;if(t&&r){if(e.minAmount>e.maxAmount)return console.warn(`Invalid amount range: min (${e.minAmount}) > max (${e.maxAmount})`),this;const t=f.from(e.minAmount,a),r=f.from(e.maxAmount,a);t&&r&&this.whereAmountBetween(t,r)}else t?this.whereGreaterThanOrEqual("amount",e.minAmount):r&&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=[],r=this.toFilters(),n=e?.formatDate??(e=>e);if(r.sortBy){const e="asc"===r.sortOrder?"Ascending":"Descending";t.push({label:"Sort",value:`${this.formatSortField(r.sortBy)} (${e})`})}if(r.startDate&&r.endDate?t.push({label:"Date Range",value:`${n(r.startDate)} — ${n(r.endDate)}`}):r.startDate?t.push({label:"From",value:n(r.startDate)}):r.endDate&&t.push({label:"Until",value:n(r.endDate)}),r.statusIn?.length?t.push({label:"Status",value:r.statusIn.join(", ")}):r.status&&t.push({label:"Status",value:r.status}),r.approvalStatusIn?.length?t.push({label:"Approval Status",value:r.approvalStatusIn.join(", ")}):r.approvalStatus&&t.push({label:"Approval Status",value:r.approvalStatus}),r.channelIn?.length?t.push({label:"Channel",value:r.channelIn.join(", ")}):r.channel&&t.push({label:"Channel",value:r.channel}),void 0!==r.minAmount&&void 0!==r.maxAmount){const e=Number(r.minAmount),n=Number(r.maxAmount);if(Number.isFinite(e)&&Number.isFinite(n)){const r=f.from(e,"TZS"),a=f.from(n,"TZS");r&&a&&t.push({label:"Amount Range",value:`${r.label} — ${a.label}`})}}else if(void 0!==r.minAmount){const e=Number(r.minAmount);if(Number.isFinite(e)){const r=f.from(e,"TZS");r&&t.push({label:"Minimum Amount",value:r.label})}}else if(void 0!==r.maxAmount){const e=Number(r.maxAmount);if(Number.isFinite(e)){const r=f.from(e,"TZS");r&&t.push({label:"Maximum Amount",value:r.label})}}return r.search&&t.push({label:"Search",value:`"${r.search}"`}),r.payeeName&&t.push({label:"Beneficiary Name",value:r.payeeName}),r.msisdnIn?.length?t.push({label:"MSISDN",value:r.msisdnIn.join(", ")}):r.msisdn&&t.push({label:"MSISDN",value:r.msisdn}),r.profileId&&t.push({label:"Profile",value:r.profileId}),r.createdByIdIn?.length?t.push({label:"Created By ID",value:r.createdByIdIn.join(", ")}):r.createdById&&t.push({label:"Created By ID",value:r.createdById}),r.actionedByIdIn?.length?t.push({label:"Actioned By ID",value:r.actionedByIdIn.join(", ")}):r.actionedById&&t.push({label:"Actioned By ID",value:r.actionedById}),r.partnerReference&&t.push({label:"Reference",value:r.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=Pn.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=Pn.toStringList(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Pn.toStringList(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidApprovalStatuses(e){const t=Pn.toStringList(e).filter(e=>this.isValidApprovalStatus(e));return t.length>0?t:void 0}isValidStatus(e){return Object.values(ln).includes(e)}isValidApprovalStatus(e){return Object.values(hn).includes(e)}}const Tn=Ut().router({getPayouts:{method:"GET",path:"",query:r.object({}),responses:{200:r.object({results:r.array(Sn.PayoutDTO),total:r.number()})}},getPayoutsByApprovalStatus:{method:"GET",path:"",query:r.object({rangeStart:r.number(),rangeEnd:r.number(),eager:r.string(),approvalStatus:Sn.PayoutApprovalStatus,orderByDesc:r.string()}),responses:{200:r.object({results:r.array(Sn.PayoutDTO),total:r.number()})}},postPayout:{method:"POST",path:"",body:Sn.PayoutInputDTO,responses:{201:Sn.PayoutDTO,400:er.schema}},approve:{method:"POST",path:"/:id/approve",body:r.object({action:r.enum(["Approve","Reject"]),notes:r.string().optional()}),responses:{201:Sn.PayoutDTO,400:er.schema,401:er.schema,404:r.object({}),409:r.object({})}},getPayout:{method:"GET",path:"/:id/",responses:{200:Sn.PayoutDTO,404:r.object({})}}}),xn="MOBILE TRANSFER ",En="PAYOUT",kn="PAYOUT TO BANK",Bn="TO_BANK",Dn="PAYOUT TO MOBILE",jn="TO_MOMO",Rn=t.object({text:t.string(),_version:t.string().optional().default("2.0")});class Jn{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 Xr.is(e)?Jn.generateMobilePayoutNarrationV2(e):en.is(e)?Jn.generateBankPayoutNarrationV2(e):""}static generateMobilePayoutNarrationV2(e){const{phoneNumber:t,name:r}=e;return`${En.toUpperCase()} ${t.e164Format.trim()} ${r.trim()}`.toUpperCase()}static generateBankPayoutNarrationV2(e){const{bank:t,accName:r,accNo:n}=e;return`${En.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(xn)&&(e=e.substring(16));try{if(e.startsWith(En)){const t=e.replace(En,"").trim().split(" ");if(t.length>=3){const e=t[0],r=t[1],n=t.slice(2).map(Mn).join(" ");if(e.length>=8&&e.length<=11&&/^[A-Z0-9]+$/i.test(e)){const t=h.getCountryFromSwiftCode(e);if(t){if(h.validateSwiftCode(e,t)){const a=p.fromBIC(e,t);if(r&&n&&a)return new en(n,a,r)}}}}}if(e.startsWith(Bn)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=r.account_number,a=r.account_name,s=r.swift_code,i=h.getCountryFromSwiftCode(s);if(!i)return;if(!h.validateSwiftCode(s,i))return;const o=p.fromBIC(s,i);if(n&&a&&o)return new en(a,o,n)}if(e.startsWith(kn)){const t=e.replace(kn,"").trim().split(" "),r=y.getInstance().searchBanks("TZ",t[0]),n=r.length>0?r[0]:void 0,a=t[1],s=t.slice(2).map(Mn).join(" ");if(s&&a&&n)return new en(s,n,a)}}catch(e){return}};getMobileBeneficiaryDetails=()=>{let e=this.text.trim();e.startsWith(xn)&&(e=e.substring(16));try{if(e.startsWith(En)){const t=e.replace(En,"").trim().split(" ");if(t.length>=2){const e=t[0],r=t.slice(1).map(Mn).join(" ");if(e.startsWith("+")){const t=d.from(e);if(t&&r)return new Xr(r,t)}}}if(e.startsWith(jn)){const t=e.split("=>")[1].trim(),r=JSON.parse(t),n=d.from(r.phone_number,{defaultCountry:"TZ"});let a=r.username;void 0===a&&(a="");let s=a.split(" ");if(s=s.filter(e=>e.trim().length>0),a=s.map(Mn).join(" "),n&&a)return new Xr(a,n)}if(e.startsWith(Dn)){const t=e.replace(Dn,"").trim().split(" "),r=d.from(t[0],{defaultCountry:"TZ"}),n=t.slice(1).map(Mn).join(" ");if(r&&n)return new Xr(n,r)}}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=Rn.safeParse(t);if(!r.success)return void console.error("Invalid NarrationJSON:",r.error.flatten());const n=r.data;return new Jn(n.text)}catch(e){return void console.error("Error parsing NarrationJSON:",e)}}static isNarrationJSON(e){return Rn.safeParse(e).success}toJson(){return this.toJSON()}static fromJson(e){return Jn.fromJSON(e)}}function Mn(e){if(0===e.length)return e;return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}const Zn=["TZ","KE"],Ln={TZ:un.TZ_BANK_B2C,KE:un.KE_BANK_B2C},$n={TIGO:un.TZ_TIGO_B2C,VODACOM:un.TZ_TIGO_B2C,AIRTEL:un.TZ_AIRTEL_B2C,HALOTEL:un.TZ_HALOTEL_B2C},Fn="Invalid bank beneficiary info",Un="Invalid phone number",qn="The provided phone number is not eligible for payout. Please make sure it is a valid mobile number.",Vn="Wallet country does not match beneficiary country",Wn="Wallet currency does not match payout amount currency",Kn="Payout amount currency does not match the payout country currency",zn="Only TZ and KE bank payout channels are supported for now",Gn="Only TZ and KE mobile money payout channels are supported for now",Hn="Mobile money provider is not supported for payouts in this country",Qn=e=>Zn.includes(e);class Yn{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===b.MOBILE||t===b.FIXED_LINE_OR_MOBILE}}class Xn{static resolve(e){const{wallet:t,receiver:r,amount:n}=e;return Xn.assertCompatibleWalletReceiverAndAmount(t,r,n),Xr.is(r)?Xn.forMobile(r.phoneNumber,r.mnoId,t):Xn.forBank(r,t)}static forBank(e,t){if(!en.is(e))throw new Error(Fn);if(!Qn(t.countryCode))throw new Error(zn);if(t.countryCode!==e.countryCode)throw new Error(Vn);return Ln[t.countryCode]}static forMobile(e,t,r){if(!d.is(e))throw new Error(Un);if(!Qn(r.countryCode)||!Qn(e.countryCode))throw new Error(Gn);if(r.countryCode!==e.countryCode)throw new Error(Vn);if(!Yn.isPhoneEligibleForPayout(e))throw new Error(qn);if("KE"===r.countryCode)return un.KE_SAFARICOM_B2C;const n=c.findById(t,e.countryCode);if(!n||!n.supportsDirection(g.PAYOUT))throw new Error(Hn);const a=$n[n.id];if(!a)throw new Error(Hn);return a}static getChannelType(e){return Xn.isBankChannel(e)?v.BANK:v.MOBILE_MONEY}static getCountryCode(e){return e.slice(0,2)}static getProviderId(e){if(!Xn.isBankChannel(e))return e.split("-")[1]}static isBankChannel(e){return e.endsWith("-BANK-B2C")}static isMobileMoneyChannel(e){return!Xn.isBankChannel(e)}static assertCompatibleWalletReceiverAndAmount(e,t,r){if(e.countryCode!==t.countryCode)throw new Error(Vn);if(e.currencyCode!==r.currencyCode)throw new Error(Wn);const n=_.fromCode(e.countryCode)?.currencyCode;if(n&&r.currencyCode!==n)throw new Error(Kn)}}class ea{getPayoutInput(e,t){const r=Xn.resolve({...e,wallet:t});if(Xr.is(e.receiver))return this.createMobileInput(e.receiver,e.amount,r,e.notes);if(en.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,r,n){const a=Yn.processNotes(n);return{channel:r,msisdn:e.phoneNumber.getWithFormat(l.INTERNATIONAL_NUMERIC),description:a??Jn.generateDefaultPayoutNarration(e),payeeName:e.name,notes:a,amount:t.numericValue}}createBankInput(e,t,r,n){const a=Yn.processNotes(n);return{channel:r,msisdn:`${e.bank.bic}:${e.accNo}`,description:a??Jn.generateDefaultPayoutNarration(e),payeeName:e.accName,notes:a,amount:t.numericValue}}}const ta={bank:Xn.forBank.bind(Xn),mobile:Xn.forMobile.bind(Xn)};class ra extends nr{constructor(e){super("payout",Tn,e)}async getPayouts(e){try{const t=Pn.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i=new or(s.page??1,s.limit??10,a.total);return{results:On.createMany(a.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=Pn.from(e).build();delete t.rangeStart,delete t.rangeEnd;const r=await this.client.getPayouts({query:t}),n=this.handleResponse(r,200);return On.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=Pn.fromRequest(e);return this.getPayouts(t)}async pay(e){const{wallet:t,receiver:r,amount:n,notes:a}=e,s=Xn.resolve({wallet:t,receiver:r,amount:n}),i=w.getTransactionLimits({countryCode:t.countryCode,currencyCode:n.currencyCode,direction:g.PAYOUT,channelType:Xn.getChannelType(s)});if(!i)throw new er({statusCode:400,message:`Payout limits are not configured for ${t.countryCode} ${n.currencyCode} ${s} payouts`});const{min:o,max:c}=i;if(n.lessThan(o)||n.greaterThan(c))throw new er({statusCode:400,message:`Please make sure the amount is between ${o.label} - ${c.label}`});const d=(new ea).getPayoutInput({receiver:r,amount:n,notes:a},t),u=await this.client.postPayout({body:d});if(201===u.status)return On.create(u.body);if(400===u.status)throw new er(u.body);throw er.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 On.create(t.body);if(401===t.status)throw new er({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new er({message:"Payout not found",statusCode:404});if(409===t.status)throw new er({message:"Payout already approved",statusCode:409});throw er.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 On.create(t.body);if(401===t.status)throw new er({message:"You are not authorized to perform this action",statusCode:401});if(404===t.status)throw new er({message:"Payout not found",statusCode:404});if(409===t.status)throw new er({message:"Payout already rejected",statusCode:409});throw er.unknown()}async getByID(e){const t=await this.client.getPayout({params:{id:e}});if(200===t.status)return On.create(t.body);if(404===t.status)throw new er({message:"Payout not found",statusCode:404});throw er.unknown()}async count(e){const t=Pn.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}}const na=Ut().router({getCurrentProfile:{method:"GET",path:"/me",responses:{200:Sr.schema}}});class aa extends nr{constructor(e){super("profile",na,e)}async getCurrentProfile(){const e=await this.client.getCurrentProfile();if(200===e.status){const t=Sr.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}`)}}const sa=e=>e.optional().transform(e=>e??void 0),ia={walletDTO:r.object({id:r.string().min(1,{message:"Wallet ID is required."}),profileId:r.string().min(1,{message:"Profile ID is required."}),accountNo:r.string().min(1,{message:"Account number is required."}),accountName:r.string().min(1,{message:"Account name is required."}),channel:r.string().min(1,{message:"Channel is required."}),countryCode:r.string().default("TZ").refine(e=>u.isISO2Code(e),{message:"Provided country code is not a valid ISO2 code."}),currencyCode:r.string().default("TZS").refine(e=>m.isCode(e),{message:"Provided currency code is not a valid currency code."}),createdAt:r.string().datetime({message:"Creation timestamp must be a valid ISO 8601 datetime string."}),updatedAt:r.string().datetime({message:"Update timestamp must be a valid ISO 8601 datetime string."})}),walletQuery:r.object({id:r.string().optional(),profileId:r.string().optional(),accountNo:r.string().optional(),accountName:r.string().optional(),channel:r.string().optional(),countryCode:r.string().default("TZ").refine(e=>S.has(e),{message:"Provided country code is not a valid ISO2 code."}).optional(),currencyCode:r.string().default("TZS").refine(e=>{const t=N.fromCode(e);return void 0!==t&&I.has(t.code)},{message:"Provided currency code is not a valid currency code."}).optional()}),statementEntry:r.object({accountNo:sa(r.string()),debitOrCredit:r.string().min(1,"Transaction type is required"),tranRefNo:r.string().min(1,"Transaction reference is required"),narration:r.string().min(1,"Transaction description is required"),txnDate:r.coerce.date({error:()=>({message:"Invalid transaction date format"})}),valueDate:r.coerce.date({error:()=>({message:"Invalid value date format"})}),amountCredited:r.number().min(0,"Credited amount must be non-negative"),amountDebited:r.number().min(0,"Debited amount must be non-negative"),balance:r.number(),currencyCode:sa(r.string().min(3,"Currency code must be at least 3 characters")).default("TZS")}),plainDate:r.string().regex(/^\d{4}-\d{2}-\d{2}$/,{message:"Date must be in YYYY-MM-DD format (no time component)."})},oa=t.object({accountNo:t.string().optional(),debitOrCredit:t.string(),tranRefNo:t.string(),narration:Rn,txnDate:t.string(),valueDate:t.string(),amountCredited:A,amountDebited:A,balance:A,currencyCode:t.string(),_version:t.string().optional().default("2.0")});class ca{_accountNo;_debitOrCredit;_tranRefNo;_narration;_txnDate;_valueDate;_amountCredited;_amountDebited;_balance;_currencyCode;static get schema(){return ia.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 r=N.fromCode(e.currencyCode);if(!r)throw new Error(`Currency not found for code: ${e.currencyCode}`);const n=f.from(e.amountCredited,r.code),a=f.from(e.amountDebited,r.code),s=f.from(e.balance,r.code);if(!n||!a||!s)throw new Error(`Failed to create Amount instances with currency code: ${e.currencyCode}`);this._amountCredited=n,this._amountDebited=a,this._balance=s}static create(e){const t="string"==typeof e.narration?new Jn(e.narration):e.narration,r={...e,narration:t.text},n=ca.schema.safeParse(r);if(n.success)try{const{narration:e,...r}=n.data;return new ca(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=ca.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&&Jn.is(t._narration)&&t._txnDate instanceof Date&&t._valueDate instanceof Date&&f.is(t._amountCredited)&&f.is(t._amountDebited)&&f.is(t._balance)&&"string"==typeof t._currencyCode}catch(e){return!1}}equals(e){return this._tranRefNo===e._tranRefNo}clone(){return ca.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,r,n,a,s=e.currencyCode||"TZS";if(e.amountCredited&&"object"==typeof e.amountCredited&&"value"in e.amountCredited){const a=f.fromJSON(e.amountCredited),i=f.fromJSON(e.amountDebited),o=f.fromJSON(e.balance);if(!a||!i||!o)return void console.error("Failed to deserialize Amount objects from JSON");t=a.numericValue,r=i.numericValue,n=o.numericValue,e.currencyCode||(s=a.currencyCode)}else if(t=Number(e.amountCredited),r=Number(e.amountDebited),n=Number(e.balance),!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n))return void console.error("Invalid numeric values for amounts");if("string"==typeof e.narration)a=e.narration;else if(Jn.is(e.narration))a=e.narration;else{if(!Jn.isNarrationJSON(e.narration))return void console.error("Invalid narration data");{const t=Jn.fromJson(e.narration);if(!t)return void console.error("Failed to create Narration from NarrationJson");a=t}}return ca.create({accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,narration:a,txnDate:e.txnDate,valueDate:e.valueDate,amountCredited:t,amountDebited:r,balance:n,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,r=oa.safeParse(t);if(!r.success)return void console.error("Invalid WalletStatementEntryJSON:",r.error.flatten());const n=r.data,a=Jn.fromJSON(n.narration);if(!a)return void console.warn("Failed to deserialize narration");const s=f.fromJSON(n.amountCredited),i=f.fromJSON(n.amountDebited),o=f.fromJSON(n.balance);return s&&i&&o?s.currencyCode!==n.currencyCode||i.currencyCode!==n.currencyCode||o.currencyCode!==n.currencyCode?void console.warn("Currency code mismatch"):ca.create({accountNo:n.accountNo,debitOrCredit:n.debitOrCredit,tranRefNo:n.tranRefNo,narration:a,txnDate:n.txnDate,valueDate:n.valueDate,amountCredited:s.numericValue,amountDebited:i.numericValue,balance:o.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 oa.safeParse(e).success}static fromJSONArray(e){try{const t="string"==typeof e?JSON.parse(e):e;return Array.isArray(t)?t.map(e=>ca.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 ca.fromJSON(e)}static fromJsonArray(e){return ca.fromJSONArray(e)}static toJsonArray(e){return ca.toJSONArray(e)}}const da=t.object({id:t.string(),profileId:t.string(),accountNo:t.string(),accountName:t.string(),channel:t.string(),countryCode:t.string(),currencyCode:t.string(),createdAt:t.string(),updatedAt:t.string(),_version:t.string().optional().default("1.0")});class ua{_id;_profileId;_accountNo;_accountName;_channel;_countryCode;_currencyCode;_createdAt;_updatedAt;static get schema(){return ia.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=ua.schema.safeParse(e);if(t.success)return new ua(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=ua.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 ua.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&&u.isISO2Code(t._countryCode)&&"string"==typeof t._currencyCode&&m.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=da.safeParse(t);if(!r.success)return void console.error("Invalid WalletJSON:",r.error.flatten());const n=r.data;return ua.create(n)}catch(e){return void console.error("Error parsing WalletJSON:",e)}}static isWalletJSON(e){return da.safeParse(e).success}}const la=Ut().router({getWallets:{method:"GET",path:"/",query:ia.walletQuery,responses:{200:r.array(ua.schema)}},getBalance:{method:"POST",path:"/balance",body:r.object({accountNo:r.string().optional()}),responses:{201:r.object({availableBalance:r.number()})}},getStatement:{method:"POST",path:"/statement",summary:"Get Wallet Statement",body:r.object({endDate:ia.plainDate,startDate:ia.plainDate,accountNo:r.string().optional()}),responses:{201:r.array(ca.schema)}}});class ha extends yr{static create(){return new ha}static fromFilters(e){return(new ha).applyFilters(e)}static fromUrlParams(e){try{const t=ia.walletQuery.parse(e);return ha.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 ha.fromUrlParams(t)}static fromRequest(e){const{searchParams:t}=new URL(e.url);return ha.fromSearchParams(t)}static from(e){try{return null==e?new ha:yr.is(e)?new ha(e.options):e instanceof URLSearchParams?ha.fromSearchParams(e):ha.isStringRecord(e)?ha.fromUrlParams(e):ha.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 pa="Africa/Nairobi";function ma(e,t){const[r,n,a]=e.split("-").map(Number),s=Date.UTC(r,n-1,a,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 fa(e){return{startDate:ma(e.startDate,-1),endDate:ma(e.endDate,1)}}function ya(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}function ga(e){return!e||e===pa}class va extends nr{constructor(e){super("wallet",la,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 r=t.body.availableBalance,n=f.from(r,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 r=t[0],n=await this.client.getBalance({body:{accountNo:e.accountNo}});if(201===n.status){const e=n.body.availableBalance,t=f.from(e,r.currencyCode);if(t)return t}}throw new Error("Failed to fetch balance")}async getWallets(e){const t=ha.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=ua.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=ha.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 n=await this.getWallets({accountNo:e.accountNo});if(0===n.length)throw new Error(`No wallet found for accountNo: ${e.accountNo}`);t=n[0],r=e.accountNo}}const n=!ga(e.timezone),a={...n?fa(e.range):e.range,accountNo:r},s=await this.client.getStatement({body:a});if(201===s.status){const r=s.body.map(e=>({...e,currencyCode:t.currencyCode})).reduce((e,t)=>{const r=ca.create(t);return r?e.push(r):console.warn("[WalletRepository] Skipping invalid statement entry:",t),e},[]);if(!n)return r;const a=e.timezone,{startDate:i,endDate:o}=e.range;return r.filter(e=>{const t=ya(e.valueDate,a);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}}function _a(e){return`${String(e.getFullYear()).padStart(4,"0")}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}const ba={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)};export{er as APIError,_r as AuthDTOSchemas,Fr as AuthRepository,kn as BANK_NARR_PREFIX,en as BankBeneficiaryInfo,Gr as BankBeneficiaryJSONSchema,nr as BaseRepository,an as Beneficiary,Wr as BeneficiaryDTOSchemas,Qr as BeneficiaryError,rn as BeneficiaryInfo,tn as BeneficiaryInfoFactory,Hr as BeneficiaryInfoJSONSchema,nn as BeneficiaryJSONSchema,dn as BeneficiaryRepository,Ur as BeneficiaryType,Pr as CompanyMembership,Cr as CompanyMembershipJSONSchema,pa as EAT_TIMEZONE,xn as ECOBANK_PREFIX,pr as FilterOperator,kr as IdentityRepository,Bn as LEGACY_BANK_NARR_PREFIX,jn as LEGACY_MOBILE_NARR_PREFIX,Nr as LogIn,wr as LogInJSONSchema,br as LogInSchemas,Dn as MOBILE_NARR_PREFIX,Xr as MobileBeneficiaryInfo,zr as MobileBeneficiaryJSONSchema,En as NARR_V2_PREFIX,Jn as Narration,Rn as NarrationJSONSchema,or as Pagination,ur as PaginationParamsSchema,lr as PaginationSchema,On as Payout,hn as PayoutApprovalStatus,un as PayoutChannel,Xn as PayoutChannelResolver,Sn as PayoutDTOSchemas,ea as PayoutInputFactory,An as PayoutJSONSchema,Pn as PayoutQuery,ra as PayoutRepository,ln as PayoutStatus,sr as PermissionError,ar as Permissions,Sr as Profile,vr as ProfileDTOSchemas,Ir as ProfileJSONSchema,aa as ProfileRepository,fr as QUERY_BUILDER_TYPE,yr as QueryBuilder,Or as Role,Ar as RoleJSONSchema,mr as SortDirection,Rr as TeamManagementDTOSchemas,Zr as TeamMember,Mr as TeamMemberJSONSchema,Lr as TeamMemberRepository,xr as User,Tr as UserJSONSchema,cn as ValidatedBeneficiaryInputFactory,ua as Wallet,ia as WalletDTOSchemas,da as WalletJSONSchema,va as WalletRepository,ca as WalletStatementEntry,oa as WalletStatementEntryJSONSchema,ba as WalletUtils,Kr as contract,cr as createPaginatedResponse,hr as createPaginatedResponseSchema,ta as createPayoutChannelCode,dr as emptyPaginatedResponse,ga as isEatTimezone,ir as isError,ya as localDateInZone,fa as padEatRange,rr as setGlobalTokenGetter,ma as shiftPlainDate,_a as toPlainDate};
2
2
  //# sourceMappingURL=index.esm.js.map