meta-cloud-api 0.2.18 → 0.2.19

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 (52) hide show
  1. package/dist/{BusinessProfileApi-DDkv2WQK.d.ts → BusinessProfileApi-BjOyDR-8.d.ts} +3 -3
  2. package/dist/{EncryptionApi-CwxQlC-2.d.ts → EncryptionApi-B3hzgZwc.d.ts} +1 -1
  3. package/dist/{FlowApi-BIBrWYEv.d.ts → FlowApi-OEAji2dP.d.ts} +2 -2
  4. package/dist/{MediaApi-VqxndaBJ.d.ts → MediaApi-C2-eC3BR.d.ts} +1 -1
  5. package/dist/{MessageApi-CHc6bn3g.d.ts → MessageApi-BQhqbAOY.d.ts} +2 -2
  6. package/dist/{PhoneNumberApi-C-bs6YAe.d.ts → PhoneNumberApi-BgfYrui-.d.ts} +2 -2
  7. package/dist/{QrCodeApi-BjlyPUXV.d.ts → QrCodeApi-CimaUuYP.d.ts} +1 -1
  8. package/dist/{RegistrationApi-D7Bg8BUz.d.ts → RegistrationApi-BSDXRJlL.d.ts} +2 -2
  9. package/dist/{TemplateApi-dmZbvMkO.d.ts → TemplateApi-B7dTBIlN.d.ts} +3 -3
  10. package/dist/{TwoStepVerificationApi-DaYWPjY_.d.ts → TwoStepVerificationApi-BY0eD8R2.d.ts} +1 -1
  11. package/dist/{WabaApi-CMoTCWiH.d.ts → WabaApi-BFbVUUlw.d.ts} +1 -1
  12. package/dist/{base-BG2gtoDs.d.ts → base-B4QLc9vb.d.ts} +2 -2
  13. package/dist/chunk-34SVEEB7.js +3 -0
  14. package/dist/chunk-34SVEEB7.js.map +1 -0
  15. package/dist/chunk-BSNA6RYF.js +3 -0
  16. package/dist/chunk-BSNA6RYF.js.map +1 -0
  17. package/dist/{chunk-FFOE5YKT.js → chunk-GT3XQN7Y.js} +2 -2
  18. package/dist/chunk-GT3XQN7Y.js.map +1 -0
  19. package/dist/chunk-H55VIWDI.js +2 -0
  20. package/dist/chunk-H55VIWDI.js.map +1 -0
  21. package/dist/chunk-I222VSWK.js +2 -0
  22. package/dist/chunk-I222VSWK.js.map +1 -0
  23. package/dist/{chunk-XIIJD6SG.js → chunk-R36L2XYO.js} +2 -2
  24. package/dist/chunk-R36L2XYO.js.map +1 -0
  25. package/dist/core/webhook/index.d.ts +630 -0
  26. package/dist/core/webhook/index.js +2 -0
  27. package/dist/core/webhook/index.js.map +1 -0
  28. package/dist/core/whatsapp/index.d.ts +100 -0
  29. package/dist/core/whatsapp/index.js +2 -0
  30. package/dist/core/whatsapp/index.js.map +1 -0
  31. package/dist/{enums-Z1f7QuVx.d.ts → enums-CL4CRQAe.d.ts} +1 -1
  32. package/dist/features/encryption/index.d.ts +4 -4
  33. package/dist/features/flow/index.d.ts +4 -4
  34. package/dist/features/media/index.d.ts +4 -4
  35. package/dist/features/messages/index.d.ts +4 -4
  36. package/dist/features/phone/index.d.ts +4 -4
  37. package/dist/features/profile/index.d.ts +4 -4
  38. package/dist/features/qrCode/index.d.ts +4 -4
  39. package/dist/features/qrCode/index.js +1 -1
  40. package/dist/features/registration/index.d.ts +4 -4
  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/waba/index.d.ts +4 -4
  45. package/dist/index.d.ts +18 -674
  46. package/dist/index.js +1 -2
  47. package/dist/index.js.map +1 -1
  48. package/dist/shared/types/config.d.ts +1 -1
  49. package/dist/shared/types/enums.d.ts +1 -1
  50. package/package.json +1 -1
  51. package/dist/chunk-FFOE5YKT.js.map +0 -1
  52. package/dist/chunk-XIIJD6SG.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { B as BaseClass, b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { d as BaseClass, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { d as BusinessVerticalEnum } from './enums-Z1f7QuVx.js';
3
+ import { B as BusinessVerticalEnum } from './enums-CL4CRQAe.js';
4
4
 
5
5
  /**
6
6
  * Upload session information for creating upload sessions.
@@ -349,4 +349,4 @@ declare class BusinessProfileApi extends BaseAPI implements BusinessProfileClass
349
349
  getUploadHandle(uploadId: string): Promise<UploadHandle>;
350
350
  }
351
351
 
352
- export { BusinessProfileApi as B, type CreateUploadSessionParams as C, type GetUploadHandleParams as G, type UpdateBusinessProfileRequest as U, BusinessProfileClass as a, type BusinessProfileResponse as b, type BusinessProfileData as c, type BusinessProfileField as d, type BusinessProfileFieldsParam as e, type UploadBusinessProfileResponse as f, type UploadHandle as g, type UploadMediaParams as h, type UploadSession as i, type UploadSessionResponse as j };
352
+ export { BusinessProfileApi as B, type CreateUploadSessionParams as C, type GetUploadHandleParams as G, type UpdateBusinessProfileRequest as U, BusinessProfileClass as a, type BusinessProfileData as b, type BusinessProfileField as c, type BusinessProfileFieldsParam as d, type BusinessProfileResponse as e, type UploadBusinessProfileResponse as f, type UploadHandle as g, type UploadMediaParams as h, type UploadSession as i, type UploadSessionResponse as j };
@@ -1,4 +1,4 @@
1
- import { d as ResponseData, b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type EncryptionPublicKeyResponse = ResponseData<{
@@ -1,4 +1,4 @@
1
- import { b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  /**
@@ -468,4 +468,4 @@ declare class FlowApi extends BaseAPI implements FlowClass {
468
468
  }): Promise<FlowMigrationResponse>;
469
469
  }
470
470
 
471
- export { type CreateFlowResponse as C, FlowApi as F, type UpdateFlowResponse as U, type ValidateFlowJsonResponse as V, type FlowEndpointRequest as a, FlowTypeEnum as b, type Flow as c, type FlowClass as d, type FlowEndpointResponse as e, FlowActionEnum as f, type FlowAssetsResponse as g, FlowCategoryEnum as h, type FlowMigrationResponse as i, type FlowPreviewResponse as j, type FlowsListResponse as k, FlowStatusEnum as l, type FlowValidationError as m };
471
+ export { type CreateFlowResponse as C, FlowApi as F, type UpdateFlowResponse as U, type ValidateFlowJsonResponse as V, type Flow as a, FlowActionEnum as b, type FlowAssetsResponse as c, FlowCategoryEnum as d, type FlowClass as e, type FlowEndpointRequest as f, type FlowEndpointResponse as g, type FlowMigrationResponse as h, type FlowPreviewResponse as i, type FlowsListResponse as j, FlowStatusEnum as k, type FlowValidationError as l, FlowTypeEnum as m };
@@ -1,4 +1,4 @@
1
- import { b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type MediaResponse = {
@@ -1,6 +1,6 @@
1
- import { B as BaseClass, G as GeneralRequestBody, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { d as BaseClass, G as GeneralRequestBody, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { I as InteractiveTypesEnum, C as ComponentTypesEnum, L as LanguagesEnum, P as ParametersTypesEnum, b as CurrencyCodesEnum, B as ButtonTypesEnum, c as ButtonPositionEnum, M as MessageTypesEnum } from './enums-Z1f7QuVx.js';
3
+ import { I as InteractiveTypesEnum, b as ComponentTypesEnum, L as LanguagesEnum, P as ParametersTypesEnum, c as CurrencyCodesEnum, d as ButtonTypesEnum, e as ButtonPositionEnum, M as MessageTypesEnum } from './enums-CL4CRQAe.js';
4
4
 
5
5
  interface ReactionParams {
6
6
  messageId: string;
@@ -1,4 +1,4 @@
1
- import { P as Paging, b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { P as Paging, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type QualityRating = 'GREEN' | 'YELLOW' | 'RED' | 'NA';
@@ -138,4 +138,4 @@ declare class PhoneNumberApi extends BaseAPI implements PhoneNumberClass {
138
138
  verifyCode(request: VerifyCodeRequest): Promise<ResponseSuccess>;
139
139
  }
140
140
 
141
- export { type AccountMode as A, type CodeVerificationStatus as C, type HealthStatus as H, type MessagingLimitTier as M, PhoneNumberApi as P, type QualityRating as Q, type RequestVerificationCodeRequest as R, type Throughput as T, type VerifyCodeRequest as V, type PhoneNumberClass as a, type PhoneNumberResponse as b, type Cursors as c, type HealthStatusEntity as d, type PhoneNumbersResponse as e, type PlatformType as f, type QualityScore as g, type ThroughputLevel as h, type TwoStepVerificationParams as i };
141
+ export { type AccountMode as A, type CodeVerificationStatus as C, type HealthStatus as H, type MessagingLimitTier as M, PhoneNumberApi as P, type QualityRating as Q, type RequestVerificationCodeRequest as R, type Throughput as T, type VerifyCodeRequest as V, type Cursors as a, type HealthStatusEntity as b, type PhoneNumberClass as c, type PhoneNumberResponse as d, type PhoneNumbersResponse as e, type PlatformType as f, type QualityScore as g, type ThroughputLevel as h, type TwoStepVerificationParams as i };
@@ -1,4 +1,4 @@
1
- import { d as ResponseData, b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type QrCodeResponse = {
@@ -1,6 +1,6 @@
1
- import { b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { D as DataLocalizationRegionEnum } from './enums-Z1f7QuVx.js';
3
+ import { D as DataLocalizationRegionEnum } from './enums-CL4CRQAe.js';
4
4
 
5
5
  type RegistrationRequest = {
6
6
  messaging_product: 'whatsapp';
@@ -1,6 +1,6 @@
1
- import { G as GeneralRequestBody, b as ResponseSuccess, c as ResponsePagination, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { G as GeneralRequestBody, R as ResponseSuccess, b as ResponsePagination, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
- import { L as LanguagesEnum, e as CategoryEnum, T as TemplateStatusEnum } from './enums-Z1f7QuVx.js';
3
+ import { L as LanguagesEnum, C as CategoryEnum, T as TemplateStatusEnum } from './enums-CL4CRQAe.js';
4
4
 
5
5
  type TemplateFormat = 'TEXT' | 'IMAGE' | 'VIDEO' | 'DOCUMENT' | 'LOCATION';
6
6
  type PhoneNumberButton = {
@@ -114,4 +114,4 @@ declare class TemplateApi extends BaseAPI implements TemplateClass {
114
114
  deleteTemplate(params: TemplateDeleteParams): Promise<ResponseSuccess>;
115
115
  }
116
116
 
117
- export { TemplateApi as T, TemplateClass as a, type TemplateResponse as b, type TemplateDeleteParams as c, type TemplateGetParams as d, type TemplateRequestBody as e };
117
+ export { TemplateApi as T, TemplateClass as a, type TemplateDeleteParams as b, type TemplateGetParams as c, type TemplateRequestBody as d, type TemplateResponse as e };
@@ -1,4 +1,4 @@
1
- import { b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type TwoStepVerificationRequest = {
@@ -1,4 +1,4 @@
1
- import { b as ResponseSuccess, a as BaseAPI, R as RequesterClass } from './base-BG2gtoDs.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-B4QLc9vb.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  /**
@@ -1,5 +1,5 @@
1
1
  import { WabaConfigType } from './shared/types/config.js';
2
- import { H as HttpMethodsEnum } from './enums-Z1f7QuVx.js';
2
+ import { H as HttpMethodsEnum } from './enums-CL4CRQAe.js';
3
3
 
4
4
  type GeneralRequestBody = Record<string, unknown>;
5
5
  interface RequesterResponseInterface<T> {
@@ -43,4 +43,4 @@ declare class BaseAPI implements BaseClass {
43
43
  protected sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;
44
44
  }
45
45
 
46
- export { BaseClass as B, type GeneralRequestBody as G, type Paging as P, RequesterClass as R, BaseAPI as a, type ResponseSuccess as b, type ResponsePagination as c, type ResponseData as d };
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 };
@@ -0,0 +1,3 @@
1
+ import {a as a$1,b}from'./chunk-BSNA6RYF.js';import {a}from'./chunk-VW3LGHTJ.js';import l from'crypto';var P=(n=>(n.DELIVERED="delivered",n.READ="read",n.SENT="sent",n))(P||{}),x=(a=>(a.MESSAGES="messages",a.STATUSES="statuses",a.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",a.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",a.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",a.UNKNOWN="unknown",a))(x||{});function E(d){return typeof d=="object"&&d!==null}function g(d){return typeof d=="string"}var T=["data_exchange","INIT","BACK"],S=["data_exchange","INIT"];function _(d){if(!("flow_token"in d&&g(d.flow_token)&&"action"in d))return false;let{action:t,version:e,screen:n,data:r}=d,o=e==="3.0",a=T.includes(t),s=typeof n>"u"||g(n)&&n!=="SUCCESS",u=t==="data_exchange"||E(r);return o&&a&&s&&u}function v(d){if(!("flow_token"in d&&g(d.flow_token)&&"action"in d))return false;let{action:t,screen:e,data:n}=d,r=S.includes(t),o=g(e),a=E(n)&&"error_key"in n&&g(n.error)&&"error_message"in n&&g(n.error_message);return r&&o&&a}function w(d){return "action"in d&&d.action==="ping"}var C="WEBHOOK",W=false,i=new a(C,process.env.DEBUG==="true"||W),m=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(t){let e=a$1(t);this.config=e,this.client=new b(t),i.log("WebhookHandler instantiated!");}handleVerificationRequest(t,e){let n=t.query["hub.mode"],r=t.query["hub.verify_token"],o=t.query["hub.challenge"];if(n==="subscribe"&&r===this.config.WEBHOOK_VERIFICATION_TOKEN)if(i.log("Webhook verified successfully"),e){e.status(200).send(o);return}else return i.log("Returning challenge for manual handling"),o;else if(i.log("Webhook verification failed"),e){e.status(403).end();return}else throw i.log("Verification failed - throwing error for manual handling"),new Error("Webhook verification failed")}async handleWebhookRequest(t,e){let n=t.body,r=[];if(n.object!=="whatsapp_business_account"){let o="Received webhook for non-WhatsApp event";if(i.log(o),e){e.status(404).end();return}else return r.push(o),{success:false,errors:r}}for(let o of n.entry)try{let a=o.changes;for(let s of a)s.field==="messages"?await this.processMessages(s.value):await this.processEvent(s.field,s.value);}catch(a){let s=`Error processing webhook: ${a}`;i.log(s),r.push(s);}if(e){e.status(200).end();return}else return {success:r.length===0,errors:r.length>0?r:void 0}}handleRequest(t,e){if(t.method==="GET")return e?this.handleVerificationRequest(t,e):this.handleVerificationRequest(t);if(t.method==="POST")return e?this.handleWebhookRequest(t,e):this.handleWebhookRequest(t);if(e){e.status(405).end();return}else throw new Error("Method not allowed")}async processMessages(t){let e=t.metadata,n=e.display_phone_number,r=e.phone_number_id,o=t.contacts[0].profile.name,a=t.messages;if(a&&a.length>0)for(let s of a){let u=s.type,c={id:s.id,from:s.from,timestamp:s.timestamp,type:s.type,phoneNumberId:r,displayPhoneNumber:n,profileName:o,originalData:s};switch(s.type){case "text":c.text=s.text;break;case "image":c.image=s.image;break;case "video":c.video=s.video;break;case "audio":c.audio=s.audio;break;case "document":c.document=s.document;break;case "sticker":c.sticker=s.sticker;break;case "location":c.location=s.location;break;case "contacts":c.contacts=s.contacts;break;case "interactive":c.interactive=s.interactive;break;case "button":c.button=s.button;break;case "order":c.order=s.order;break;case "system":c.system=s.system;break;}if(s.context&&(c.context=s.context),s.errors&&(c.errors=s.errors),this.preProcessHandler)try{await this.preProcessHandler(this.client,c);}catch(p){i.log(`Error in pre-process handler: ${p}`);}let f=this.messageHandlers.get(u);if(f)try{await f(this.client,c);}catch(p){i.log(`Error in message handler for ${u}: ${p}`);}if(this.postProcessHandler)try{await this.postProcessHandler(this.client,c);}catch(p){i.log(`Error in post-process handler: ${p}`);}}}async processEvent(t,e){let n={field:t,value:e,timestamp:Date.now()},r=this.eventHandlers.get(t);if(r)try{await r(n);}catch(o){i.log(`Error in event handler for ${t}: ${o}`);}}onMessage(t,e){this.messageHandlers.set(t,e),i.log(`Registered message handler for ${t}`);}onEvent(t,e){this.eventHandlers.set(t,e),i.log(`Registered event handler for ${t}`);}onMessagePreProcess(t){this.preProcessHandler=t,i.log("Registered pre-process handler");}onMessagePostProcess(t){this.postProcessHandler=t,i.log("Registered post-process handler");}async handleFlowRequest(t,e){try{if(!this.isRequestSignatureValid(t)){let s={error:"Unauthorized"};if(i.log("Invalid request signature"),e){e.status(401).json(s);return}else return {statusCode:401,body:s}}let n=JSON.parse(t.rawBody),{decryptedBody:r}=this.decryptRequest(n),o=this.flowHandlers.get("*");if(!o){let s={error:"Handler not found"};if(i.log(`No handler registered for flow action: ${r.action}`),e){e.status(404).json(s);return}else return {statusCode:404,body:s}}if(w(r)){let s={version:"3.0",data:{status:"active"}};if(e){e.status(200).json(s);return}else return {statusCode:200,body:s}}if(v(r)){i.log(`Flow error: ${JSON.stringify(r)}`);let s={};if(e){e.status(200).json(s);return}else return {statusCode:200,body:s}}if(_(r)){let s=await o(this.client,r),u=this.encryptResponse(s,Buffer.from(n.aes_key,"base64"),Buffer.from(n.initial_vector,"base64"));if(e){e.status(200).json(u);return}else return {statusCode:200,body:u}}let a={error:"Unknown request type"};if(i.log(`Unknown flow request type: ${JSON.stringify(r)}`),e){e.status(400).json(a);return}else return {statusCode:400,body:a}}catch(n){let r={error:"Internal server error"};if(i.log(`Error handling flow request: ${n}`),e){e.status(500).json(r);return}else return {statusCode:500,body:r}}}isRequestSignatureValid(t){let e=t.headers["x-hub-signature-256"];if(!e)return false;let r=`sha256=${l.createHmac("sha256",this.config.WEBHOOK_VERIFICATION_TOKEN||"").update(t.rawBody,"utf8").digest("hex")}`;return l.timingSafeEqual(Buffer.from(e),Buffer.from(r))}decryptRequest(t){i.log("Received body for decryption:",JSON.stringify(t,null,2));let{encrypted_aes_key:e,encrypted_flow_data:n,initial_vector:r}=t;if(!e)throw new Error("Missing required property: encrypted_aes_key");if(!n)throw new Error("Missing required property: encrypted_flow_data");if(!r)throw new Error("Missing required property: initial_vector");i.log("Received body for privatePem:",JSON.stringify(this.config.FLOW_API_PRIVATE_PEM,null,2)),i.log("Received body for passphrase:",JSON.stringify(this.config.FLOW_API_PASSPHRASE,null,2));let o=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),a=this.config.FLOW_API_PASSPHRASE,s=l.createPrivateKey({key:o,passphrase:a}),u=null;try{u=l.privateDecrypt({key:s,padding:l.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(e,"base64"));}catch(k){throw i.error(k),new Error("Failed to decrypt the request. Please verify your private key.")}let c=Buffer.from(n,"base64"),f=Buffer.from(r,"base64"),q=c.subarray(0,-16),A=c.subarray(-16),h=l.createDecipheriv("aes-128-gcm",u,f);h.setAuthTag(A);let I=Buffer.concat([h.update(q),h.final()]).toString("utf-8");return {decryptedBody:JSON.parse(I),aesKeyBuffer:u,initialVectorBuffer:f}}encryptResponse(t,e,n){let r=[];for(let o of Array.from(n.entries()))r.push(~o[1]);try{let o=l.createCipheriv("aes-128-gcm",e,Buffer.from(r));return Buffer.concat([o.update(JSON.stringify(t||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64")}catch(o){throw i.error("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}onFlow(t,e){this.flowHandlers.set(t,e),i.log(`Registered flow handler for ${t}`);}};export{P as a,x as b,m as c};//# sourceMappingURL=chunk-34SVEEB7.js.map
3
+ //# sourceMappingURL=chunk-34SVEEB7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/webhook/types.ts","../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/WebhookHandler.ts"],"names":["MessageStatus","EventField","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOG_LOCAL","LOGGER","Logger","WebhookHandler","config","configuration","importConfig","WhatsApp","req","res","mode","token","challenge","body","errors","errorMsg","entry","changes","change","error","metadata","displayPhoneNumber","phoneNumberId","profileName","messages","message","messageType","processedMessage","handler","field","event","type","decryptedBody","response","result","encryptedResponse","errorResponse","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","aesKeyBuffer","flipped_iv","pair","cipher"],"mappings":"uGAwgBO,IAAKA,CACRA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,SAAY,CAAA,WAAA,CACZA,EAAA,IAAO,CAAA,MAAA,CACPA,CAAA,CAAA,IAAA,CAAO,OAHCA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CASAC,CACRA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,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,EAAS,KAAM,EACnB,CAAC,CAAA,CAAE,QAAS,CAAA,OAAO,EAEnB,OAAO,CACH,cAAe,IAAK,CAAA,KAAA,CAAMC,CAAmB,CAC7C,CAAA,YAAA,CAAcP,CACd,CAAA,mBAAA,CAAAE,CACJ,CACJ,CAKQ,eAAgBf,CAAAA,CAAAA,CAAeqB,CAAsBN,CAAAA,CAAAA,CAA6B,CACtF,IAAMO,EAAuB,EAAC,CAC9B,IAAWC,IAAAA,CAAAA,IAAQ,KAAM,CAAA,IAAA,CAAKR,EAAoB,OAAQ,EAAC,EACvDO,CAAW,CAAA,IAAA,CAAK,CAACC,CAAK,CAAA,CAAC,CAAC,CAAA,CAG5B,GAAI,CAEA,IAAMC,CAASlB,CAAAA,CAAAA,CAAO,cAAe,CAAA,aAAA,CAAee,CAAc,CAAA,MAAA,CAAO,KAAKC,CAAU,CAAC,CACzF,CAAA,OAAO,MAAO,CAAA,MAAA,CAAO,CACjBE,CAAO,CAAA,MAAA,CAAO,KAAK,SAAUxB,CAAAA,CAAAA,EAAY,EAAE,CAAA,CAAG,OAAO,CAAA,CACrDwB,CAAO,CAAA,KAAA,GACPA,CAAO,CAAA,UAAA,EACX,CAAC,CAAE,CAAA,QAAA,CAAS,QAAQ,CACxB,CAAA,MAAStC,CAAO,CAAA,CACZ,MAAAlB,CAAAA,CAAO,MAAM,4BAA8BkB,CAAAA,CAAK,CAC1C,CAAA,IAAI,KAAM,CAAA,oDAAoD,CACxE,CACJ,CAKO,MACHY,CAAAA,CAAAA,CACAH,CACI,CAAA,CACJ,KAAK,YAAa,CAAA,GAAA,CAAIG,CAAMH,CAAAA,CAAO,CACnC3B,CAAAA,CAAAA,CAAO,IAAI,CAA+B8B,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ","file":"chunk-34SVEEB7.js","sourcesContent":["import { MessageTypesEnum } from '@shared/types/enums';\n\nexport interface WebhookContact {\n /**\n * WhatsApp ID of the contact. Business can respond to this contact using this ID.\n */\n wa_id: string;\n /**\n * Additional unique, alphanumeric identifier for a WhatsApp user\n */\n user_id?: string;\n /**\n * Profile of Whatsapp user\n */\n profile: {\n /**\n * The display name of the contact\n */\n name: string;\n };\n}\n\n/**\n * Represents a message received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object\n */\nexport interface WebhookMessage {\n /**\n * The message ID\n */\n id: string;\n\n /**\n * The sender's phone number\n */\n from: string;\n\n /**\n * The timestamp of the message\n */\n timestamp: string;\n\n /**\n * The type of message (text, image, etc.)\n */\n type: MessageTypesEnum;\n\n /**\n * The phone number ID that received the message\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the message\n */\n displayPhoneNumber: string;\n\n /**\n * The profile name of the sender\n */\n profileName: string;\n\n /**\n * Text object for text messages\n */\n text?: {\n /**\n * The text content of the message\n */\n body: string;\n };\n\n /**\n * Image object for image messages\n */\n image?: {\n /**\n * The image caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the image\n */\n sha256?: string;\n /**\n * The ID for the image\n */\n id: string;\n /**\n * The MIME type of the image\n */\n mime_type: string;\n };\n\n /**\n * Video object for video messages\n */\n video?: {\n /**\n * The video caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the video\n */\n sha256?: string;\n /**\n * The ID for the video\n */\n id: string;\n /**\n * The MIME type of the video\n */\n mime_type: string;\n };\n\n /**\n * Audio object for audio messages\n */\n audio?: {\n /**\n * The ID for the audio file\n */\n id: string;\n /**\n * The MIME type of the audio file\n */\n mime_type: string;\n /**\n * Whether the audio is a voice message\n */\n voice?: boolean;\n };\n\n /**\n * Document object for document messages\n */\n document?: {\n /**\n * The document caption (if provided)\n */\n caption?: string;\n /**\n * The document filename\n */\n filename: string;\n /**\n * The SHA256 hash of the document\n */\n sha256?: string;\n /**\n * The ID for the document\n */\n id: string;\n /**\n * The MIME type of the document\n */\n mime_type: string;\n };\n\n /**\n * Sticker object for sticker messages\n */\n sticker?: {\n /**\n * The ID for the sticker\n */\n id: string;\n /**\n * Whether this is an animated sticker\n */\n animated: boolean;\n /**\n * The MIME type of the sticker\n */\n mime_type: string;\n };\n\n /**\n * Reaction object for reaction messages\n */\n reaction?: {\n /**\n * The ID of the message being reacted to\n */\n message_id: string;\n /**\n * Emoji used for the reaction\n */\n emoji: string;\n };\n\n /**\n * Contacts object for contact messages\n */\n contacts?: Array<{\n /**\n * The contact's name\n */\n name: {\n /**\n * The formatted name\n */\n formatted_name: string;\n /**\n * The first name\n */\n first_name?: string;\n /**\n * The last name\n */\n last_name?: string;\n /**\n * The middle name\n */\n middle_name?: string;\n /**\n * The suffix\n */\n suffix?: string;\n /**\n * The prefix\n */\n prefix?: string;\n };\n /**\n * The contact's phone numbers\n */\n phones?: Array<{\n phone: string;\n type?: string;\n wa_id?: string;\n }>;\n /**\n * The contact's emails\n */\n emails?: Array<{\n email: string;\n type?: string;\n }>;\n /**\n * The contact's addresses\n */\n addresses?: Array<{\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n country?: string;\n country_code?: string;\n type?: string;\n }>;\n /**\n * The contact's organizations\n */\n org?: {\n company?: string;\n department?: string;\n title?: string;\n };\n /**\n * The contact's URLs\n */\n urls?: Array<{\n url: string;\n type?: string;\n }>;\n /**\n * The contact's birthday (YYYY-MM-DD format)\n */\n birthday?: string;\n }>;\n\n /**\n * Location object for location messages\n */\n location?: {\n /**\n * Latitude of the location\n */\n latitude: number;\n /**\n * Longitude of the location\n */\n longitude: number;\n /**\n * Name of the location\n */\n name?: string;\n /**\n * Address of the location\n */\n address?: string;\n };\n\n /**\n * Interactive object for interactive messages\n */\n interactive?: {\n /**\n * Type of the interactive message\n * Can be: button_reply, list_reply, flow, nfm_reply, etc.\n */\n type: string;\n /**\n * ID for the button that was clicked\n */\n button_reply?: {\n id: string;\n title: string;\n };\n /**\n * ID for the list item that was selected\n */\n list_reply?: {\n id: string;\n title: string;\n description?: string;\n };\n\n /**\n * NFM (No-Code Flow Message) reply data\n */\n nfm_reply?: {\n /**\n * Response data in JSON format\n */\n response_json: string;\n /**\n * Body text of the reply\n */\n body: string;\n /**\n * Name of the flow\n */\n name: string;\n };\n };\n\n /**\n * System object for system messages (like user phone number changes)\n */\n system?: {\n /**\n * The type of system update\n */\n type: string;\n /**\n * User's identity if the update is a customer identity change\n */\n identity?: string;\n /**\n * Old and new phone numbers if the update is a phone number change\n */\n customer?: {\n /**\n * The previous phone number\n */\n previous_wa_id: string;\n /**\n * The new phone number\n */\n wa_id: string;\n };\n };\n\n /**\n * Order object for order messages\n */\n order?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product items in the order\n */\n product_items: Array<{\n /**\n * Product ID\n */\n product_retailer_id: string;\n /**\n * Quantity of the product\n */\n quantity: number;\n /**\n * Item price\n */\n item_price: number;\n /**\n * Currency code\n */\n currency: string;\n }>;\n /**\n * Text message included with the order\n */\n text?: string;\n };\n\n /**\n * Context object, included when a user replies or interacts\n */\n context?: {\n /**\n * ID of the message\n */\n id?: string;\n /**\n * ID of the sender\n */\n from?: string;\n /**\n * ID of the message being replied to or interacted with\n */\n message_id: string;\n /**\n * ID of the forwarded message, if applicable\n */\n forwarded?: boolean;\n /**\n * Frequently forwarded status\n */\n frequently_forwarded?: boolean;\n /**\n * Original message information if the message was referred\n */\n referred_product?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product ID\n */\n product_retailer_id: string;\n };\n };\n\n /**\n * Errors array, if the message had errors\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error title\n */\n title: string;\n /**\n * Error message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * Button object for button messages\n */\n button?: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n\n /**\n * The original message data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Webhook event received from WhatsApp\n */\nexport interface WebhookEvent {\n /**\n * The field type of the event\n */\n field: string;\n\n /**\n * The event data\n */\n value: any;\n\n /**\n * The timestamp when the event was received\n */\n timestamp: number;\n}\n\n/**\n * Message handler function type\n */\nexport type MessageHandler = (message: WebhookMessage) => void | Promise<void>;\n\n/**\n * Event handler function type\n */\nexport type EventHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * Message status enum\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n\n/**\n * Event field enum for webhook events\n */\nexport enum EventField {\n MESSAGES = 'messages',\n STATUSES = 'statuses',\n MESSAGE_TEMPLATE_STATUS_UPDATE = 'message_template_status_update',\n PHONE_NUMBER_QUALITY_UPDATE = 'phone_number_quality_update',\n PHONE_NUMBER_NAME_UPDATE = 'phone_number_name_update',\n UNKNOWN = 'unknown',\n}\n","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 { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport { IncomingMessage } from 'http';\n\nimport { FlowEndpointRequest } from '@features/flow';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../whatsapp';\n\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport { EventField, WebhookEvent, WebhookMessage } from './types';\nconst LIB_NAME = 'WEBHOOK';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport interface IRequest extends IncomingMessage {\n body: any;\n query: Record<string, any>;\n method?: string;\n}\nexport interface IResponse {\n status: (code: number) => IResponse;\n send: (body: any) => IResponse | void;\n json: (body: any) => IResponse | void;\n end: () => void;\n}\n\n/**\n * Webhook handler for WhatsApp Cloud API\n */\nexport default class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<\n MessageTypesEnum,\n (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>\n > = new Map();\n private eventHandlers: Map<string, (event: WebhookEvent) => void | Promise<void>> = new Map();\n private preProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private postProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private flowHandlers: Map<FlowTypeEnum, (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>> =\n new Map();\n\n /**\n * Create a new WebhookHandler\n * @param config The WhatsApp configuration\n */\n constructor(config: WhatsAppConfig) {\n const configuration = importConfig(config);\n this.config = configuration;\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle a GET request for webhook verification\n */\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void;\n public handleVerificationRequest<Req extends IRequest>(req: Req): string;\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res?: Res): void | string {\n const mode = req.query['hub.mode'];\n const token = req.query['hub.verify_token'];\n const challenge = req.query['hub.challenge'];\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n if (res) {\n res.status(200).send(challenge);\n return;\n } else {\n LOGGER.log('Returning challenge for manual handling');\n return challenge;\n }\n } else {\n LOGGER.log('Webhook verification failed');\n if (res) {\n res.status(403).end();\n return;\n } else {\n LOGGER.log('Verification failed - throwing error for manual handling');\n throw new Error('Webhook verification failed');\n }\n }\n }\n\n /**\n * Handle a POST request for webhook events\n */\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void>;\n public async handleWebhookRequest<Req extends IRequest>(req: Req): Promise<{ success: boolean; errors?: string[] }>;\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(\n req: Req,\n res?: Res,\n ): Promise<void | { success: boolean; errors?: string[] }> {\n const body = req.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\n if (res) {\n res.status(404).end();\n return;\n } else {\n errors.push(errorMsg);\n return { success: false, errors };\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 === EventField.MESSAGES) {\n await this.processMessages(change.value);\n } else {\n // Handle other event types\n await this.processEvent(change.field, change.value);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n if (res) {\n // Always respond with 200 to acknowledge receipt\n res.status(200).end();\n return;\n } else {\n // Return processing result\n return { success: errors.length === 0, errors: errors.length > 0 ? errors : undefined };\n }\n }\n\n /**\n * Handle webhook requests (both verification and events)\n */\n public handleRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void | Promise<void>;\n public handleRequest<Req extends IRequest>(req: Req): string | Promise<{ success: boolean; errors?: string[] }>;\n public handleRequest<Req extends IRequest, Res extends IResponse>(\n req: Req,\n res?: Res,\n ): void | string | Promise<void | { success: boolean; errors?: string[] }> {\n if (req.method === 'GET') {\n if (res) {\n return this.handleVerificationRequest(req, res);\n } else {\n return this.handleVerificationRequest(req);\n }\n } else if (req.method === 'POST') {\n if (res) {\n return this.handleWebhookRequest(req, res);\n } else {\n return this.handleWebhookRequest(req);\n }\n } else {\n if (res) {\n res.status(405).end(); // Method not allowed\n return;\n } else {\n throw new Error('Method not allowed');\n }\n }\n }\n\n /**\n * Process incoming messages\n */\n private async processMessages(value: any): Promise<void> {\n // Extract metadata\n const metadata = value.metadata;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n const profileName = value.contacts[0].profile.name;\n const messages = value.messages as WebhookMessage[];\n\n // Process messages if present\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n // Create the base message object\n const processedMessage: WebhookMessage = {\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 // Add type-specific data based on the message type\n switch (message.type) {\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 default:\n // Unknown message type\n break;\n }\n\n // Add context if available\n if (message.context) {\n processedMessage.context = message.context;\n }\n\n // Add errors if available\n if (message.errors) {\n processedMessage.errors = message.errors;\n }\n\n // 1. Execute pre-processing handler if exists\n if (this.preProcessHandler) {\n try {\n await this.preProcessHandler(this.client, processedMessage);\n } catch (error) {\n LOGGER.log(`Error in pre-process handler: ${error}`);\n }\n }\n\n // 2. Execute type-specific message handler if registered\n const handler = this.messageHandlers.get(messageType);\n if (handler) {\n try {\n await handler(this.client, processedMessage);\n } catch (error) {\n LOGGER.log(`Error in message handler for ${messageType}: ${error}`);\n }\n }\n\n // 3. Execute post-processing handler if exists\n if (this.postProcessHandler) {\n try {\n await this.postProcessHandler(this.client, processedMessage);\n } catch (error) {\n LOGGER.log(`Error in post-process handler: ${error}`);\n }\n }\n }\n }\n }\n\n /**\n * Process other webhook events\n */\n private async processEvent(field: string, value: any): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n timestamp: Date.now(),\n };\n\n const handler = this.eventHandlers.get(field);\n if (handler) {\n try {\n await handler(event);\n } catch (error) {\n LOGGER.log(`Error in event handler for ${field}: ${error}`);\n }\n }\n }\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(\n type: MessageTypesEnum,\n handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>,\n ): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register an event handler for a specific field\n */\n public onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered event handler for ${field}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): 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: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }, Res extends IResponse>(\n req: Req,\n res: Res,\n ): Promise<void>;\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }>(\n req: Req,\n ): Promise<{ statusCode: number; body: any; headers?: Record<string, string> }>;\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }, Res extends IResponse>(\n req: Req,\n res?: Res,\n ): Promise<void | { statusCode: number; body: any; headers?: Record<string, string> }> {\n try {\n // Validate request signature\n if (!this.isRequestSignatureValid(req)) {\n const error = { error: 'Unauthorized' };\n LOGGER.log('Invalid request signature');\n\n if (res) {\n res.status(401).json(error);\n return;\n } else {\n return { statusCode: 401, body: error };\n }\n }\n\n const body = JSON.parse(req.rawBody);\n\n // Decrypt the request\n const { decryptedBody } = this.decryptRequest(body);\n\n // Get the flow handler\n const handler = this.flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n const error = { error: 'Handler not found' };\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n\n if (res) {\n res.status(404).json(error);\n return;\n } else {\n return { statusCode: 404, body: error };\n }\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n // For ping requests, just respond with version\n const response = {\n version: '3.0',\n data: {\n status: 'active',\n },\n };\n\n if (res) {\n res.status(200).json(response);\n return;\n } else {\n return { statusCode: 200, body: response };\n }\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n const response = {};\n\n if (res) {\n res.status(200).json(response);\n return;\n } else {\n return { statusCode: 200, body: response };\n }\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n // Process data exchange request\n const result = await handler(this.client, decryptedBody);\n\n // Encrypt and send response\n const encryptedResponse = this.encryptResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n if (res) {\n res.status(200).json(encryptedResponse);\n return;\n } else {\n return { statusCode: 200, body: encryptedResponse };\n }\n }\n\n // Unknown flow type\n const error = { error: 'Unknown request type' };\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n\n if (res) {\n res.status(400).json(error);\n return;\n } else {\n return { statusCode: 400, body: error };\n }\n } catch (error) {\n const errorResponse = { error: 'Internal server error' };\n LOGGER.log(`Error handling flow request: ${error}`);\n\n if (res) {\n res.status(500).json(errorResponse);\n return;\n } else {\n return { statusCode: 500, body: errorResponse };\n }\n }\n }\n\n /**\n * Validate the request signature\n */\n public isRequestSignatureValid(req: IRequest & { rawBody: string }): boolean {\n const signature = req.headers['x-hub-signature-256'] as string;\n if (!signature) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', this.config.WEBHOOK_VERIFICATION_TOKEN || '')\n .update(req.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n }\n\n /**\n * Decrypt a flow request\n */\n public decryptRequest(body: any): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n } {\n LOGGER.log('Received body for decryption:', JSON.stringify(body, null, 2));\n\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key) {\n throw new Error('Missing required property: encrypted_aes_key');\n }\n if (!encrypted_flow_data) {\n throw new Error('Missing required property: encrypted_flow_data');\n }\n if (!initial_vector) {\n throw new Error('Missing required property: initial_vector');\n }\n\n LOGGER.log('Received body for privatePem:', JSON.stringify(this.config.FLOW_API_PRIVATE_PEM, null, 2));\n LOGGER.log('Received body for passphrase:', JSON.stringify(this.config.FLOW_API_PASSPHRASE, null, 2));\n\n const privatePem = this.config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = this.config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey = null;\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 LOGGER.error(error);\n /*\n Failed to decrypt. Please verify your private key.\n If you change your public key. You need to return HTTP status code 421 to refresh the public key on the client\n */\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n // decrypt flow data\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([\n decipher.update(encrypted_flow_data_body),\n decipher.final(),\n ]).toString('utf-8');\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n }\n\n /**\n * Encrypt a flow response\n */\n private encryptResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer) {\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 // encrypt response data\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.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(\n type: FlowTypeEnum,\n handler: (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>,\n ): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n"]}
@@ -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$8}from'./chunk-KFPOVYEJ.js';import {b as b$7}from'./chunk-A264MT4Q.js';import {b as b$1}from'./chunk-GIQLIMOD.js';import {a}from'./chunk-VW3LGHTJ.js';import {z}from'./chunk-EYGUX4EA.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 b$7(this.config,this.requester),this.businessProfile=new b$8(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-BSNA6RYF.js.map
3
+ //# sourceMappingURL=chunk-BSNA6RYF.js.map
@@ -0,0 +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":"+lBAIMA,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,sBAAA,CAAgCA,CAAa,EAAA,cAAA,EAAkB,OAAQ,CAAA,GAAA,CAAI,sBAA0B,EAAA,EAAA,CACrG,iBAA4BA,CAAAA,CAAAA,EAAa,UAAc,EAAA,OAAA,CAAQ,GAAI,CAAA,iBAAA,EAAqB,GACxF,sBAA6BA,CAAAA,CAAAA,EAAa,WAAe,EAAA,OAAA,CAAQ,GAAI,CAAA,sBAAA,EAA0B,EAC/F,CAAA,gBAAA,CAAiCA,CAAa,E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5B,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-BSNA6RYF.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,2 +1,2 @@
1
- import {b}from'./chunk-VW3LGHTJ.js';var s=class extends b{endpoint="message_qrdls";constructor(e,t){super(e,t);}async createQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}};var p=s;export{s as a,p as b};//# sourceMappingURL=chunk-FFOE5YKT.js.map
2
- //# sourceMappingURL=chunk-FFOE5YKT.js.map
1
+ import {b}from'./chunk-VW3LGHTJ.js';var s=class extends b{endpoint="message_qrdls";constructor(e,o){super(e,o);}async createQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}};export{s as a};//# sourceMappingURL=chunk-GT3XQN7Y.js.map
2
+ //# sourceMappingURL=chunk-GT3XQN7Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/features/qrCode/QrCodeApi.ts"],"names":["QrCodeApi","BaseAPI","config","client","request","qrCodeId"],"mappings":"oCAiBA,IAAqBA,CAArB,CAAA,cAAuCC,CAAsC,CACxD,QAAW,CAAA,eAAA,CAE5B,WAAYC,CAAAA,CAAAA,CAAwBC,CAAwB,CAAA,CACxD,KAAMD,CAAAA,CAAAA,CAAQC,CAAM,EACxB,CAcA,MAAM,YAAaC,CAAAA,CAAAA,CAAqE,CACpF,OAAO,IAAK,CAAA,QAAA,CAAA,MAAA,CAER,CAAG,EAAA,IAAA,CAAK,MAAO,CAAA,kBAA6B,CAAI,CAAA,EAAA,IAAA,CAAK,QAAQ,CAC7D,CAAA,CAAA,IAAA,CAAK,MAAO,CAAA,eAAA,CACZ,IAAK,CAAA,SAAA,CAAUA,CAAO,CAC1B,CACJ,CAUA,MAAM,UAAA,EAA8C,CAChD,OAAO,IAAK,CAAA,QAAA,CAAA,KAAA,CAER,CAAG,EAAA,IAAA,CAAK,MAAO,CAAA,kBAA6B,CAAI,CAAA,EAAA,IAAA,CAAK,QAAQ,CAAA,CAAA,CAC7D,IAAK,CAAA,MAAA,CAAO,eACZ,CAAA,IACJ,CACJ,CAWA,MAAM,SAAA,CAAUC,EAAkD,CAC9D,OAAO,IAAK,CAAA,QAAA,CAAA,KAAA,CAER,CAAG,EAAA,IAAA,CAAK,MAAO,CAAA,kBAA6B,CAAI,CAAA,EAAA,IAAA,CAAK,QAAQ,CAAA,CAAA,EAAIA,CAAQ,CAAA,CAAA,CACzE,IAAK,CAAA,MAAA,CAAO,eACZ,CAAA,IACJ,CACJ,CAcA,MAAM,YAAA,CAAaD,CAAqE,CAAA,CACpF,OAAO,IAAA,CAAK,QAER,CAAA,MAAA,CAAA,CAAA,EAAG,IAAK,CAAA,MAAA,CAAO,kBAA6B,CAAA,CAAA,EAAI,KAAK,QAAQ,CAAA,CAAA,CAC7D,IAAK,CAAA,MAAA,CAAO,eACZ,CAAA,IAAA,CAAK,SAAUA,CAAAA,CAAO,CAC1B,CACJ,CAWA,MAAM,YAAaC,CAAAA,CAAAA,CAA4C,CAC3D,OAAO,IAAK,CAAA,QAAA,CAAA,QAAA,CAER,CAAG,EAAA,IAAA,CAAK,MAAO,CAAA,kBAA6B,CAAI,CAAA,EAAA,IAAA,CAAK,QAAQ,CAAA,CAAA,EAAIA,CAAQ,CAAA,CAAA,CACzE,IAAK,CAAA,MAAA,CAAO,eACZ,CAAA,IACJ,CACJ,CACJ","file":"chunk-GT3XQN7Y.js","sourcesContent":["import { BaseAPI } from '@shared/types/base';\nimport type { WabaConfigType } from '@shared/types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '@shared/types/enums';\nimport type { RequesterClass, ResponseSuccess } from '@shared/types/request';\n\nimport type * as qrCode from './types';\n\n/**\n * API for managing WhatsApp QR Codes.\n *\n * This API allows you to:\n * - Create QR codes with prefilled messages\n * - Get all QR codes\n * - Get specific QR code details\n * - Update QR code messages\n * - Delete QR codes\n */\nexport default class QrCodeApi extends BaseAPI implements qrCode.QrCodeClass {\n private readonly endpoint = 'message_qrdls';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Create a new QR code with a prefilled message.\n *\n * @param request The QR code creation request\n * @returns QR code information including code, deep link URL, and optional image URL\n *\n * @example\n * const qrCode = await whatsappClient.qrCode.createQrCode({\n * prefilled_message: 'Hello from WhatsApp!',\n * generate_qr_image: 'PNG'\n * });\n */\n async createQrCode(request: qrCode.CreateQrCodeRequest): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Get all QR codes for the current phone number.\n *\n * @returns List of all QR codes\n *\n * @example\n * const qrCodes = await whatsappClient.qrCode.getQrCodes();\n */\n async getQrCodes(): Promise<qrCode.QrCodesResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get a specific QR code by ID.\n *\n * @param qrCodeId The QR code ID to retrieve\n * @returns QR code information\n *\n * @example\n * const qrCode = await whatsappClient.qrCode.getQrCode('qr_code_123');\n */\n async getQrCode(qrCodeId: string): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}/${qrCodeId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update an existing QR code's prefilled message.\n *\n * @param request The QR code update request containing code and new message\n * @returns Updated QR code information\n *\n * @example\n * const updatedQrCode = await whatsappClient.qrCode.updateQrCode({\n * code: 'existing_qr_code',\n * prefilled_message: 'Updated message!'\n * });\n */\n async updateQrCode(request: qrCode.UpdateQrCodeRequest): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Delete a QR code.\n *\n * @param qrCodeId The QR code ID to delete\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.qrCode.deleteQrCode('qr_code_123');\n */\n async deleteQrCode(qrCodeId: string): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}/${qrCodeId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-R36L2XYO.js';var p=a;export{p as a};//# sourceMappingURL=chunk-H55VIWDI.js.map
2
+ //# sourceMappingURL=chunk-H55VIWDI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/features/template/index.ts"],"names":["template_default","TemplateApi"],"mappings":"oCAGA,IAAOA,CAAQC,CAAAA","file":"chunk-H55VIWDI.js","sourcesContent":["import TemplateApi from './TemplateApi';\n\n// 기본 export 유지\nexport default TemplateApi;\n\n// 명시적 named export\nexport { TemplateApi };\n\n// 필요한 타입만 명시적으로 export\nexport type {\n TemplateClass,\n TemplateDeleteParams,\n TemplateGetParams,\n TemplateRequestBody,\n TemplateResponse,\n} from './types';\n"]}
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-GT3XQN7Y.js';var r=a;export{r as a};//# sourceMappingURL=chunk-I222VSWK.js.map
2
+ //# sourceMappingURL=chunk-I222VSWK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/features/qrCode/index.ts"],"names":["qrCode_default","QrCodeApi"],"mappings":"oCAGA,IAAOA,CAAQC,CAAAA","file":"chunk-I222VSWK.js","sourcesContent":["import QrCodeApi from './QrCodeApi';\n\n// 기본 export 유지\nexport default QrCodeApi;\n\n// 명시적 named export\nexport { QrCodeApi };\n\n// 필요한 타입만 명시적으로 export\nexport type { CreateQrCodeRequest, QrCodeClass, QrCodeResponse, QrCodesResponse, UpdateQrCodeRequest } from './types';\n"]}
@@ -1,2 +1,2 @@
1
- import {a}from'./chunk-BZ5QDXNR.js';import {b}from'./chunk-VW3LGHTJ.js';var t=class extends b{endpoint="message_templates";constructor(e,s){super(e,s);}async getTemplate(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,s){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(e){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${a(e??{})}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${a(e)}`,this.config.REQUEST_TIMEOUT,null)}};var l=t;export{t as a,l as b};//# sourceMappingURL=chunk-XIIJD6SG.js.map
2
- //# sourceMappingURL=chunk-XIIJD6SG.js.map
1
+ import {a}from'./chunk-BZ5QDXNR.js';import {b}from'./chunk-VW3LGHTJ.js';var n=class extends b{endpoint="message_templates";constructor(e,s){super(e,s);}async getTemplate(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,s){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(e){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${a(e??{})}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${a(e)}`,this.config.REQUEST_TIMEOUT,null)}};export{n as a};//# sourceMappingURL=chunk-R36L2XYO.js.map
2
+ //# sourceMappingURL=chunk-R36L2XYO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/features/template/TemplateApi.ts"],"names":["TemplateApi","BaseAPI","config","client","templateId","template","params","objectToQueryString"],"mappings":"wEAaA,IAAqBA,CAArB,CAAA,cAAyCC,CAAiC,CACrD,QAAW,CAAA,mBAAA,CAE5B,WAAYC,CAAAA,CAAAA,CAAwBC,CAAwB,CAAA,CACxD,KAAMD,CAAAA,CAAAA,CAAQC,CAAM,EACxB,CAEA,MAAM,WAAYC,CAAAA,CAAAA,CAA+C,CAC7D,OAAO,IAAK,CAAA,QAAA,CAAA,KAAA,CAA8B,CAAGA,EAAAA,CAAU,CAAI,CAAA,CAAA,IAAA,CAAK,MAAO,CAAA,eAAA,CAAgC,IAAI,CAC/G,CAEA,MAAM,cAAeA,CAAAA,CAAAA,CAAoBC,CAAkE,CAAA,CACvG,OAAO,IAAA,CAAK,QAER,CAAA,MAAA,CAAA,CAAA,EAAGD,CAAU,CAAA,CAAA,CACb,IAAK,CAAA,MAAA,CAAO,eACZ,CAAA,IAAA,CAAK,SAAUC,CAAAA,CAAQ,CAC3B,CACJ,CAEA,MAAM,YAAaC,CAAAA,CAAAA,CAA2E,CAC1F,OAAO,IAAK,CAAA,QAAA,CAAA,KAAA,CAER,CAAG,EAAA,IAAA,CAAK,OAAO,sBAA8B,CAAA,CAAA,EAAI,IAAK,CAAA,QAAQ,CAAGC,EAAAA,CAAAA,CAAoBD,CAAU,EAAA,EAAE,CAAC,CAClG,CAAA,CAAA,IAAA,CAAK,MAAO,CAAA,eAAA,CACZ,IACJ,CACJ,CAEA,MAAM,cAAeD,CAAAA,CAAAA,CAA0D,CAC3E,OAAO,IAAK,CAAA,QAAA,CAAA,MAAA,CAER,CAAG,EAAA,IAAA,CAAK,MAAO,CAAA,sBAA8B,CAAI,CAAA,EAAA,IAAA,CAAK,QAAQ,CAAA,CAAA,CAC9D,IAAK,CAAA,MAAA,CAAO,eACZ,CAAA,IAAA,CAAK,SAAUA,CAAAA,CAAQ,CAC3B,CACJ,CAEA,MAAM,cAAeC,CAAAA,CAAAA,CAAwD,CACzE,OAAO,IAAK,CAAA,QAAA,CAAA,QAAA,CAER,CAAG,EAAA,IAAA,CAAK,MAAO,CAAA,sBAA8B,CAAI,CAAA,EAAA,IAAA,CAAK,QAAQ,CAAA,EAAGC,CAAoBD,CAAAA,CAAM,CAAC,CAAA,CAAA,CAC5F,IAAK,CAAA,MAAA,CAAO,eACZ,CAAA,IACJ,CACJ,CACJ","file":"chunk-R36L2XYO.js","sourcesContent":["import { BaseAPI } from '@shared/types/base';\nimport type { WabaConfigType } from '@shared/types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '@shared/types/enums';\nimport type { RequesterClass, ResponsePagination, ResponseSuccess } from '@shared/types/request';\nimport { objectToQueryString } from '@shared/utils/objectToQueryString';\nimport type {\n TemplateClass,\n TemplateDeleteParams,\n TemplateGetParams,\n TemplateRequestBody,\n TemplateResponse,\n} from './types';\n\nexport default class TemplateApi extends BaseAPI implements TemplateClass {\n private readonly endpoint = 'message_templates';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getTemplate(templateId: string): Promise<TemplateResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${templateId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n async updateTemplate(templateId: string, template: Partial<TemplateRequestBody>): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${templateId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(template),\n );\n }\n\n async getTemplates(params?: TemplateGetParams): Promise<ResponsePagination<TemplateResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${objectToQueryString(params ?? {})}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async createTemplate(template: TemplateRequestBody): Promise<TemplateResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(template),\n );\n }\n\n async deleteTemplate(params: TemplateDeleteParams): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${objectToQueryString(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n"]}