meta-cloud-api 0.2.35 → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BusinessProfileApi-BJ9zy6c2.d.ts → BusinessProfileApi-DO28tMcf.d.ts} +2 -2
- package/dist/{EncryptionApi-1aZ13Qyh.d.ts → EncryptionApi-CFuuNH2K.d.ts} +1 -1
- package/dist/{FlowApi-QDjrvCLp.d.ts → FlowApi-Mwlby1Rl.d.ts} +1 -1
- package/dist/{MediaApi-V44kQnsN.d.ts → MediaApi-CyoByati.d.ts} +1 -1
- package/dist/{MessageApi-BhSK0pfd.d.ts → MessageApi-BU1WUNKS.d.ts} +2 -2
- package/dist/{PhoneNumberApi-CPAIS17R.d.ts → PhoneNumberApi-C3Hmh_nZ.d.ts} +1 -1
- package/dist/{QrCodeApi-BjPYQIWF.d.ts → QrCodeApi-BPsHp3ad.d.ts} +1 -1
- package/dist/{RegistrationApi-CGlvAgaz.d.ts → RegistrationApi-DI9NskvK.d.ts} +2 -2
- package/dist/{TemplateApi-D_23Ys02.d.ts → TemplateApi-DXr47lZe.d.ts} +41 -6
- package/dist/{TwoStepVerificationApi-CXMjxkUl.d.ts → TwoStepVerificationApi-CICKknhN.d.ts} +1 -1
- package/dist/{WabaApi-BwnBkMPm.d.ts → WabaApi-DZurKSzA.d.ts} +1 -1
- package/dist/{WebhookHandler-Dn1NlyGm.d.ts → WebhookHandler-q8tq2j0d.d.ts} +2 -2
- package/dist/{base-DtfdeScM.d.ts → base-GKqD_DhO.d.ts} +1 -1
- package/dist/{chunk-LYB4T5PE.js → chunk-4LWNMCXG.js} +3 -3
- package/dist/{chunk-LYB4T5PE.js.map → chunk-4LWNMCXG.js.map} +1 -1
- package/dist/chunk-FLDBNTNY.js +2 -0
- package/dist/chunk-FLDBNTNY.js.map +1 -0
- package/dist/{chunk-YJWNS2MK.js → chunk-MTRF47KZ.js} +3 -3
- package/dist/{chunk-YJWNS2MK.js.map → chunk-MTRF47KZ.js.map} +1 -1
- package/dist/chunk-QCFJGLDQ.js +2 -0
- package/dist/chunk-QCFJGLDQ.js.map +1 -0
- package/dist/core/webhook/index.d.ts +14 -14
- package/dist/core/webhook/index.js +1 -1
- package/dist/core/whatsapp/index.d.ts +13 -13
- package/dist/core/whatsapp/index.js +1 -1
- package/dist/{enums-DcRC4vFO.d.ts → enums-CM95zXd_.d.ts} +18 -8
- package/dist/features/encryption/index.d.ts +4 -4
- package/dist/features/encryption/index.js +1 -1
- package/dist/features/flow/index.d.ts +4 -4
- package/dist/features/flow/index.js +1 -1
- package/dist/features/media/index.d.ts +4 -4
- package/dist/features/media/index.js +1 -1
- package/dist/features/messages/index.d.ts +4 -4
- package/dist/features/messages/index.js +1 -1
- package/dist/features/phone/index.d.ts +4 -4
- package/dist/features/phone/index.js +1 -1
- package/dist/features/profile/index.d.ts +4 -4
- package/dist/features/profile/index.js +1 -1
- package/dist/features/qrCode/index.d.ts +4 -4
- package/dist/features/qrCode/index.js +1 -1
- package/dist/features/registration/index.d.ts +4 -4
- package/dist/features/registration/index.js +1 -1
- package/dist/features/template/index.d.ts +210 -5
- package/dist/features/template/index.js +1 -1
- package/dist/features/twoStepVerification/index.d.ts +4 -4
- package/dist/features/twoStepVerification/index.js +1 -1
- package/dist/features/waba/index.d.ts +4 -4
- package/dist/features/waba/index.js +1 -1
- package/dist/index.d.ts +15 -15
- package/dist/index.js +1 -1
- package/dist/shared/types/config.d.ts +1 -1
- package/dist/shared/types/enums.d.ts +1 -1
- package/dist/shared/types/enums.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-H55VIWDI.js +0 -2
- package/dist/chunk-H55VIWDI.js.map +0 -1
- package/dist/chunk-SMHCU5MN.js +0 -2
- package/dist/chunk-SMHCU5MN.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { d as BaseClass, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-
|
|
1
|
+
import { d as BaseClass, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
|
|
2
2
|
import { WabaConfigType } from './shared/types/config.js';
|
|
3
|
-
import { B as BusinessVerticalEnum } from './enums-
|
|
3
|
+
import { B as BusinessVerticalEnum } from './enums-CM95zXd_.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-
|
|
1
|
+
import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.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-
|
|
1
|
+
import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.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-
|
|
1
|
+
import { d as BaseClass, G as GeneralRequestBody, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
|
|
2
2
|
import { WabaConfigType } from './shared/types/config.js';
|
|
3
|
-
import { g as InteractiveTypesEnum,
|
|
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';
|
|
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-
|
|
1
|
+
import { P as Paging, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.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-
|
|
1
|
+
import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.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-
|
|
1
|
+
import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
|
|
2
2
|
import { WabaConfigType } from './shared/types/config.js';
|
|
3
|
-
import { D as DataLocalizationRegionEnum } from './enums-
|
|
3
|
+
import { D as DataLocalizationRegionEnum } from './enums-CM95zXd_.js';
|
|
4
4
|
|
|
5
5
|
type RegistrationRequest = {
|
|
6
6
|
messaging_product: 'whatsapp';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { G as GeneralRequestBody, R as ResponseSuccess, b as ResponsePagination, B as BaseAPI, a as RequesterClass } from './base-
|
|
1
|
+
import { G as GeneralRequestBody, R as ResponseSuccess, b as ResponsePagination, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
|
|
2
2
|
import { WabaConfigType } from './shared/types/config.js';
|
|
3
|
-
import { L as LanguagesEnum,
|
|
3
|
+
import { L as LanguagesEnum, a as CategoryEnum, T as TemplateStatusEnum } from './enums-CM95zXd_.js';
|
|
4
4
|
|
|
5
|
-
type TemplateFormat = 'TEXT' | 'IMAGE' | 'VIDEO' | 'DOCUMENT' | 'LOCATION';
|
|
5
|
+
type TemplateFormat = 'TEXT' | 'IMAGE' | 'VIDEO' | 'DOCUMENT' | 'LOCATION' | 'PRODUCT';
|
|
6
6
|
type PhoneNumberButton = {
|
|
7
7
|
type: 'PHONE_NUMBER';
|
|
8
8
|
text: string;
|
|
@@ -33,14 +33,32 @@ type FlowButton = {
|
|
|
33
33
|
};
|
|
34
34
|
type MPMButton = {
|
|
35
35
|
type: 'MPM';
|
|
36
|
+
action?: {
|
|
37
|
+
thumbnail_product_retailer_id: string;
|
|
38
|
+
sections: Array<{
|
|
39
|
+
title?: string;
|
|
40
|
+
product_items: Array<{
|
|
41
|
+
product_retailer_id: string;
|
|
42
|
+
}>;
|
|
43
|
+
}>;
|
|
44
|
+
};
|
|
36
45
|
};
|
|
37
46
|
type OTPButton = {
|
|
38
47
|
type: 'OTP';
|
|
39
48
|
};
|
|
40
49
|
type SPMButton = {
|
|
41
50
|
type: 'SPM';
|
|
51
|
+
action?: {
|
|
52
|
+
product_retailer_id: string;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
type CatalogButton = {
|
|
56
|
+
type: 'CATALOG';
|
|
57
|
+
action?: {
|
|
58
|
+
thumbnail_product_retailer_id: string;
|
|
59
|
+
};
|
|
42
60
|
};
|
|
43
|
-
type TemplateButton = PhoneNumberButton | URLButton | QuickReplyButton | CopyCodeButton | FlowButton | MPMButton | OTPButton | SPMButton;
|
|
61
|
+
type TemplateButton = PhoneNumberButton | URLButton | QuickReplyButton | CopyCodeButton | FlowButton | MPMButton | OTPButton | SPMButton | CatalogButton;
|
|
44
62
|
type TemplateHeaderExample = {
|
|
45
63
|
header_text?: string[];
|
|
46
64
|
header_text_named_params?: Array<{
|
|
@@ -70,7 +88,24 @@ type TemplateFooter = {
|
|
|
70
88
|
type: 'FOOTER';
|
|
71
89
|
text: string;
|
|
72
90
|
};
|
|
73
|
-
type
|
|
91
|
+
type TemplateButtons = {
|
|
92
|
+
type: 'BUTTONS';
|
|
93
|
+
buttons: TemplateButton[];
|
|
94
|
+
};
|
|
95
|
+
type TemplateLimitedTimeOffer = {
|
|
96
|
+
type: 'LIMITED_TIME_OFFER';
|
|
97
|
+
limited_time_offer: {
|
|
98
|
+
expiration_time_ms: number;
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
type TemplateCarousel = {
|
|
102
|
+
type: 'CAROUSEL';
|
|
103
|
+
cards: Array<{
|
|
104
|
+
card_index: number;
|
|
105
|
+
components: ComponentTypes[];
|
|
106
|
+
}>;
|
|
107
|
+
};
|
|
108
|
+
type ComponentTypes = TemplateHeader | TemplateBody | TemplateFooter | TemplateButtons | TemplateLimitedTimeOffer | TemplateCarousel;
|
|
74
109
|
type TemplateRequestBody = GeneralRequestBody & {
|
|
75
110
|
name: string;
|
|
76
111
|
language: LanguagesEnum;
|
|
@@ -114,4 +149,4 @@ declare class TemplateApi extends BaseAPI implements TemplateClass {
|
|
|
114
149
|
deleteTemplate(params: TemplateDeleteParams): Promise<ResponseSuccess>;
|
|
115
150
|
}
|
|
116
151
|
|
|
117
|
-
export {
|
|
152
|
+
export { type CatalogButton as C, type FlowButton as F, type MPMButton as M, type OTPButton as O, type PhoneNumberButton as P, type QuickReplyButton as Q, type SPMButton as S, type TemplateFormat as T, type URLButton as U, type TemplateRequestBody as a, TemplateClass as b, type TemplateDeleteParams as c, type TemplateGetParams as d, type TemplateResponse as e, TemplateApi as f, type ComponentTypes as g, type CopyCodeButton as h, type TemplateBody as i, type TemplateButton as j, type TemplateButtons as k, type TemplateCarousel as l, type TemplateFooter as m, type TemplateHeader as n, type TemplateHeaderExample as o, type TemplateLimitedTimeOffer as p };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-
|
|
1
|
+
import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
|
|
2
2
|
import { WabaConfigType } from './shared/types/config.js';
|
|
3
3
|
|
|
4
4
|
type TwoStepVerificationRequest = {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { WabaConfigType, WhatsAppConfig } from './shared/types/config.js';
|
|
2
|
-
import { M as MessageTypesEnum } from './enums-
|
|
3
|
-
import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-
|
|
2
|
+
import { M as MessageTypesEnum } from './enums-CM95zXd_.js';
|
|
3
|
+
import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-Mwlby1Rl.js';
|
|
4
4
|
import { WhatsApp } from './core/whatsapp/index.js';
|
|
5
5
|
|
|
6
6
|
interface WebhookContact {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { WabaConfigType } from './shared/types/config.js';
|
|
2
|
-
import { H as HttpMethodsEnum } from './enums-
|
|
2
|
+
import { H as HttpMethodsEnum } from './enums-CM95zXd_.js';
|
|
3
3
|
|
|
4
4
|
type GeneralRequestBody = Record<string, unknown>;
|
|
5
5
|
interface RequesterResponseInterface<T> {
|
|
@@ -1,3 +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 {z}from'./chunk-
|
|
2
|
-
export{N as a,l as b};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
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 {z}from'./chunk-QCFJGLDQ.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=z;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-4LWNMCXG.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-4LWNMCXG.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,MAA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igType, 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_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,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I,CAAA,oCAAoC,EACnD,CAEQ,SAAoB,EAAA,CAExB,OADwB,CAAA,EAAGwC,CAAY,CAAA,gBAAA,EAAwB,OAAQ,CAAA,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"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function m(e){let t={type:"HEADER",format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function n(e){let t={type:"BODY",text:e.text};return e.example&&(t.example=e.example),t}function u(e){return {type:"FOOTER",text:e.text}}function l(e){let t=[];if(e.phone_number&&t.push({type:"PHONE_NUMBER",text:e.phone_number.text,phone_number:e.phone_number.phone_number}),e.url){let a={type:"URL",text:e.url.text,url:e.url.url};e.url.example&&(a.example=[e.url.example]),t.push(a);}if(e.quick_reply&&e.quick_reply.forEach(a=>{t.push({type:"QUICK_REPLY",text:a.text});}),e.copy_code&&t.push({type:"COPY_CODE",example:e.copy_code.example}),e.flow){let a={type:"FLOW",text:e.flow.text};e.flow.flow_id&&(a.flow_id=e.flow.flow_id),e.flow.flow_name&&(a.flow_name=e.flow.flow_name),e.flow.flow_json&&(a.flow_json=e.flow.flow_json),e.flow.flow_action&&(a.flow_action=e.flow.flow_action),e.flow.navigate_screen&&(a.navigate_screen=e.flow.navigate_screen),t.push(a);}return e.mpm&&t.push({type:"MPM"}),e.otp&&t.push({type:"OTP"}),e.spm&&t.push({type:"SPM"}),t.length>0?[{type:"BUTTONS",buttons:t}]:[]}function f(e){return e.map(t=>{switch(t.type){case "text":return t.value;case "currency":return t.fallback_value;case "date_time":return t.fallback_value;case "image":case "video":case "document":return t.handle||t.link||"";case "location":return t.name||"";case "product":return t.product_retailer_id;default:return ""}})}function s(e){let t=[];if(e.header&&t.push(m(e.header)),e.body&&t.push(n(e.body)),e.footer&&t.push(u(e.footer)),e.buttons&&t.push(...l(e.buttons)),e.carousel){let a=[];e.carousel.cards.forEach((r,p)=>{if(r.image||r.video||r.product){let o=r.image?"IMAGE":r.video?"VIDEO":"DOCUMENT",c=r.image||r.video||r.product||"";a.push({type:"HEADER",format:o,example:{header_handle:[c]}});}r.body&&a.push({type:"BODY",text:r.body,example:r.bodyParameters?{body_text:[f(r.bodyParameters)]}:void 0}),r.buttons&&a.push(...l(r.buttons));}),t.push(...a);}return e.limitedTimeOffer&&t.push({type:"LIMITED_TIME_OFFER",limited_time_offer:{expiration_time_ms:e.limitedTimeOffer.expiration_time_ms}}),{name:e.name,language:e.language,category:e.category,components:t.length>0?t:void 0}}function d(e){let t=[],a="*{{1}}* is your verification code.";return e.add_security_recommendation&&(a+=" For your security, do not share this code."),e.code_expiration_minutes&&(a+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:"BODY",text:a,example:{body_text:[["123456"]]}}),t.push({type:"BUTTONS",buttons:[{type:"OTP"}]}),{name:e.name,language:e.language,category:"AUTHENTICATION",components:t}}function i(e){let t=[],a="Your security code is *{{1}}*.";return e.add_security_recommendation&&(a+=" Do not share this code with anyone."),e.code_expiration_minutes&&(a+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:"BODY",text:a,example:{body_text:[["ABCD1234"]]}}),e.copy_code_button&&t.push({type:"BUTTONS",buttons:[{type:"COPY_CODE",example:"ABCD1234"}]}),{name:e.name,language:e.language,category:"AUTHENTICATION",components:t}}function y(e){let t=[];return e.header&&t.push(m({...e.header,format:"TEXT"})),t.push(n(e.body)),e.footer&&t.push(u(e.footer)),t.push({type:"BUTTONS",buttons:[{type:"CATALOG",action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id}}]}),{name:e.name,language:e.language,category:"MARKETING",components:t}}function T(e){let t=[];return e.header&&t.push(m({...e.header,format:"TEXT"})),t.push(n(e.body)),e.footer&&t.push(u(e.footer)),t.push({type:"BUTTONS",buttons:[{type:"COPY_CODE",example:e.coupon_code}]}),{name:e.name,language:e.language,category:"MARKETING",components:t}}function h(e){let t=[];return t.push({type:"LIMITED_TIME_OFFER",limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(m({...e.header,format:"TEXT"})),t.push(n(e.body)),e.footer&&t.push(u(e.footer)),{name:e.name,language:e.language,category:"MARKETING",components:t}}function _(e){let t=[],a=[];return e.cards.forEach((r,p)=>{let o=[];o.push({type:"HEADER",format:r.header.format,example:r.header.example}),o.push(n(r.body)),r.buttons&&o.push(...l(r.buttons)),a.push({card_index:p,components:o});}),t.push({type:"CAROUSEL",cards:a}),{name:e.name,language:e.language,category:"MARKETING",components:t}}function g(e){let t=[];return e.header&&t.push(m({...e.header,format:"TEXT"})),t.push(n(e.body)),e.footer&&t.push(u(e.footer)),t.push({type:"BUTTONS",buttons:[{type:"MPM",action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id,sections:e.sections}}]}),{name:e.name,language:e.language,category:"MARKETING",components:t}}function x(e){let t=[];e.header&&t.push(m({...e.header,format:"TEXT"})),t.push(n(e.body)),e.footer&&t.push(u(e.footer));let a=e.cards.map((r,p)=>({card_index:p,components:[{type:"HEADER",format:"PRODUCT",example:{header_handle:[r.product_retailer_id]}}]}));return t.push({type:"CAROUSEL",cards:a}),{name:e.name,language:e.language,category:"MARKETING",components:t}}function O(e){let t=[];return e.header&&t.push(m({...e.header,format:"TEXT"})),t.push(n(e.body)),e.footer&&t.push(u(e.footer)),t.push({type:"BUTTONS",buttons:[{type:"SPM",action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:"MARKETING",components:t}}export{s as a,d as b,i as c,y as d,T as e,h as f,_ as g,g as h,x as i,O as j};//# sourceMappingURL=chunk-FLDBNTNY.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-FLDBNTNY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/features/template/factories/index.ts"],"names":["createHeader","options","header","createBody","body","createFooter","createButtons","buttons","urlButton","qr","flowButton","formatParameterExamples","parameters","param","createTemplate","components","carouselComponents","card","index","format","handle","createOTPTemplate","bodyText","createAuthenticationTemplate","createCatalogTemplate","createCouponTemplate","createLimitedTimeOfferTemplate","createMediaCardCarouselTemplate","carouselCards","cardComponents","createMPMTemplate","createProductCardCarouselTemplate","createSPMTemplate"],"mappings":"AA4BA,SAASA,CAAaC,CAAAA,CAAAA,CAAwC,CAC1D,IAAMC,EAAyB,CAC3B,IAAA,CAAM,QACN,CAAA,MAAA,CAAQD,CAAQ,CAAA,MACpB,CAEA,CAAA,OAAIA,EAAQ,IACRC,GAAAA,CAAAA,CAAO,IAAOD,CAAAA,CAAAA,CAAQ,IAGtBA,CAAAA,CAAAA,CAAAA,CAAQ,OACRC,GAAAA,CAAAA,CAAO,QAAUD,CAAQ,CAAA,OAAA,CAAA,CAGtBC,CACX,CAGA,SAASC,CAAAA,CAAWF,CAAoC,CAAA,CACpD,IAAMG,CAAqB,CAAA,CACvB,IAAM,CAAA,MAAA,CACN,IAAMH,CAAAA,CAAAA,CAAQ,IAClB,CAAA,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IAAA,CAAKV,CAAaJ,CAAAA,CAAAA,CAAQ,MAAM,CAAC,CAIhDc,CAAAA,CAAAA,CAAW,KAAK,CACZ,IAAA,CAAM,SACN,CAAA,OAAA,CAAS,CACL,CACI,IAAM,CAAA,KAAA,CACN,OAAQ,CACJ,mBAAA,CAAqBd,CAAQ,CAAA,mBACjC,CACJ,CACJ,CACJ,CAAC,EAEM,CACH,IAAA,CAAMA,CAAQ,CAAA,IAAA,CACd,SAAUA,CAAQ,CAAA,QAAA,CAClB,QACA,CAAA,WAAA,CAAA,UAAA,CAAAc,CACJ,CACJ","file":"chunk-FLDBNTNY.js","sourcesContent":["import { CategoryEnum } from '@shared/types/enums';\nimport type {\n ComponentTypes,\n TemplateBody,\n TemplateButton,\n TemplateFooter,\n TemplateHeader,\n TemplateRequestBody,\n} from '../types/common';\nimport type {\n AuthenticationTemplateOptions,\n BodyOptions,\n ButtonOptions,\n CatalogTemplateOptions,\n CouponTemplateOptions,\n FooterOptions,\n HeaderOptions,\n LimitedTimeOfferTemplateOptions,\n MediaCardCarouselTemplateOptions,\n MPMTemplateOptions,\n OTPTemplateOptions,\n ProductCardCarouselTemplateOptions,\n SPMTemplateOptions,\n TemplateOptions,\n TemplateParameter,\n} from '../types/factory';\n\n// Helper function to create header component\nfunction createHeader(options: HeaderOptions): TemplateHeader {\n const header: TemplateHeader = {\n type: 'HEADER',\n format: options.format,\n };\n\n if (options.text) {\n header.text = options.text;\n }\n\n if (options.example) {\n header.example = options.example;\n }\n\n return header;\n}\n\n// Helper function to create body component\nfunction createBody(options: BodyOptions): TemplateBody {\n const body: TemplateBody = {\n type: 'BODY',\n text: options.text,\n };\n\n if (options.example) {\n body.example = options.example;\n }\n\n return body;\n}\n\n// Helper function to create footer component\nfunction createFooter(options: FooterOptions): TemplateFooter {\n return {\n type: 'FOOTER',\n text: options.text,\n };\n}\n\n// Helper function to create buttons\nfunction createButtons(options: ButtonOptions): ComponentTypes[] {\n const buttons: TemplateButton[] = [];\n\n if (options.phone_number) {\n buttons.push({\n type: 'PHONE_NUMBER',\n text: options.phone_number.text,\n phone_number: options.phone_number.phone_number,\n });\n }\n\n if (options.url) {\n const urlButton: any = {\n type: 'URL',\n text: options.url.text,\n url: options.url.url,\n };\n if (options.url.example) {\n urlButton.example = [options.url.example];\n }\n buttons.push(urlButton);\n }\n\n if (options.quick_reply) {\n options.quick_reply.forEach((qr) => {\n buttons.push({\n type: 'QUICK_REPLY',\n text: qr.text,\n });\n });\n }\n\n if (options.copy_code) {\n buttons.push({\n type: 'COPY_CODE',\n example: options.copy_code.example,\n });\n }\n\n if (options.flow) {\n const flowButton: any = {\n type: 'FLOW',\n text: options.flow.text,\n };\n if (options.flow.flow_id) flowButton.flow_id = options.flow.flow_id;\n if (options.flow.flow_name) flowButton.flow_name = options.flow.flow_name;\n if (options.flow.flow_json) flowButton.flow_json = options.flow.flow_json;\n if (options.flow.flow_action) flowButton.flow_action = options.flow.flow_action;\n if (options.flow.navigate_screen) flowButton.navigate_screen = options.flow.navigate_screen;\n buttons.push(flowButton);\n }\n\n if (options.mpm) {\n buttons.push({ type: 'MPM' });\n }\n\n if (options.otp) {\n buttons.push({ type: 'OTP' });\n }\n\n if (options.spm) {\n buttons.push({ type: 'SPM' });\n }\n\n return buttons.length > 0\n ? [\n {\n type: 'BUTTONS',\n buttons: buttons as any,\n },\n ]\n : [];\n}\n\n// Helper function to format parameter examples\nfunction formatParameterExamples(parameters: TemplateParameter[]): string[] {\n return parameters.map((param) => {\n switch (param.type) {\n case 'text':\n return param.value;\n case 'currency':\n return param.fallback_value;\n case 'date_time':\n return param.fallback_value;\n case 'image':\n case 'video':\n case 'document':\n return param.handle || param.link || '';\n case 'location':\n return param.name || '';\n case 'product':\n return param.product_retailer_id;\n default:\n return '';\n }\n });\n}\n\n// Generic template factory\nexport function createTemplate(options: TemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader(options.header));\n }\n\n if (options.body) {\n components.push(createBody(options.body));\n }\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n if (options.buttons) {\n components.push(...createButtons(options.buttons));\n }\n\n if (options.carousel) {\n // Handle carousel components\n const carouselComponents: ComponentTypes[] = [];\n options.carousel.cards.forEach((card, index) => {\n if (card.image || card.video || card.product) {\n const format = card.image ? 'IMAGE' : card.video ? 'VIDEO' : 'DOCUMENT';\n const handle = card.image || card.video || card.product || '';\n carouselComponents.push({\n type: 'HEADER',\n format: format,\n example: {\n header_handle: [handle],\n },\n });\n }\n if (card.body) {\n carouselComponents.push({\n type: 'BODY',\n text: card.body,\n example: card.bodyParameters\n ? {\n body_text: [formatParameterExamples(card.bodyParameters)],\n }\n : undefined,\n });\n }\n if (card.buttons) {\n carouselComponents.push(...createButtons(card.buttons));\n }\n });\n components.push(...carouselComponents);\n }\n\n if (options.limitedTimeOffer) {\n components.push({\n type: 'LIMITED_TIME_OFFER',\n limited_time_offer: {\n expiration_time_ms: options.limitedTimeOffer.expiration_time_ms,\n },\n } as any);\n }\n\n return {\n name: options.name,\n language: options.language,\n category: options.category,\n components: components.length > 0 ? components : undefined,\n };\n}\n\n// OTP Template Factory\nexport function createOTPTemplate(options: OTPTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add security recommendation if requested\n let bodyText = '*{{1}}* is your verification code.';\n if (options.add_security_recommendation) {\n bodyText += ' For your security, do not share this code.';\n }\n if (options.code_expiration_minutes) {\n bodyText += ` This code expires in ${options.code_expiration_minutes} minutes.`;\n }\n\n components.push({\n type: 'BODY',\n text: bodyText,\n example: {\n body_text: [['123456']], // Example OTP code\n },\n });\n\n // Add OTP button\n components.push({\n type: 'BUTTONS',\n buttons: [{ type: 'OTP' }] as any,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Authentication,\n components,\n };\n}\n\n// Authentication Template Factory\nexport function createAuthenticationTemplate(options: AuthenticationTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add security message\n let bodyText = 'Your security code is *{{1}}*.';\n if (options.add_security_recommendation) {\n bodyText += ' Do not share this code with anyone.';\n }\n if (options.code_expiration_minutes) {\n bodyText += ` This code expires in ${options.code_expiration_minutes} minutes.`;\n }\n\n components.push({\n type: 'BODY',\n text: bodyText,\n example: {\n body_text: [['ABCD1234']], // Example auth code\n },\n });\n\n // Add copy code button if requested\n if (options.copy_code_button) {\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'COPY_CODE',\n example: 'ABCD1234',\n },\n ] as any,\n });\n }\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Authentication,\n components,\n };\n}\n\n// Catalog Template Factory\nexport function createCatalogTemplate(options: CatalogTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add catalog button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'CATALOG',\n action: {\n thumbnail_product_retailer_id: options.thumbnail_product_retailer_id,\n },\n },\n ] as any,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Coupon Template Factory\nexport function createCouponTemplate(options: CouponTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add copy code button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'COPY_CODE',\n example: options.coupon_code,\n },\n ] as any,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Limited Time Offer Template Factory\nexport function createLimitedTimeOfferTemplate(options: LimitedTimeOfferTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add limited time offer component first\n components.push({\n type: 'LIMITED_TIME_OFFER',\n limited_time_offer: {\n expiration_time_ms: options.expiration_time_ms,\n },\n } as any);\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Media Card Carousel Template Factory\nexport function createMediaCardCarouselTemplate(options: MediaCardCarouselTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add carousel component\n const carouselCards: any[] = [];\n options.cards.forEach((card, index) => {\n const cardComponents: any[] = [];\n\n // Add header (media)\n cardComponents.push({\n type: 'HEADER',\n format: card.header.format,\n example: card.header.example,\n });\n\n // Add body\n cardComponents.push(createBody(card.body));\n\n // Add buttons if any\n if (card.buttons) {\n cardComponents.push(...createButtons(card.buttons));\n }\n\n carouselCards.push({\n card_index: index,\n components: cardComponents,\n });\n });\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n } as any);\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// MPM (Multi-Product Message) Template Factory\nexport function createMPMTemplate(options: MPMTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add MPM button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'MPM',\n action: {\n thumbnail_product_retailer_id: options.thumbnail_product_retailer_id,\n sections: options.sections,\n },\n },\n ] as any,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Product Card Carousel Template Factory\nexport function createProductCardCarouselTemplate(options: ProductCardCarouselTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add carousel with product cards\n const carouselCards: any[] = options.cards.map((card, index) => ({\n card_index: index,\n components: [\n {\n type: 'HEADER',\n format: 'PRODUCT',\n example: {\n header_handle: [card.product_retailer_id],\n },\n },\n ],\n }));\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n } as any);\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// SPM (Single-Product Message) Template Factory\nexport function createSPMTemplate(options: SPMTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add SPM button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'SPM',\n action: {\n product_retailer_id: options.product_retailer_id,\n },\n },\n ] as any,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {a as a$1,b}from'./chunk-
|
|
2
|
-
`),c=e.FLOW_API_PASSPHRASE,d=l__default.createPrivateKey({key:a,passphrase:c}),u;try{u=l__default.privateDecrypt({key:d,padding:l__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"),f=y.subarray(0,-16),i=y.subarray(-16),k=l__default.createDecipheriv("aes-128-gcm",u,g);k.setAuthTag(i);let S=Buffer.concat([k.update(f),k.final()]).toString("utf-8");return {decryptedBody:JSON.parse(S),aesKeyBuffer:u,initialVectorBuffer:g}}function x(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=l__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 p.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",m=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),m.log("WebhookHandler instantiated!");}handleVerification=e=>R(e,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async e=>E(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),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}};var oe=(s,e)=>l.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{C as a,F as b,q as c,R as d,E as e,H as f,W as g,oe as h};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1,b}from'./chunk-4LWNMCXG.js';import {a}from'./chunk-VW3LGHTJ.js';import*as l from'crypto';import l__default from'crypto';function M(s){return typeof s=="object"&&s!==null}function h(s){return typeof s=="string"}var P=["data_exchange","INIT","BACK"],T=["data_exchange","INIT"];function C(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,version:r,screen:t,data:o}=s,a=r==="3.0",c=P.includes(e),d=typeof t>"u"||h(t)&&t!=="SUCCESS",u=e==="data_exchange"||M(o);return a&&c&&d&&u}function F(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,screen:r,data:t}=s,o=T.includes(e),a=h(r),c=M(t)&&"error_key"in t&&h(t.error)&&"error_message"in t&&h(t.error_message);return o&&a&&c}function q(s){return "action"in s&&s.action==="ping"}var B="WEBHOOK_UTILS",p=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?(p.log("Webhook verified successfully"),{statusCode:200,body:o}):(p.log("Webhook verification failed"),{statusCode:403}):(p.log("Not a webhook verification request - missing required parameters"),{statusCode:400,body:{error:"Invalid webhook verification request"}})}async function E(s,e,r){let t=s.body,o=[];if(t.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return p.log(a),{statusCode:404,body:{error:a}}}for(let a of t.entry)try{let c=a.changes;for(let d of c)d.field==="messages"&&await I(a.id,d.value,e,r);}catch(c){let d=`Error processing webhook: ${c}`;p.log(d),o.push(d);}return {statusCode:200,body:o.length>0?{errors:o}:void 0}}async function H(s,e,r,t){try{if(!N(s,e.WEBHOOK_VERIFICATION_TOKEN||""))return p.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let o=JSON.parse(s.rawBody||"{}"),{decryptedBody:a}=O(o,e),c=t.get("*");if(!c)return p.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(q(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(F(a))return p.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(C(a)){let d=await c(r,a);return {statusCode:200,body:x(d,Buffer.from(o.aes_key,"base64"),Buffer.from(o.initial_vector,"base64"))}}return p.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(o){return p.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,d=o?.display_phone_number||"",u=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 f={wabaId:c,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:u,displayPhoneNumber:d,profileName:y,statuses:e.statuses[0],originalData:n};await w(t.messageHandlers.get("statuses"),r,f,"statuses");}return}if(e.messages&&e.messages.length>0){let g=e.messages;for(let n of g){let f=n.type,i={wabaId:c,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:u,displayPhoneNumber:d,profileName:y,originalData:n};switch(f){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:p.log(`Unknown message type: ${f}`);break}await w(t.preProcessHandler,r,i,"pre-process"),await w(t.messageHandlers.get(f),r,i,f),await w(t.postProcessHandler,r,i,"post-process");}}}async function w(s,e,r,t){if(s)try{await s(e,r);}catch(o){p.log(`Error in ${t} handler: ${o}`);}}function N(s,e){let r=s.headers["x-hub-signature-256"];if(!r||!s.rawBody)return false;let o=`sha256=${l__default.createHmac("sha256",e).update(s.rawBody,"utf8").digest("hex")}`;return l__default.timingSafeEqual(Buffer.from(r),Buffer.from(o))}function O(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,d=l__default.createPrivateKey({key:a,passphrase:c}),u;try{u=l__default.privateDecrypt({key:d,padding:l__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"),f=y.subarray(0,-16),i=y.subarray(-16),k=l__default.createDecipheriv("aes-128-gcm",u,g);k.setAuthTag(i);let S=Buffer.concat([k.update(f),k.final()]).toString("utf-8");return {decryptedBody:JSON.parse(S),aesKeyBuffer:u,initialVectorBuffer:g}}function x(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=l__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 p.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",m=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),m.log("WebhookHandler instantiated!");}handleVerification=e=>R(e,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async e=>E(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),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}};var oe=(s,e)=>l.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{C as a,F as b,q as c,R as d,E as e,H as f,W as g,oe as h};//# sourceMappingURL=chunk-MTRF47KZ.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-MTRF47KZ.js.map
|