meta-cloud-api 0.2.36 → 0.2.38

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 (57) hide show
  1. package/dist/{BusinessProfileApi-DO28tMcf.d.ts → BusinessProfileApi-DpYV4svz.d.ts} +2 -2
  2. package/dist/{EncryptionApi-CFuuNH2K.d.ts → EncryptionApi-D6FamzN6.d.ts} +1 -1
  3. package/dist/{FlowApi-Mwlby1Rl.d.ts → FlowApi-DWb7g0Zn.d.ts} +1 -1
  4. package/dist/{MediaApi-CyoByati.d.ts → MediaApi-DE0jVnF1.d.ts} +1 -1
  5. package/dist/{MessageApi-BU1WUNKS.d.ts → MessageApi-D5f5CfT2.d.ts} +2 -2
  6. package/dist/{PhoneNumberApi-C3Hmh_nZ.d.ts → PhoneNumberApi-B7W0s_c-.d.ts} +1 -1
  7. package/dist/{QrCodeApi-BPsHp3ad.d.ts → QrCodeApi-CX8jf7Ac.d.ts} +1 -1
  8. package/dist/{RegistrationApi-DI9NskvK.d.ts → RegistrationApi-GgpYO2rY.d.ts} +2 -2
  9. package/dist/{TemplateApi-DXr47lZe.d.ts → TemplateApi-D07haTIv.d.ts} +2 -2
  10. package/dist/{TwoStepVerificationApi-CICKknhN.d.ts → TwoStepVerificationApi-CPFMU93y.d.ts} +1 -1
  11. package/dist/{WabaApi-DZurKSzA.d.ts → WabaApi-BRqE-S9E.d.ts} +1 -1
  12. package/dist/{WebhookHandler-q8tq2j0d.d.ts → WebhookHandler-CTp7u5q0.d.ts} +3 -3
  13. package/dist/{base-GKqD_DhO.d.ts → base-BxNBMX7d.d.ts} +20 -2
  14. package/dist/chunk-7PDRNOEC.js +3 -0
  15. package/dist/{chunk-4LWNMCXG.js.map → chunk-7PDRNOEC.js.map} +1 -1
  16. package/dist/chunk-GP6T67R7.js +3 -0
  17. package/dist/{chunk-MTRF47KZ.js.map → chunk-GP6T67R7.js.map} +1 -1
  18. package/dist/chunk-XL2LO2UM.js +2 -0
  19. package/dist/chunk-XL2LO2UM.js.map +1 -0
  20. package/dist/core/webhook/index.d.ts +15 -15
  21. package/dist/core/webhook/index.js +1 -1
  22. package/dist/core/whatsapp/index.d.ts +16 -100
  23. package/dist/core/whatsapp/index.js +1 -1
  24. package/dist/{enums-CM95zXd_.d.ts → enums-GplwFXwj.d.ts} +20 -5
  25. package/dist/features/encryption/index.d.ts +4 -4
  26. package/dist/features/encryption/index.js +1 -1
  27. package/dist/features/flow/index.d.ts +4 -4
  28. package/dist/features/flow/index.js +1 -1
  29. package/dist/features/media/index.d.ts +4 -4
  30. package/dist/features/media/index.js +1 -1
  31. package/dist/features/messages/index.d.ts +4 -4
  32. package/dist/features/messages/index.js +1 -1
  33. package/dist/features/phone/index.d.ts +4 -4
  34. package/dist/features/phone/index.js +1 -1
  35. package/dist/features/profile/index.d.ts +4 -4
  36. package/dist/features/profile/index.js +1 -1
  37. package/dist/features/qrCode/index.d.ts +4 -4
  38. package/dist/features/qrCode/index.js +1 -1
  39. package/dist/features/registration/index.d.ts +4 -4
  40. package/dist/features/registration/index.js +1 -1
  41. package/dist/features/template/index.d.ts +4 -4
  42. package/dist/features/template/index.js +1 -1
  43. package/dist/features/twoStepVerification/index.d.ts +4 -4
  44. package/dist/features/twoStepVerification/index.js +1 -1
  45. package/dist/features/waba/index.d.ts +4 -4
  46. package/dist/features/waba/index.js +1 -1
  47. package/dist/index-Dmd_nPsa.d.ts +100 -0
  48. package/dist/index.d.ts +17 -17
  49. package/dist/index.js +1 -1
  50. package/dist/shared/types/config.d.ts +1 -1
  51. package/dist/shared/types/enums.d.ts +1 -1
  52. package/dist/shared/types/enums.js +1 -1
  53. package/package.json +1 -1
  54. package/dist/chunk-4LWNMCXG.js +0 -3
  55. package/dist/chunk-MTRF47KZ.js +0 -3
  56. package/dist/chunk-QCFJGLDQ.js +0 -2
  57. package/dist/chunk-QCFJGLDQ.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { d as BaseClass, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { d as BaseClass, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { B as BusinessVerticalEnum } from './enums-CM95zXd_.js';
3
+ import { B as BusinessVerticalEnum } from './enums-GplwFXwj.js';
4
4
 
5
5
  /**
6
6
  * Upload session information for creating upload sessions.
@@ -1,4 +1,4 @@
1
- import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type EncryptionPublicKeyResponse = ResponseData<{
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type MediaResponse = {
@@ -1,6 +1,6 @@
1
- import { d as BaseClass, G as GeneralRequestBody, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { d as BaseClass, G as GeneralRequestBody, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { g as InteractiveTypesEnum, d as ComponentTypesEnum, L as LanguagesEnum, P as ParametersTypesEnum, C as CurrencyCodesEnum, c as ButtonTypesEnum, b as ButtonPositionEnum, M as MessageTypesEnum } from './enums-CM95zXd_.js';
3
+ import { g as InteractiveTypesEnum, d as ComponentTypesEnum, L as LanguagesEnum, P as ParametersTypesEnum, C as CurrencyCodesEnum, c as ButtonTypesEnum, b as ButtonPositionEnum, M as MessageTypesEnum } from './enums-GplwFXwj.js';
4
4
 
5
5
  interface ReactionParams {
6
6
  messageId: string;
@@ -1,4 +1,4 @@
1
- import { P as Paging, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { P as Paging, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type QualityRating = 'GREEN' | 'YELLOW' | 'RED' | 'NA';
@@ -1,4 +1,4 @@
1
- import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type QrCodeResponse = {
@@ -1,6 +1,6 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { D as DataLocalizationRegionEnum } from './enums-CM95zXd_.js';
3
+ import { D as DataLocalizationRegionEnum } from './enums-GplwFXwj.js';
4
4
 
5
5
  type RegistrationRequest = {
6
6
  messaging_product: 'whatsapp';
@@ -1,6 +1,6 @@
1
- import { G as GeneralRequestBody, R as ResponseSuccess, b as ResponsePagination, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { G as GeneralRequestBody, R as ResponseSuccess, b as ResponsePagination, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { L as LanguagesEnum, a as CategoryEnum, T as TemplateStatusEnum } from './enums-CM95zXd_.js';
3
+ import { L as LanguagesEnum, a as CategoryEnum, T as TemplateStatusEnum } from './enums-GplwFXwj.js';
4
4
 
5
5
  type TemplateFormat = 'TEXT' | 'IMAGE' | 'VIDEO' | 'DOCUMENT' | 'LOCATION' | 'PRODUCT';
6
6
  type PhoneNumberButton = {
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type TwoStepVerificationRequest = {
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-BxNBMX7d.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  /**
@@ -1,7 +1,7 @@
1
1
  import { WabaConfigType, WhatsAppConfig } from './shared/types/config.js';
2
- import { M as MessageTypesEnum } from './enums-CM95zXd_.js';
3
- import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-Mwlby1Rl.js';
4
- import { WhatsApp } from './core/whatsapp/index.js';
2
+ import { M as MessageTypesEnum } from './enums-GplwFXwj.js';
3
+ import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-DWb7g0Zn.js';
4
+ import { W as WhatsApp } from './index-Dmd_nPsa.js';
5
5
 
6
6
  interface WebhookContact {
7
7
  /**
@@ -1,7 +1,25 @@
1
1
  import { WabaConfigType } from './shared/types/config.js';
2
- import { H as HttpMethodsEnum } from './enums-CM95zXd_.js';
2
+ import { H as HttpMethodsEnum } from './enums-GplwFXwj.js';
3
3
 
4
4
  type GeneralRequestBody = Record<string, unknown>;
5
+ interface GeneralHeaderInterface {
6
+ /**
7
+ * Authorization token. This is required for all HTTP requests made to the graph API.
8
+ * @default 'Bearer '
9
+ */
10
+ Authorization: string;
11
+ /**
12
+ * Content type of the message being sent. This is required for all HTTP requests made to the graph API.
13
+ * @default 'application/json'
14
+ */
15
+ 'Content-Type': string;
16
+ /**
17
+ * User agent field sent in all requests. This is used to gather SDK usage metrics and help
18
+ * better triage support requests.
19
+ * @default `WA_SDK/${ SDK_version } (Node.js ${ process.version })`
20
+ */
21
+ 'User-Agent': string;
22
+ }
5
23
  interface RequesterResponseInterface<T> {
6
24
  json: () => Promise<T>;
7
25
  }
@@ -43,4 +61,4 @@ declare class BaseAPI implements BaseClass {
43
61
  protected sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;
44
62
  }
45
63
 
46
- export { BaseAPI as B, type GeneralRequestBody as G, type Paging as P, type ResponseSuccess as R, RequesterClass as a, type ResponsePagination as b, type ResponseData as c, BaseClass as d };
64
+ export { BaseAPI as B, type GeneralRequestBody as G, type Paging as P, type ResponseSuccess as R, RequesterClass as a, type ResponsePagination as b, type ResponseData as c, BaseClass as d, type GeneralHeaderInterface as e, type RequesterResponseInterface as f };
@@ -0,0 +1,3 @@
1
+ import {a as a$3}from'./chunk-3MO3BTBC.js';import {a as a$1}from'./chunk-R36L2XYO.js';import {a as a$2}from'./chunk-GT3XQN7Y.js';import {b as b$4}from'./chunk-O2OTHNWM.js';import {b as b$2}from'./chunk-7NQLQPLH.js';import {b as b$3}from'./chunk-UQPD6GIF.js';import {b as b$6}from'./chunk-5JGM556C.js';import {b}from'./chunk-2NJVBJUN.js';import {b as b$5}from'./chunk-XPPDOFBN.js';import {b as b$7}from'./chunk-KFPOVYEJ.js';import {c}from'./chunk-LGLRGXCE.js';import {b as b$1}from'./chunk-GIQLIMOD.js';import {a}from'./chunk-VW3LGHTJ.js';import {A as A$1}from'./chunk-XL2LO2UM.js';import {Agent}from'https';var D="UTILS",M=false,W=new a(D,process.env.DEBUG==="true"||M),U=3e3,k=30,q=2e4,v=s=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!s?.accessToken)throw W.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},N=s=>{v(s);let e={M4D_APP_ID:s?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:s?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:s?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:s?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:s?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:s?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:s?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:s?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:s?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||U,MAX_RETRIES_AFTER_WAIT:s?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||k,REQUEST_TIMEOUT:s?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||q,DEBUG:s?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:s?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:s?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return W.log(`Configuration loaded for App Id ${e.M4D_APP_ID}`),e};var B="HttpsClient",$=false,L=new a(B,process.env.DEBUG==="true"||$),u=class{agent;constructor(){this.agent=new Agent({keepAlive:true});}clearSockets(){return this.agent.destroy(),true}async sendRequest(e,r,t,o,i,m){let a=`https://${e}/${r}`,g=new AbortController,n=setTimeout(()=>g.abort(),i);try{let p=await fetch(a,{method:t,headers:o,body:m,signal:g.signal});return L.log(`${t} : ${a} - ${JSON.stringify(p)}`),clearTimeout(n),new A(p)}catch(p){throw L.error(`${t} : ${a} - ${JSON.stringify(p)}`),p}}},A=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries());}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};var G="REQUESTER",K=false,F=new a(G,process.env.DEBUG==="true"||K),d=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,r,t,o,i){this.client=new u,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=r,this.accessToken=t,this.businessAcctId=o,this.userAgent=i;}buildHeader(e,r){let t={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(t["Content-Type"]=e),r&&Object.assign(t,r),t}buildCAPIPath(e){return `v${this.apiVersion}.0/${e}`}async sendRequest(e,r,t,o,i="application/json",m){let a=i;o instanceof FormData?a="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(a="application/xml");let g=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(r)}`;F.log(`${e} : ${g} (${a})`);try{let n=await this.client.sendRequest(this.host,this.buildCAPIPath(r),e,this.buildHeader(a,m),t,e==="POST"||e==="PUT"?o:void 0);if(!n.rawResponse().ok){let p=await n.json();throw a$3(p)?p:{name:"MetaError",message:"Unknown error occurred",error:{message:p.message||"Unknown error occurred",type:"UnknownError",code:n.statusCode(),fbtrace_id:""}}}return n}catch(n){throw a$3(n)?n:{name:"MetaError",message:n instanceof Error?n.message:"Network error occurred",error:{message:n instanceof Error?n.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,r,t,o,i){return await(await this.sendRequest(e,r,t,o,"application/json",i)).json()}async sendFormData(e,r,t,o,i){return await(await this.sendRequest(e,r,t,o,"multipart/form-data",i)).json()}async sendUrlEncodedForm(e,r,t,o,i){let m=new URLSearchParams(o).toString();return await(await this.sendRequest(e,r,t,m,"application/x-www-form-urlencoded",i)).json()}};var V="WHATSAPP",x=false,h=new a(V,process.env.DEBUG==="true"||x),j="WA_SDK",l=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=A$1;constructor(e){this.config=N(e),this.requester=new d(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new b(this.config,this.requester),this.templates=new a$1(this.config,this.requester),this.phoneNumber=new b$1(this.config,this.requester),this.qrCode=new a$2(this.config,this.requester),this.encryption=new b$2(this.config,this.requester),this.twoStepVerification=new b$3(this.config,this.requester),this.registration=new b$4(this.config,this.requester),this.media=new b$5(this.config,this.requester),this.waba=new b$6(this.config,this.requester),this.flow=new c(this.config,this.requester),this.businessProfile=new b$7(this.config,this.requester),h.log("WhatsApp Node.js SDK instantiated!");}userAgent(){return `${j}/0.0.1 (Node.js ${process.version})`}updateTimeout(e){return this.config.REQUEST_TIMEOUT=e,h.log(`Updated request timeout to ${e}ms`),true}updatePhoneNumberId(e){return this.config.WA_PHONE_NUMBER_ID=e,h.log(`Updated sender phone number id to ${e}`),true}updateAccessToken(e){return this.config.CLOUD_API_ACCESS_TOKEN=e,h.log("Updated access token"),true}updateWabaId(e){return this.config.WA_BUSINESS_ACCOUNT_ID=e,h.log(`Updated business account id to ${e}`),true}};
2
+ export{N as a,l as b};//# sourceMappingURL=chunk-7PDRNOEC.js.map
3
+ //# sourceMappingURL=chunk-7PDRNOEC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shared/config/importConfig.ts","../src/shared/http/httpsClient.ts","../src/shared/http/request.ts","../src/core/whatsapp/WhatsApp.ts"],"names":["LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","contentType","additionalHeaders","endpoint","effectiveContentType","errorData","isMetaError","formData","urlEncodedBody","headerPrefix","WhatsApp","enums_exports","messages_default","TemplateApi","phone_default","QrCodeApi","encryption_default","twoStepVerification_default","registration_default","media_default","waba_default","flow_default","profile_default","ms","wabaId"],"mappings":"wlBAIMA,IAAAA,CAAAA,CAAW,OACXC,CAAAA,CAAAA,CAAY,KACZC,CAAAA,CAAAA,CAAS,IAAIC,CAAOH,CAAAA,CAAAA,CAAU,OAAQ,CAAA,GAAA,CAAI,KAAU,GAAA,MAAA,EAAUC,CAAS,CACvEG,CAAAA,CAAAA,CAAwB,GACxBC,CAAAA,CAAAA,CAAiC,EACjCC,CAAAA,CAAAA,CAA0B,GAE1BC,CAAAA,CAAAA,CAAsBC,CAAuC,EAAA,CAC/D,GAAI,CAAC,OAAQ,CAAA,GAAA,CAAI,wBAA+B,CAACA,CAAAA,EAAQ,WACrD,CAAA,MAAAN,CAAO,CAAA,GAAA,CAAI,2FAA2F,CAChG,CAAA,IAAI,KAAM,CAAA,gCAAgC,CAExD,CAAA,CAEaO,EAAgBC,CAAiC,EAAA,CAC1DH,CAAmBG,CAAAA,CAAW,CAE9B,CAAA,IAAMC,CAA6B,CAAA,CAC9B,UAAuBD,CAAAA,CAAAA,EAAa,KAAS,EAAA,OAAA,CAAQ,GAAI,CAAA,UAAA,EAAc,GACvE,cAA2BA,CAAAA,CAAAA,EAAa,SAAa,EAAA,OAAA,CAAQ,GAAI,CAAA,cAAA,EAAkB,GACnF,kBAA+BA,CAAAA,CAAAA,EAAa,aAAiB,EAAA,MAAA,CAAO,OAAQ,CAAA,GAAA,CAAI,kBAAkB,CAClG,CAAA,s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,OAAO,CAElF,CAAA,CAAA,CAEA,cAAcc,CAAqB,CAAA,CAC/B,OAAK,IAAA,CAAA,MAAA,CAAO,eAA0CA,CAAAA,CAAAA,CACtDtD,EAAO,GAAI,CAAA,CAAA,2BAAA,EAA8BsD,CAAE,CAAA,EAAA,CAAI,CACxC,CAAA,IACX,CAEA,mBAAoB1B,CAAAA,CAAAA,CAAgC,CAChD,OAAA,IAAA,CAAK,MAAO,CAAA,kBAAA,CAAyCA,CACrD5B,CAAAA,CAAAA,CAAO,GAAI,CAAA,CAAA,kCAAA,EAAqC4B,CAAa,CAAA,CAAE,CACxD,CAAA,IACX,CAEA,iBAAkBC,CAAAA,CAAAA,CAA8B,CAC5C,OAAA,IAAA,CAAK,MAAO,CAAA,sBAAA,CAAuCA,CACnD7B,CAAAA,CAAAA,CAAO,GAAI,CAAA,sBAAsB,CAC1B,CAAA,IACX,CAEA,YAAA,CAAauD,EAAyB,CAClC,OAAA,IAAA,CAAK,MAAO,CAAA,sBAAA,CAA0CA,CACtDvD,CAAAA,CAAAA,CAAO,GAAI,CAAA,CAAA,+BAAA,EAAkCuD,CAAM,CAAA,CAAE,CAC9C,CAAA,IACX,CACJ","file":"chunk-4LWNMCXG.js","sourcesContent":["import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\n};\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../types/httpsClient';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../types/enums';\nimport type { RequesterClass } from '../types/request';\nimport { isMetaError, MetaError } from '../utils/isMetaError';\nimport Logger from '../utils/logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport * as SDKEnums from '@shared/types/enums';\nimport Logger from '@shared/utils/logger';\n\nimport EncryptionApi from '@features/encryption';\nimport FlowApi from '@features/flow';\nimport MediaApi from '@features/media';\nimport MessagesApi from '@features/messages';\nimport PhoneNumberApi from '@features/phone';\nimport BusinessProfileApi from '@features/profile';\nimport QrCodeApi from '@features/qrCode/QrCodeApi';\nimport RegistrationApi from '@features/registration';\nimport TemplateApi from '@features/template/TemplateApi';\nimport TwoStepVerificationApi from '@features/twoStepVerification';\nimport WabaApi from '@features/waba';\nimport { importConfig } from '@shared/config/importConfig';\nimport Requester from '@shared/http/request';\nimport { WhatsAppClass } from './types';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nconst headerPrefix = 'WA_SDK';\n\nexport default class WhatsApp implements WhatsAppClass {\n config: WabaConfigType;\n\n requester: Readonly<Requester>;\n\n readonly messages: MessagesApi;\n readonly templates: TemplateApi;\n readonly phoneNumber: PhoneNumberApi;\n readonly qrCode: QrCodeApi;\n readonly encryption: EncryptionApi;\n readonly twoStepVerification: TwoStepVerificationApi;\n readonly registration: RegistrationApi;\n readonly media: MediaApi;\n readonly waba: WabaApi;\n readonly flow: FlowApi;\n readonly businessProfile: BusinessProfileApi;\n static readonly Enums = SDKEnums;\n\n constructor(config?: WhatsAppConfig) {\n this.config = importConfig(config);\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.userAgent(),\n );\n\n this.messages = new MessagesApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.phoneNumber = new PhoneNumberApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n this.flow = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n LOGGER.log('WhatsApp Node.js SDK instantiated!');\n }\n\n private userAgent(): string {\n const userAgentString = `${headerPrefix}/${'0.0.1'} (Node.js ${process.version})`;\n return userAgentString;\n }\n\n updateTimeout(ms: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = ms;\n LOGGER.log(`Updated request timeout to ${ms}ms`);\n return true;\n }\n\n updatePhoneNumberId(phoneNumberId: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Updated sender phone number id to ${phoneNumberId}`);\n return true;\n }\n\n updateAccessToken(accessToken: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n LOGGER.log(`Updated access token`);\n return true;\n }\n\n updateWabaId(wabaId: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId] = wabaId;\n LOGGER.log(`Updated business account id to ${wabaId}`);\n return true;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/shared/config/importConfig.ts","../src/shared/http/httpsClient.ts","../src/shared/http/request.ts","../src/core/whatsapp/WhatsApp.ts"],"names":["LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","contentType","additionalHeaders","endpoint","effectiveContentType","errorData","isMetaError","formData","urlEncodedBody","headerPrefix","WhatsApp","enums_exports","messages_default","TemplateApi","phone_default","QrCodeApi","encryption_default","twoStepVerification_default","registration_default","media_default","waba_default","flow_default","profile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AAa,CAAA,CAAE,CACxD,CAAA,IACX,CAEA,iBAAkBC,CAAAA,CAAAA,CAA8B,CAC5C,OAAA,IAAA,CAAK,MAAO,CAAA,sBAAA,CAAuCA,CACnD7B,CAAAA,CAAAA,CAAO,GAAI,CAAA,sBAAsB,CAC1B,CAAA,IACX,CAEA,YAAA,CAAauD,EAAyB,CAClC,OAAA,IAAA,CAAK,MAAO,CAAA,sBAAA,CAA0CA,CACtDvD,CAAAA,CAAAA,CAAO,GAAI,CAAA,CAAA,+BAAA,EAAkCuD,CAAM,CAAA,CAAE,CAC9C,CAAA,IACX,CACJ","file":"chunk-7PDRNOEC.js","sourcesContent":["import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\n};\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../types/httpsClient';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../types/enums';\nimport type { RequesterClass } from '../types/request';\nimport { isMetaError, MetaError } from '../utils/isMetaError';\nimport Logger from '../utils/logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport * as SDKEnums from '@shared/types/enums';\nimport Logger from '@shared/utils/logger';\n\nimport EncryptionApi from '@features/encryption';\nimport FlowApi from '@features/flow';\nimport MediaApi from '@features/media';\nimport MessagesApi from '@features/messages';\nimport PhoneNumberApi from '@features/phone';\nimport BusinessProfileApi from '@features/profile';\nimport QrCodeApi from '@features/qrCode/QrCodeApi';\nimport RegistrationApi from '@features/registration';\nimport TemplateApi from '@features/template/TemplateApi';\nimport TwoStepVerificationApi from '@features/twoStepVerification';\nimport WabaApi from '@features/waba';\nimport { importConfig } from '@shared/config/importConfig';\nimport Requester from '@shared/http/request';\nimport { WhatsAppClass } from './types';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nconst headerPrefix = 'WA_SDK';\n\nexport default class WhatsApp implements WhatsAppClass {\n config: WabaConfigType;\n\n requester: Readonly<Requester>;\n\n readonly messages: MessagesApi;\n readonly templates: TemplateApi;\n readonly phoneNumber: PhoneNumberApi;\n readonly qrCode: QrCodeApi;\n readonly encryption: EncryptionApi;\n readonly twoStepVerification: TwoStepVerificationApi;\n readonly registration: RegistrationApi;\n readonly media: MediaApi;\n readonly waba: WabaApi;\n readonly flow: FlowApi;\n readonly businessProfile: BusinessProfileApi;\n static readonly Enums = SDKEnums;\n\n constructor(config?: WhatsAppConfig) {\n this.config = importConfig(config);\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.userAgent(),\n );\n\n this.messages = new MessagesApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.phoneNumber = new PhoneNumberApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n this.flow = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n LOGGER.log('WhatsApp Node.js SDK instantiated!');\n }\n\n private userAgent(): string {\n const userAgentString = `${headerPrefix}/${'0.0.1'} (Node.js ${process.version})`;\n return userAgentString;\n }\n\n updateTimeout(ms: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = ms;\n LOGGER.log(`Updated request timeout to ${ms}ms`);\n return true;\n }\n\n updatePhoneNumberId(phoneNumberId: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Updated sender phone number id to ${phoneNumberId}`);\n return true;\n }\n\n updateAccessToken(accessToken: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n LOGGER.log(`Updated access token`);\n return true;\n }\n\n updateWabaId(wabaId: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId] = wabaId;\n LOGGER.log(`Updated business account id to ${wabaId}`);\n return true;\n }\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import {a as a$1,b}from'./chunk-7PDRNOEC.js';import {a}from'./chunk-VW3LGHTJ.js';import*as f from'crypto';import f__default from'crypto';function M(s){return typeof s=="object"&&s!==null}function m(s){return typeof s=="string"}var F=["data_exchange","INIT","BACK"],v=["data_exchange","INIT"];function _(s){if(!("flow_token"in s&&m(s.flow_token)&&"action"in s))return false;let{action:e,version:r,screen:t,data:o}=s,a=r==="3.0",c=F.includes(e),p=typeof t>"u"||m(t)&&t!=="SUCCESS",d=e==="data_exchange"||M(o);return a&&c&&p&&d}function T(s){if(!("flow_token"in s&&m(s.flow_token)&&"action"in s))return false;let{action:e,screen:r,data:t}=s,o=v.includes(e),a=m(r),c=M(t)&&"error_key"in t&&m(t.error)&&"error_message"in t&&m(t.error_message);return o&&a&&c}function S(s){return "action"in s&&s.action==="ping"}var B="WEBHOOK_UTILS",u=new a(B,process.env.DEBUG==="true");function R(s,e){let r=s.query["hub.mode"],t=s.query["hub.verify_token"],o=s.query["hub.challenge"];return r!==void 0&&t!==void 0&&o!==void 0?r==="subscribe"&&t===e?(u.log("Webhook verified successfully"),{statusCode:200,body:o}):(u.log("Webhook verification failed"),{statusCode:403}):(u.log("Not a webhook verification request - missing required parameters"),{statusCode:400,body:{error:"Invalid webhook verification request"}})}async function k(s,e,r){let t=s.body,o=[];if(t.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return u.log(a),{statusCode:404,body:{error:a}}}for(let a of t.entry)try{let c=a.changes;for(let p of c)p.field==="messages"&&await I(a.id,p.value,e,r);}catch(c){let p=`Error processing webhook: ${c}`;u.log(p),o.push(p);}return {statusCode:200,body:o.length>0?{errors:o}:void 0}}async function H(s,e,r,t){try{if(!x(s,e.WEBHOOK_VERIFICATION_TOKEN||""))return u.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let o=JSON.parse(s.rawBody||"{}"),{decryptedBody:a}=N(o,e),c=t.get("*");if(!c)return u.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(S(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(T(a))return u.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(_(a)){let p=await c(r,a);return {statusCode:200,body:O(p,Buffer.from(o.aes_key,"base64"),Buffer.from(o.initial_vector,"base64"))}}return u.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(o){return u.log(`Error handling flow request: ${o}`),{statusCode:500,body:{error:"Internal server error"}}}}async function I(s,e,r,t){let o=e.metadata,a=e.contacts,c=s,p=o?.display_phone_number||"",d=o?.phone_number_id||"",y=a?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let g=e.statuses;for(let n of g){let l={wabaId:c,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:d,displayPhoneNumber:p,profileName:y,statuses:e.statuses[0],originalData:n};await E(t.messageHandlers.get("statuses"),r,l,"statuses");}return}if(e.messages&&e.messages.length>0){let g=e.messages;for(let n of g){let l=n.type,i={wabaId:c,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:d,displayPhoneNumber:p,profileName:y,originalData:n};switch(l){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;case "reaction":i.reaction=n.reaction;break;default:u.log(`Unknown message type: ${l}`);break}await E(t.preProcessHandler,r,i,"pre-process"),await E(t.messageHandlers.get(l),r,i,l),await E(t.postProcessHandler,r,i,"post-process");}}}async function E(s,e,r,t){if(s)try{await s(e,r);}catch(o){u.log(`Error in ${t} handler: ${o}`);}}function x(s,e){let r=s.headers["x-hub-signature-256"];if(!r||!s.rawBody)return false;let o=`sha256=${f__default.createHmac("sha256",e).update(s.rawBody,"utf8").digest("hex")}`;return f__default.timingSafeEqual(Buffer.from(r),Buffer.from(o))}function N(s,e){let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=s;if(!r||!t||!o)throw new Error("Missing required encryption properties");let a=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),c=e.FLOW_API_PASSPHRASE,p=f__default.createPrivateKey({key:a,passphrase:c}),d;try{d=f__default.privateDecrypt({key:p,padding:f__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let y=Buffer.from(t,"base64"),g=Buffer.from(o,"base64"),l=y.subarray(0,-16),i=y.subarray(-16),w=f__default.createDecipheriv("aes-128-gcm",d,g);w.setAuthTag(i);let P=Buffer.concat([w.update(l),w.final()]).toString("utf-8");return {decryptedBody:JSON.parse(P),aesKeyBuffer:d,initialVectorBuffer:g}}function O(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=f__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([o.update(JSON.stringify(s||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64")}catch(o){throw u.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",h=new a(V,process.env.DEBUG==="true"),W=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$1(e),this.client=new b(e),h.log("WebhookHandler instantiated!");}handleVerification=e=>R(e,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async e=>k(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async e=>H(e,this.config,this.client,this.flowHandlers);onMessage(e,r){this.messageHandlers.set(e,r),h.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,h.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,h.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),h.log(`Registered flow handler for ${e}`);}};var Pe=(s,e)=>f.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{_ as a,T as b,S as c,R as d,k as e,H as f,W as g,Pe as h};//# sourceMappingURL=chunk-GP6T67R7.js.map
3
+ //# sourceMappingURL=chunk-GP6T67R7.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","verifyWebhook","verificationToken","mode","token","challenge","processWebhookMessages","whatsapp","handlers","body","errors","errorMsg","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","v"],"mappings":"yIAaA,SAASA,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,EAASD,CAAiC,CAAA,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAAA,CAAA,CAG/FC,CAAgB,CAAA,CAAA,eAAA,CAAA,MAAkD,EASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAA,EAAK,WAAYA,CACzE,CAAA,CAAA,OAAO,MAGX,CAAA,GAAM,CAAE,MAAA,CAAAC,EAAQ,OAAAC,CAAAA,CAAAA,CAAS,MAAAC,CAAAA,CAAAA,CAAQ,IAAAC,CAAAA,CAAK,EAAIJ,CAGpCK,CAAAA,CAAAA,CAAkBH,IAAY,KAG9BI,CAAAA,CAAAA,CAAiBT,EAAsB,QAASI,CAAAA,CAAa,CAG7DM,CAAAA,CAAAA,CAAiB,OAAOJ,CAAAA,CAAW,KAAgBP,CAASO,CAAAA,CAAM,CAAKA,EAAAA,CAAAA,GAAW,SAGlFK,CAAAA,CAAAA,CAAeP,IAAW,eAAgCP,EAAAA,CAAAA,CAASU,CAAI,CAAA,CAG7E,OAAOC,CAAAA,EAAmBC,GAAkBC,CAAkBC,EAAAA,CAClE,CASO,SAASC,CAAmBT,CAAAA,CAAAA,CAQjC,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CA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AA,CACtD,IAAK,CAAA,iBAAA,CAAoBA,EACzBxB,CAAO,CAAA,GAAA,CAAI,gCAAgC,EAC/C,CAKO,qBAAqBwB,CAA+B,CAAA,CACvD,IAAK,CAAA,kBAAA,CAAqBA,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOoE,CAAoB5C,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAI4C,CAAAA,CAAAA,CAAM5C,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BoE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC3FO,IAAMC,GAAqB,CAAC3D,CAAAA,CAAc4D,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAO5D,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-MTRF47KZ.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n // Check if this is actually a webhook verification request\n const isWebhookVerificationRequest = mode !== undefined && token !== undefined && challenge !== undefined;\n\n if (!isWebhookVerificationRequest) {\n LOGGER.log('Not a webhook verification request - missing required parameters');\n return {\n statusCode: 400,\n body: { error: 'Invalid webhook verification request' },\n };\n }\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\n }\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\n\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport Logger from '@shared/utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport {\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Framework-agnostic WebhookHandler using pure functions\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook verification (framework-agnostic)\n */\n public handleVerification = (request: Pick<WebhookRequest, 'query'>): WebhookResponse => {\n return verifyWebhook(request, this.config.WEBHOOK_VERIFICATION_TOKEN || '');\n };\n\n /**\n * Handle webhook messages (framework-agnostic)\n */\n public handleWebhook = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n };\n\n /**\n * Handle flow requests (framework-agnostic)\n */\n public handleFlow = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n };\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"]}
1
+ {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","verifyWebhook","verificationToken","mode","token","challenge","processWebhookMessages","whatsapp","handlers","body","errors","errorMsg","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","q"],"mappings":"yIAaA,SAASA,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,EAASD,CAAiC,CAAA,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAAA,CAAA,CAG/FC,CAAgB,CAAA,CAAA,eAAA,CAAA,MAAkD,EASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAA,EAAK,WAAYA,CACzE,CAAA,CAAA,OAAO,MAGX,CAAA,GAAM,CAAE,MAAA,CAAAC,EAAQ,OAAAC,CAAAA,CAAAA,CAAS,MAAAC,CAAAA,CAAAA,CAAQ,IAAAC,CAAAA,CAAK,EAAIJ,CAGpCK,CAAAA,CAAAA,CAAkBH,IAAY,KAG9BI,CAAAA,CAAAA,CAAiBT,EAAsB,QAASI,CAAAA,CAAa,CAG7DM,CAAAA,CAAAA,CAAiB,OAAOJ,CAAAA,CAAW,KAAgBP,CAASO,CAAAA,CAAM,CAAKA,EAAAA,CAAAA,GAAW,SAGlFK,CAAAA,CAAAA,CAAeP,IAAW,eAAgCP,EAAAA,CAAAA,CAASU,CAAI,CAAA,CAG7E,OAAOC,CAAAA,EAAmBC,GAAkBC,CAAkBC,EAAAA,CAClE,CASO,SAASC,CAAmBT,CAAAA,CAAAA,C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AAAA,EAAAA,CAAI,EAAE,EACvD,CAKO,oBAAoB5C,CAA+B,CAAA,CACtD,IAAK,CAAA,iBAAA,CAAoBA,EACzBxB,CAAO,CAAA,GAAA,CAAI,gCAAgC,EAC/C,CAKO,qBAAqBwB,CAA+B,CAAA,CACvD,IAAK,CAAA,kBAAA,CAAqBA,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOoE,CAAoB5C,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAI4C,CAAAA,CAAAA,CAAM5C,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BoE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC3FO,IAAMC,GAAqB,CAAC3D,CAAAA,CAAc4D,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAO5D,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-GP6T67R7.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n // Check if this is actually a webhook verification request\n const isWebhookVerificationRequest = mode !== undefined && token !== undefined && challenge !== undefined;\n\n if (!isWebhookVerificationRequest) {\n LOGGER.log('Not a webhook verification request - missing required parameters');\n return {\n statusCode: 400,\n body: { error: 'Invalid webhook verification request' },\n };\n }\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\n }\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\n\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport Logger from '@shared/utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport {\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Framework-agnostic WebhookHandler using pure functions\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook verification (framework-agnostic)\n */\n public handleVerification = (request: Pick<WebhookRequest, 'query'>): WebhookResponse => {\n return verifyWebhook(request, this.config.WEBHOOK_VERIFICATION_TOKEN || '');\n };\n\n /**\n * Handle webhook messages (framework-agnostic)\n */\n public handleWebhook = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n };\n\n /**\n * Handle flow requests (framework-agnostic)\n */\n public handleFlow = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n };\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-4C666HHU.js';var d={};a(d,{AudioMediaTypesEnum:()=>v,BusinessVerticalEnum:()=>b,ButtonPositionEnum:()=>t,ButtonTypesEnum:()=>Z,CategoryEnum:()=>T,ComponentTypesEnum:()=>W,ConversationTypesEnum:()=>l,CurrencyCodesEnum:()=>z,DataLocalizationRegionEnum:()=>p,DocumentMediaTypesEnum:()=>w,HttpMethodsEnum:()=>H,ImageMediaTypesEnum:()=>k,InteractiveTypesEnum:()=>X,LanguagesEnum:()=>$,MessageTypesEnum:()=>Y,ParametersTypesEnum:()=>L,ReferralSourceTypesEnum:()=>j,RequestCodeMethodsEnum:()=>q,StatusEnum:()=>h,StickerMediaTypesEnum:()=>J,SubTypeEnum:()=>x,SystemChangeTypesEnum:()=>f,TemplateStatusEnum:()=>F,VideoMediaTypesEnum:()=>i,WabaConfigEnum:()=>V,WebhookTypesEnum:()=>Q});var T=(I=>(I.Authentication="AUTHENTICATION",I.Marketing="MARKETING",I.Utility="UTILITY",I))(T||{}),F=(I=>(I.Approved="APPROVED",I.Pending="PENDING",I.Rejected="REJECTED",I))(F||{}),H=(_=>(_.Get="GET",_.Post="POST",_.Put="PUT",_.Delete="DELETE",_))(H||{}),Y=(P=>(P.Audio="audio",P.Contacts="contacts",P.Document="document",P.Image="image",P.Interactive="interactive",P.Location="location",P.Reaction="reaction",P.Sticker="sticker",P.Template="template",P.Text="text",P.Video="video",P.Button="button",P.Order="order",P.System="system",P.Unknown="unknown",P.Statuses="statuses",P["*"]="*",P))(Y||{}),L=(O=>(O.Action="ACTION",O.CouponCode="COUPON_CODE",O.Currency="CURRENCY",O.DateTime="DATE_TIME",O.Document="DOCUMENT",O.ExpirationTimeMs="EXPIRATION_TIME_MS",O.Image="IMAGE",O.LimitedTimeOffer="LIMITED_TIME_OFFER",O.Location="LOCATION",O.OrderStatus="ORDER_STATUS",O.Payload="PAYLOAD",O.Product="PRODUCT",O.Text="TEXT",O.TtlMinutes="TTL_MINUTES",O.Video="VIDEO",O.WebviewInteraction="WEBVIEW_INTERACTION",O.WebviewPresentation="WEBVIEW_PRESENTATION",O))(L||{}),X=(N=>(N.Button="button",N.List="list",N.Product="product",N.ProductList="product_list",N.CtaUrl="cta_url",N.LocationRequest="location_request_message",N.AddressMessage="address_message",N.Flow="flow",N))(X||{}),Z=(S=>(S.QuickReply="quick_reply",S.URL="url",S))(Z||{}),t=(U=>(U[U.First=1]="First",U[U.Second=2]="Second",U[U.Third=3]="Third",U[U.Fourth=4]="Fourth",U[U.Fifth=5]="Fifth",U))(t||{}),x=(M=>(M.Catalog="CATALOG",M.CopyCode="COPY_CODE",M.Flow="FLOW",M.Mpm="MPM",M.OrderDetails="ORDER_DETAILS",M.QuickReply="QUICK_REPLY",M.Reminder="REMINDER",M.Url="URL",M.VoiceCall="VOICE_CALL",M))(x||{}),W=(_=>(_.Header="HEADER",_.Body="BODY",_.Button="BUTTON",_.Footer="FOOTER",_))(W||{}),V=(G=>(G.AppId="M4D_APP_ID",G.Port="WA_PORT",G.AppSecret="M4D_APP_SECRET",G.PhoneNumberId="WA_PHONE_NUMBER_ID",G.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",G.APIVersion="CLOUD_API_VERSION",G.AccessToken="CLOUD_API_ACCESS_TOKEN",G.WebhookEndpoint="WEBHOOK_ENDPOINT",G.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",G.ListenerPort="LISTENER_PORT",G.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",G.RequestTimeout="REQUEST_TIMEOUT",G.Debug="DEBUG",G.PrivatePem="FLOW_API_PRIVATE_PEM",G.Passphrase="FLOW_API_PASSPHRASE",G))(V||{}),l=(I=>(I.BusinessInitiated="business_initiated",I.CustomerInitiated="customer_initiated",I.ReferralConversion="referral_conversion",I))(l||{}),h=(I=>(I.Delivered="delivered",I.Read="read",I.Sent="sent",I))(h||{}),i=(S=>(S.Mp4="video/mp4",S.Threegp="video/3gp",S))(i||{}),J=(g=>(g.Webp="image/webp",g))(J||{}),k=(S=>(S.Jpeg="image/jpeg",S.Png="image/png",S))(k||{}),w=(N=>(N.Text="text/plain",N.Pdf="application/pdf",N.Ppt="application/vnd.ms-powerpoint",N.Word="application/msword",N.Excel="application/vnd.ms-excel",N.OpenDoc="application/vnd.openxmlformats-officedocument.wordprocessingml.document",N.OpenPres="application/vnd.openxmlformats-officedocument.presentationml.presentation",N.OpenSheet="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",N))(w||{}),v=(U=>(U.Aac="audio/aac",U.Mp4="audio/mp4",U.Mpeg="audio/mpeg",U.Amr="audio/amr",U.Ogg="audio/ogg",U))(v||{}),Q=(K=>(K.Audio="audio",K.Button="button",K.Document="document",K.Text="text",K.Image="image",K.Interactive="interactive",K.Order="order",K.Sticker="sticker",K.System="system",K.Unknown="unknown",K.Video="video",K))(Q||{}),f=(S=>(S.CustomerChangedNumber="customer_changed_number",S.CustomerIdentityChanged="customer_identity_changed",S))(f||{}),j=(S=>(S.Ad="ad",S.Post="post",S))(j||{}),q=(S=>(S.Sms="SMS",S.Voice="VOICE",S))(q||{}),$=(A=>(A.Afrikaans="af",A.Albanian="sq",A.Arabic="ar",A.Azerbaijani="az",A.Bengali="bn",A.Bulgarian="bg",A.Catalan="ca",A.Chinese_CHN="zh_CN",A.Chinese_HKG="zh_HK",A.Chinese_TAI="zh_TW",A.Croatian="hr",A.Czech="cs",A.Danish="da",A.Dutch="nl",A.English="en",A.English_UK="en_GB",A.English_US="en_US",A.Estonian="et",A.Filipino="fil",A.Finnish="fi",A.French="fr",A.Georgian="ka",A.German="de",A.Greek="el",A.Gujarati="gu",A.Hausa="ha",A.Hebrew="he",A.Hindi="hi",A.Hungarian="hu",A.Indonesian="id",A.Irish="ga",A.Italian="it",A.Japanese="ja",A.Kannada="kn",A.Kazakh="kk",A.Kinyarwanda="rw_RW",A.Korean="ko",A.Kyrgyz_Kyrgyzstan="ky_KG",A.Lao="lo",A.Latvian="lv",A.Lithuanian="lt",A.Macedonian="mk",A.Malay="ms",A.Malayalam="ml",A.Marathi="mr",A.Norwegian="nb",A.Persian="fa",A.Polish="pl",A.Portuguese_BR="pt_BR",A.Portuguese_POR="pt_PT",A.Punjabi="pa",A.Romanian="ro",A.Russian="ru",A.Serbian="sr",A.Slovak="sk",A.Slovenian="sl",A.Spanish="es",A.Spanish_ARG="es_AR",A.Spanish_SPA="es_ES",A.Spanish_MEX="es_MX",A.Swahili="sw",A.Swedish="sv",A.Tamil="ta",A.Telugu="te",A.Thai="th",A.Turkish="tr",A.Ukrainian="uk",A.Urdu="ur",A.Uzbek="uz",A.Vietnamese="vi",A.Zulu="zu",A))($||{}),z=(R=>(R.AFN="AFN",R.EUR="EUR",R.ALL="ALL",R.DZD="DZD",R.USD="USD",R.AOA="AOA",R.XCD="XCD",R.ARS="ARS",R.AMD="AMD",R.AWG="AWG",R.AUD="AUD",R.AZN="AZN",R.BSD="BSD",R.BHD="BHD",R.BDT="BDT",R.BBD="BBD",R.BYN="BYN",R.BZD="BZD",R.XOF="XOF",R.BMD="BMD",R.INR="INR",R.BTN="BTN",R.BOB="BOB",R.BOV="BOV",R.BAM="BAM",R.BWP="BWP",R.NOK="NOK",R.BRL="BRL",R.BND="BND",R.BGN="BGN",R.BIF="BIF",R.CVE="CVE",R.KHR="KHR",R.XAF="XAF",R.CAD="CAD",R.KYD="KYD",R.CLP="CLP",R.CLF="CLF",R.CNY="CNY",R.COP="COP",R.COU="COU",R.KMF="KMF",R.CDF="CDF",R.NZD="NZD",R.CRC="CRC",R.HRK="HRK",R.CUP="CUP",R.CUC="CUC",R.ANG="ANG",R.CZK="CZK",R.DKK="DKK",R.DJF="DJF",R.DOP="DOP",R.EGP="EGP",R.SVC="SVC",R.ERN="ERN",R.SZL="SZL",R.ETB="ETB",R.FKP="FKP",R.FJD="FJD",R.XPF="XPF",R.GMD="GMD",R.GEL="GEL",R.GHS="GHS",R.GIP="GIP",R.GTQ="GTQ",R.GBP="GBP",R.GNF="GNF",R.GYD="GYD",R.HTG="HTG",R.HNL="HNL",R.HKD="HKD",R.HUF="HUF",R.ISK="ISK",R.IDR="IDR",R.XDR="XDR",R.IRR="IRR",R.IQD="IQD",R.ILS="ILS",R.JMD="JMD",R.JPY="JPY",R.JOD="JOD",R.KZT="KZT",R.KES="KES",R.KPW="KPW",R.KRW="KRW",R.KWD="KWD",R.KGS="KGS",R.LAK="LAK",R.LBP="LBP",R.LSL="LSL",R.ZAR="ZAR",R.LRD="LRD",R.LYD="LYD",R.CHF="CHF",R.MOP="MOP",R.MKD="MKD",R.MGA="MGA",R.MWK="MWK",R.MYR="MYR",R.MVR="MVR",R.MRU="MRU",R.MUR="MUR",R.XUA="XUA",R.MXN="MXN",R.MXV="MXV",R.MDL="MDL",R.MNT="MNT",R.MAD="MAD",R.MZN="MZN",R.MMK="MMK",R.NAD="NAD",R.NPR="NPR",R.NIO="NIO",R.NGN="NGN",R.OMR="OMR",R.PKR="PKR",R.PAB="PAB",R.PGK="PGK",R.PYG="PYG",R.PEN="PEN",R.PHP="PHP",R.PLN="PLN",R.QAR="QAR",R.RON="RON",R.RUB="RUB",R.RWF="RWF",R.SHP="SHP",R.WST="WST",R.STN="STN",R.SAR="SAR",R.RSD="RSD",R.SCR="SCR",R.SLL="SLL",R.SGD="SGD",R.XSU="XSU",R.SBD="SBD",R.SOS="SOS",R.SSP="SSP",R.LKR="LKR",R.SDG="SDG",R.SRD="SRD",R.SEK="SEK",R.CHE="CHE",R.CHW="CHW",R.SYP="SYP",R.TWD="TWD",R.TJS="TJS",R.TZS="TZS",R.THB="THB",R.TOP="TOP",R.TTD="TTD",R.TND="TND",R.TRY="TRY",R.TMT="TMT",R.UGX="UGX",R.UAH="UAH",R.AED="AED",R.USN="USN",R.UYU="UYU",R.UYI="UYI",R.UYW="UYW",R.UZS="UZS",R.VUV="VUV",R.VES="VES",R.VND="VND",R.YER="YER",R.ZMW="ZMW",R.ZWL="ZWL",R.XBA="XBA",R.XBB="XBB",R.XBC="XBC",R.XBD="XBD",R.XTS="XTS",R.XXX="XXX",R.XAU="XAU",R.XPD="XPD",R.XPT="XPT",R.XAG="XAG",R.AFA="AFA",R.FIM="FIM",R.ALK="ALK",R.ADP="ADP",R.ESP="ESP",R.FRF="FRF",R.AOK="AOK",R.AON="AON",R.AOR="AOR",R.ARA="ARA",R.ARP="ARP",R.ARY="ARY",R.RUR="RUR",R.ATS="ATS",R.AYM="AYM",R.AZM="AZM",R.BYB="BYB",R.BYR="BYR",R.BEC="BEC",R.BEF="BEF",R.BEL="BEL",R.BOP="BOP",R.BAD="BAD",R.BRB="BRB",R.BRC="BRC",R.BRE="BRE",R.BRN="BRN",R.BRR="BRR",R.BGJ="BGJ",R.BGK="BGK",R.BGL="BGL",R.BUK="BUK",R.HRD="HRD",R.CYP="CYP",R.CSJ="CSJ",R.CSK="CSK",R.ECS="ECS",R.ECV="ECV",R.GQE="GQE",R.EEK="EEK",R.XEU="XEU",R.GEK="GEK",R.DDM="DDM",R.DEM="DEM",R.GHC="GHC",R.GHP="GHP",R.GRD="GRD",R.GNE="GNE",R.GNS="GNS",R.GWE="GWE",R.GWP="GWP",R.ITL="ITL",R.ISJ="ISJ",R.IEP="IEP",R.ILP="ILP",R.ILR="ILR",R.LAJ="LAJ",R.LVL="LVL",R.LVR="LVR",R.LSM="LSM",R.ZAL="ZAL",R.LTL="LTL",R.LTT="LTT",R.LUC="LUC",R.LUF="LUF",R.LUL="LUL",R.MGF="MGF",R.MVQ="MVQ",R.MLF="MLF",R.MTL="MTL",R.MTP="MTP",R.MRO="MRO",R.MXP="MXP",R.MZE="MZE",R.MZM="MZM",R.NLG="NLG",R.NIC="NIC",R.PEH="PEH",R.PEI="PEI",R.PES="PES",R.PLZ="PLZ",R.PTE="PTE",R.ROK="ROK",R.ROL="ROL",R.STD="STD",R.CSD="CSD",R.SKK="SKK",R.SIT="SIT",R.RHD="RHD",R.ESA="ESA",R.ESB="ESB",R.SDD="SDD",R.SDP="SDP",R.SRG="SRG",R.CHC="CHC",R.TJR="TJR",R.TPE="TPE",R.TRL="TRL",R.TMM="TMM",R.UGS="UGS",R.UGW="UGW",R.UAK="UAK",R.SUR="SUR",R.USS="USS",R.UYN="UYN",R.UYP="UYP",R.VEB="VEB",R.VEF="VEF",R.VNC="VNC",R.YDD="YDD",R.YUD="YUD",R.YUM="YUM",R.YUN="YUN",R.ZRN="ZRN",R.ZRZ="ZRZ",R.ZMK="ZMK",R.ZWC="ZWC",R.ZWD="ZWD",R.ZWN="ZWN",R.ZWR="ZWR",R.XFO="XFO",R.XRE="XRE",R.XFU="XFU",R))(z||{}),p=(B=>(B.AU="AU",B.ID="ID",B.IN="IN",B.JP="JP",B.SG="SG",B.KR="KR",B.DE="DE",B.CH="CH",B.GB="GB",B.BR="BR",B.BH="BH",B.ZA="ZA",B.AE="AE",B.CA="CA",B))(p||{}),b=(D=>(D.ALCOHOL="ALCOHOL",D.APPAREL="APPAREL",D.AUTO="AUTO",D.BEAUTY="BEAUTY",D.EDU="EDU",D.ENTERTAIN="ENTERTAIN",D.EVENT_PLAN="EVENT_PLAN",D.FINANCE="FINANCE",D.GOVT="GOVT",D.GROCERY="GROCERY",D.HEALTH="HEALTH",D.HOTEL="HOTEL",D.NONPROFIT="NONPROFIT",D.ONLINE_GAMBLING="ONLINE_GAMBLING",D.OTC_DRUGS="OTC_DRUGS",D.OTHER="OTHER",D.PHYSICAL_GAMBLING="PHYSICAL_GAMBLING",D.PROF_SERVICES="PROF_SERVICES",D.RESTAURANT="RESTAURANT",D.RETAIL="RETAIL",D.TRAVEL="TRAVEL",D))(b||{});export{d as A,T as a,F as b,H as c,Y as d,L as e,X as f,Z as g,t as h,x as i,W as j,V as k,l,h as m,i as n,J as o,k as p,w as q,v as r,Q as s,f as t,j as u,q as v,$ as w,z as x,p as y,b as z};//# sourceMappingURL=chunk-XL2LO2UM.js.map
2
+ //# sourceMappingURL=chunk-XL2LO2UM.js.map