meta-cloud-api 1.6.0 → 1.6.1

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["LOGGER","LOGGER","decryptedAesKey: Buffer","flipped_iv: number[]","LOGGER","LOGGER","headers: HeadersInit","queryParts: string[]","fileContent: Blob","body: m.MessageRequestBody<T>","textPayload: m.TextObject","body: registration.RegistrationRequest","header: TemplateHeader","body: TemplateBody","buttons: TemplateButton[]","urlButton: any","flowButton: any","components: ComponentTypes[]","carouselComponents: ComponentTypes[]","carouselCards: MediaCarouselCard[]","cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[]","carouselCards: ProductCarouselCard[]","LOGGER","MessageApi","SDKEnums","LOGGER","errors: string[]","flowType: FlowTypeEnum","processed: ProcessedStatus","processed: ProcessedMessage","chunks: Buffer[]","crypto"],"sources":["../src/types/enums.ts","../src/utils/logger.ts","../src/config/importConfig.ts","../src/utils/configTable.ts","../src/utils/flowEncryptionUtils.ts","../src/utils/isMetaError.ts","../src/utils/http/httpsClient.ts","../src/utils/http/request.ts","../src/utils/version.ts","../src/types/base.ts","../src/utils/objectToQueryString.ts","../src/api/blockUsers/BlockUsersApi.ts","../src/api/encryption/EncryptionApi.ts","../src/api/flow/FlowApi.ts","../src/api/flow/types/common.ts","../src/api/media/MediaApi.ts","../src/api/messages/MessageApi.ts","../src/api/phone/PhoneNumberApi.ts","../src/utils/buildFieldsQueryString.ts","../src/api/profile/BusinessProfileApi.ts","../src/api/qrCode/QrCodeApi.ts","../src/api/registration/RegistrationApi.ts","../src/api/template/TemplateApi.ts","../src/api/template/factories/index.ts","../src/api/twoStepVerification/TwoStepVerificationApi.ts","../src/api/waba/WabaApi.ts","../src/utils/logoConsole.ts","../src/core/whatsapp/WhatsApp.ts","../src/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts","../src/core/webhook/frameworks/handler.ts","../src/core/webhook/frameworks/express/express.ts","../src/core/webhook/frameworks/nextjs-page/nextjs-page.ts","../src/core/webhook/frameworks/nextjs-app/nextjs-app.ts","../src/core/webhook/utils/generateXHub256Sig.ts","../src/api/waba/types/common.ts"],"sourcesContent":["export enum CategoryEnum {\n Authentication = 'AUTHENTICATION',\n Marketing = 'MARKETING',\n Utility = 'UTILITY',\n}\n\nexport enum TemplateStatusEnum {\n Approved = 'APPROVED',\n Pending = 'PENDING',\n Rejected = 'REJECTED',\n}\n\nexport enum HttpMethodsEnum {\n Get = 'GET',\n Post = 'POST',\n Put = 'PUT',\n Delete = 'DELETE',\n}\n\nexport enum MessageTypesEnum {\n Audio = 'audio',\n Contacts = 'contacts',\n Document = 'document',\n Image = 'image',\n Interactive = 'interactive',\n Location = 'location',\n Reaction = 'reaction',\n Sticker = 'sticker',\n Template = 'template',\n Text = 'text',\n Video = 'video',\n Button = 'button',\n Order = 'order',\n System = 'system',\n Unsupported = 'unsupported',\n Unknown = 'unknown',\n /**\n * @deprecated Use WebhookProcessor.onStatus() instead of onMessage(MessageTypesEnum.Statuses)\n */\n Statuses = 'statuses',\n '*' = '*',\n}\n\nexport enum ParametersTypesEnum {\n Action = 'ACTION',\n CouponCode = 'COUPON_CODE',\n Currency = 'CURRENCY',\n DateTime = 'DATE_TIME',\n Document = 'DOCUMENT',\n ExpirationTimeMs = 'EXPIRATION_TIME_MS',\n Image = 'IMAGE',\n LimitedTimeOffer = 'LIMITED_TIME_OFFER',\n Location = 'LOCATION',\n OrderStatus = 'ORDER_STATUS',\n Payload = 'PAYLOAD',\n Product = 'PRODUCT',\n Text = 'TEXT',\n TtlMinutes = 'TTL_MINUTES',\n Video = 'VIDEO',\n WebviewInteraction = 'WEBVIEW_INTERACTION',\n WebviewPresentation = 'WEBVIEW_PRESENTATION',\n}\n\nexport enum InteractiveTypesEnum {\n Button = 'button',\n List = 'list',\n Product = 'product',\n ProductList = 'product_list',\n CtaUrl = 'cta_url',\n LocationRequest = 'location_request_message',\n AddressMessage = 'address_message',\n Flow = 'flow',\n}\n\nexport enum ButtonPositionEnum {\n First = 1,\n Second = 2,\n Third = 3,\n Fourth = 4,\n Fifth = 5,\n}\n\nexport enum SubTypeEnum {\n Catalog = 'CATALOG',\n CopyCode = 'COPY_CODE',\n Flow = 'FLOW',\n Mpm = 'MPM',\n OrderDetails = 'ORDER_DETAILS',\n QuickReply = 'QUICK_REPLY',\n Reminder = 'REMINDER',\n Url = 'URL',\n VoiceCall = 'VOICE_CALL',\n}\n\nexport enum ComponentTypesEnum {\n Header = 'HEADER',\n Body = 'BODY',\n Button = 'BUTTON',\n Footer = 'FOOTER',\n}\n\nexport enum WabaConfigEnum {\n AppId = 'M4D_APP_ID',\n Port = 'WA_PORT',\n AppSecret = 'M4D_APP_SECRET',\n PhoneNumberId = 'WA_PHONE_NUMBER_ID',\n BusinessAcctId = 'WA_BUSINESS_ACCOUNT_ID',\n APIVersion = 'CLOUD_API_VERSION',\n AccessToken = 'CLOUD_API_ACCESS_TOKEN',\n WebhookEndpoint = 'WEBHOOK_ENDPOINT',\n WebhookVerificationToken = 'WEBHOOK_VERIFICATION_TOKEN',\n ListenerPort = 'LISTENER_PORT',\n MaxRetriesAfterWait = 'MAX_RETRIES_AFTER_WAIT',\n RequestTimeout = 'REQUEST_TIMEOUT',\n Debug = 'DEBUG',\n PrivatePem = 'FLOW_API_PRIVATE_PEM',\n Passphrase = 'FLOW_API_PASSPHRASE',\n}\n\nexport enum ConversationTypesEnum {\n BusinessInitiated = 'business_initiated',\n CustomerInitiated = 'customer_initiated',\n ReferralConversion = 'referral_conversion',\n}\n\nexport enum StatusEnum {\n Delivered = 'delivered',\n Read = 'read',\n Sent = 'sent',\n}\n\nexport enum VideoMediaTypesEnum {\n Mp4 = 'video/mp4',\n Threegp = 'video/3gp',\n}\n\nexport enum StickerMediaTypesEnum {\n Webp = 'image/webp',\n}\n\nexport enum ImageMediaTypesEnum {\n Jpeg = 'image/jpeg',\n Png = 'image/png',\n}\n\nexport enum DocumentMediaTypesEnum {\n Text = 'text/plain',\n Pdf = 'application/pdf',\n Ppt = 'application/vnd.ms-powerpoint',\n Word = 'application/msword',\n Excel = 'application/vnd.ms-excel',\n OpenDoc = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n OpenPres = 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n OpenSheet = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n}\n\nexport enum AudioMediaTypesEnum {\n Aac = 'audio/aac',\n Mp4 = 'audio/mp4',\n Mpeg = 'audio/mpeg',\n Amr = 'audio/amr',\n Ogg = 'audio/ogg',\n}\n\nexport enum WebhookTypesEnum {\n Audio = 'audio',\n Button = 'button',\n Document = 'document',\n Text = 'text',\n Image = 'image',\n Interactive = 'interactive',\n Order = 'order',\n Sticker = 'sticker',\n System = 'system',\n Unknown = 'unknown',\n Video = 'video',\n}\n\nexport enum SystemChangeTypesEnum {\n CustomerChangedNumber = 'customer_changed_number',\n CustomerIdentityChanged = 'customer_identity_changed',\n}\n\nexport enum ReferralSourceTypesEnum {\n Ad = 'ad',\n Post = 'post',\n}\n\nexport enum RequestCodeMethodsEnum {\n Sms = 'SMS',\n Voice = 'VOICE',\n}\n\nexport enum LanguagesEnum {\n Afrikaans = 'af',\n Albanian = 'sq',\n Arabic = 'ar',\n Azerbaijani = 'az',\n Bengali = 'bn',\n Bulgarian = 'bg',\n Catalan = 'ca',\n Chinese_CHN = 'zh_CN',\n Chinese_HKG = 'zh_HK',\n Chinese_TAI = 'zh_TW',\n Croatian = 'hr',\n Czech = 'cs',\n Danish = 'da',\n Dutch = 'nl',\n English = 'en',\n English_UK = 'en_GB',\n English_US = 'en_US',\n Estonian = 'et',\n Filipino = 'fil',\n Finnish = 'fi',\n French = 'fr',\n Georgian = 'ka',\n German = 'de',\n Greek = 'el',\n Gujarati = 'gu',\n Hausa = 'ha',\n Hebrew = 'he',\n Hindi = 'hi',\n Hungarian = 'hu',\n Indonesian = 'id',\n Irish = 'ga',\n Italian = 'it',\n Japanese = 'ja',\n Kannada = 'kn',\n Kazakh = 'kk',\n Kinyarwanda = 'rw_RW',\n Korean = 'ko',\n Kyrgyz_Kyrgyzstan = 'ky_KG',\n Lao = 'lo',\n Latvian = 'lv',\n Lithuanian = 'lt',\n Macedonian = 'mk',\n Malay = 'ms',\n Malayalam = 'ml',\n Marathi = 'mr',\n Norwegian = 'nb',\n Persian = 'fa',\n Polish = 'pl',\n Portuguese_BR = 'pt_BR',\n Portuguese_POR = 'pt_PT',\n Punjabi = 'pa',\n Romanian = 'ro',\n Russian = 'ru',\n Serbian = 'sr',\n Slovak = 'sk',\n Slovenian = 'sl',\n Spanish = 'es',\n Spanish_ARG = 'es_AR',\n Spanish_SPA = 'es_ES',\n Spanish_MEX = 'es_MX',\n Swahili = 'sw',\n Swedish = 'sv',\n Tamil = 'ta',\n Telugu = 'te',\n Thai = 'th',\n Turkish = 'tr',\n Ukrainian = 'uk',\n Urdu = 'ur',\n Uzbek = 'uz',\n Vietnamese = 'vi',\n Zulu = 'zu',\n}\n\nexport enum CurrencyCodesEnum {\n AFN = 'AFN',\n EUR = 'EUR',\n ALL = 'ALL',\n DZD = 'DZD',\n USD = 'USD',\n AOA = 'AOA',\n XCD = 'XCD',\n ARS = 'ARS',\n AMD = 'AMD',\n AWG = 'AWG',\n AUD = 'AUD',\n AZN = 'AZN',\n BSD = 'BSD',\n BHD = 'BHD',\n BDT = 'BDT',\n BBD = 'BBD',\n BYN = 'BYN',\n BZD = 'BZD',\n XOF = 'XOF',\n BMD = 'BMD',\n INR = 'INR',\n BTN = 'BTN',\n BOB = 'BOB',\n BOV = 'BOV',\n BAM = 'BAM',\n BWP = 'BWP',\n NOK = 'NOK',\n BRL = 'BRL',\n BND = 'BND',\n BGN = 'BGN',\n BIF = 'BIF',\n CVE = 'CVE',\n KHR = 'KHR',\n XAF = 'XAF',\n CAD = 'CAD',\n KYD = 'KYD',\n CLP = 'CLP',\n CLF = 'CLF',\n CNY = 'CNY',\n COP = 'COP',\n COU = 'COU',\n KMF = 'KMF',\n CDF = 'CDF',\n NZD = 'NZD',\n CRC = 'CRC',\n HRK = 'HRK',\n CUP = 'CUP',\n CUC = 'CUC',\n ANG = 'ANG',\n CZK = 'CZK',\n DKK = 'DKK',\n DJF = 'DJF',\n DOP = 'DOP',\n EGP = 'EGP',\n SVC = 'SVC',\n ERN = 'ERN',\n SZL = 'SZL',\n ETB = 'ETB',\n FKP = 'FKP',\n FJD = 'FJD',\n XPF = 'XPF',\n GMD = 'GMD',\n GEL = 'GEL',\n GHS = 'GHS',\n GIP = 'GIP',\n GTQ = 'GTQ',\n GBP = 'GBP',\n GNF = 'GNF',\n GYD = 'GYD',\n HTG = 'HTG',\n HNL = 'HNL',\n HKD = 'HKD',\n HUF = 'HUF',\n ISK = 'ISK',\n IDR = 'IDR',\n XDR = 'XDR',\n IRR = 'IRR',\n IQD = 'IQD',\n ILS = 'ILS',\n JMD = 'JMD',\n JPY = 'JPY',\n JOD = 'JOD',\n KZT = 'KZT',\n KES = 'KES',\n KPW = 'KPW',\n KRW = 'KRW',\n KWD = 'KWD',\n KGS = 'KGS',\n LAK = 'LAK',\n LBP = 'LBP',\n LSL = 'LSL',\n ZAR = 'ZAR',\n LRD = 'LRD',\n LYD = 'LYD',\n CHF = 'CHF',\n MOP = 'MOP',\n MKD = 'MKD',\n MGA = 'MGA',\n MWK = 'MWK',\n MYR = 'MYR',\n MVR = 'MVR',\n MRU = 'MRU',\n MUR = 'MUR',\n XUA = 'XUA',\n MXN = 'MXN',\n MXV = 'MXV',\n MDL = 'MDL',\n MNT = 'MNT',\n MAD = 'MAD',\n MZN = 'MZN',\n MMK = 'MMK',\n NAD = 'NAD',\n NPR = 'NPR',\n NIO = 'NIO',\n NGN = 'NGN',\n OMR = 'OMR',\n PKR = 'PKR',\n PAB = 'PAB',\n PGK = 'PGK',\n PYG = 'PYG',\n PEN = 'PEN',\n PHP = 'PHP',\n PLN = 'PLN',\n QAR = 'QAR',\n RON = 'RON',\n RUB = 'RUB',\n RWF = 'RWF',\n SHP = 'SHP',\n WST = 'WST',\n STN = 'STN',\n SAR = 'SAR',\n RSD = 'RSD',\n SCR = 'SCR',\n SLL = 'SLL',\n SGD = 'SGD',\n XSU = 'XSU',\n SBD = 'SBD',\n SOS = 'SOS',\n SSP = 'SSP',\n LKR = 'LKR',\n SDG = 'SDG',\n SRD = 'SRD',\n SEK = 'SEK',\n CHE = 'CHE',\n CHW = 'CHW',\n SYP = 'SYP',\n TWD = 'TWD',\n TJS = 'TJS',\n TZS = 'TZS',\n THB = 'THB',\n TOP = 'TOP',\n TTD = 'TTD',\n TND = 'TND',\n TRY = 'TRY',\n TMT = 'TMT',\n UGX = 'UGX',\n UAH = 'UAH',\n AED = 'AED',\n USN = 'USN',\n UYU = 'UYU',\n UYI = 'UYI',\n UYW = 'UYW',\n UZS = 'UZS',\n VUV = 'VUV',\n VES = 'VES',\n VND = 'VND',\n YER = 'YER',\n ZMW = 'ZMW',\n ZWL = 'ZWL',\n XBA = 'XBA',\n XBB = 'XBB',\n XBC = 'XBC',\n XBD = 'XBD',\n XTS = 'XTS',\n XXX = 'XXX',\n XAU = 'XAU',\n XPD = 'XPD',\n XPT = 'XPT',\n XAG = 'XAG',\n AFA = 'AFA',\n FIM = 'FIM',\n ALK = 'ALK',\n ADP = 'ADP',\n ESP = 'ESP',\n FRF = 'FRF',\n AOK = 'AOK',\n AON = 'AON',\n AOR = 'AOR',\n ARA = 'ARA',\n ARP = 'ARP',\n ARY = 'ARY',\n RUR = 'RUR',\n ATS = 'ATS',\n AYM = 'AYM',\n AZM = 'AZM',\n BYB = 'BYB',\n BYR = 'BYR',\n BEC = 'BEC',\n BEF = 'BEF',\n BEL = 'BEL',\n BOP = 'BOP',\n BAD = 'BAD',\n BRB = 'BRB',\n BRC = 'BRC',\n BRE = 'BRE',\n BRN = 'BRN',\n BRR = 'BRR',\n BGJ = 'BGJ',\n BGK = 'BGK',\n BGL = 'BGL',\n BUK = 'BUK',\n HRD = 'HRD',\n CYP = 'CYP',\n CSJ = 'CSJ',\n CSK = 'CSK',\n ECS = 'ECS',\n ECV = 'ECV',\n GQE = 'GQE',\n EEK = 'EEK',\n XEU = 'XEU',\n GEK = 'GEK',\n DDM = 'DDM',\n DEM = 'DEM',\n GHC = 'GHC',\n GHP = 'GHP',\n GRD = 'GRD',\n GNE = 'GNE',\n GNS = 'GNS',\n GWE = 'GWE',\n GWP = 'GWP',\n ITL = 'ITL',\n ISJ = 'ISJ',\n IEP = 'IEP',\n ILP = 'ILP',\n ILR = 'ILR',\n LAJ = 'LAJ',\n LVL = 'LVL',\n LVR = 'LVR',\n LSM = 'LSM',\n ZAL = 'ZAL',\n LTL = 'LTL',\n LTT = 'LTT',\n LUC = 'LUC',\n LUF = 'LUF',\n LUL = 'LUL',\n MGF = 'MGF',\n MVQ = 'MVQ',\n MLF = 'MLF',\n MTL = 'MTL',\n MTP = 'MTP',\n MRO = 'MRO',\n MXP = 'MXP',\n MZE = 'MZE',\n MZM = 'MZM',\n NLG = 'NLG',\n NIC = 'NIC',\n PEH = 'PEH',\n PEI = 'PEI',\n PES = 'PES',\n PLZ = 'PLZ',\n PTE = 'PTE',\n ROK = 'ROK',\n ROL = 'ROL',\n STD = 'STD',\n CSD = 'CSD',\n SKK = 'SKK',\n SIT = 'SIT',\n RHD = 'RHD',\n ESA = 'ESA',\n ESB = 'ESB',\n SDD = 'SDD',\n SDP = 'SDP',\n SRG = 'SRG',\n CHC = 'CHC',\n TJR = 'TJR',\n TPE = 'TPE',\n TRL = 'TRL',\n TMM = 'TMM',\n UGS = 'UGS',\n UGW = 'UGW',\n UAK = 'UAK',\n SUR = 'SUR',\n USS = 'USS',\n UYN = 'UYN',\n UYP = 'UYP',\n VEB = 'VEB',\n VEF = 'VEF',\n VNC = 'VNC',\n YDD = 'YDD',\n YUD = 'YUD',\n YUM = 'YUM',\n YUN = 'YUN',\n ZRN = 'ZRN',\n ZRZ = 'ZRZ',\n ZMK = 'ZMK',\n ZWC = 'ZWC',\n ZWD = 'ZWD',\n ZWN = 'ZWN',\n ZWR = 'ZWR',\n XFO = 'XFO',\n XRE = 'XRE',\n XFU = 'XFU',\n}\n\nexport enum DataLocalizationRegionEnum {\n // APAC\n AU = 'AU', // Australia\n ID = 'ID', // Indonesia\n IN = 'IN', // India\n JP = 'JP', // Japan\n SG = 'SG', // Singapore\n KR = 'KR', // South Korea\n\n // Europe\n DE = 'DE', // EU (Germany)\n CH = 'CH', // Switzerland\n GB = 'GB', // United Kingdom\n\n // LATAM\n BR = 'BR', // Brazil\n\n // MEA\n BH = 'BH', // Bahrain\n ZA = 'ZA', // South Africa\n AE = 'AE', // United Arab Emirates\n\n // NORAM\n CA = 'CA', // Canada\n}\n\n/**\n * Business category values for WhatsApp Business Profile.\n * These values map to specific strings displayed in the WhatsApp client.\n */\nexport enum BusinessVerticalEnum {\n /**\n * Alcoholic Beverages\n */\n ALCOHOL = 'ALCOHOL',\n /**\n * Clothing and Apparel\n */\n APPAREL = 'APPAREL',\n /**\n * Automotive\n */\n AUTO = 'AUTO',\n /**\n * Beauty, Spa and Salon\n */\n BEAUTY = 'BEAUTY',\n /**\n * Education\n */\n EDU = 'EDU',\n /**\n * Entertainment\n */\n ENTERTAIN = 'ENTERTAIN',\n /**\n * Event Planning and Service\n */\n EVENT_PLAN = 'EVENT_PLAN',\n /**\n * Finance and Banking\n */\n FINANCE = 'FINANCE',\n /**\n * Public Service\n */\n GOVT = 'GOVT',\n /**\n * Food and Grocery\n */\n GROCERY = 'GROCERY',\n /**\n * Medical and Health\n */\n HEALTH = 'HEALTH',\n /**\n * Hotel and Lodging\n */\n HOTEL = 'HOTEL',\n /**\n * Non-profit\n */\n NONPROFIT = 'NONPROFIT',\n /**\n * Online Gambling & Gaming\n */\n ONLINE_GAMBLING = 'ONLINE_GAMBLING',\n /**\n * Over-the-Counter Drugs\n */\n OTC_DRUGS = 'OTC_DRUGS',\n /**\n * Other\n */\n OTHER = 'OTHER',\n /**\n * Non-Online Gambling & Gaming (E.g. Brick and mortar)\n */\n PHYSICAL_GAMBLING = 'PHYSICAL_GAMBLING',\n /**\n * Professional Services\n */\n PROF_SERVICES = 'PROF_SERVICES',\n /**\n * Restaurant\n */\n RESTAURANT = 'RESTAURANT',\n /**\n * Shopping and Retail\n */\n RETAIL = 'RETAIL',\n /**\n * Travel and Transportation\n */\n TRAVEL = 'TRAVEL',\n}\n","// @ts-nocheck\nimport { inspect } from 'util';\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n private formatData(data: any[]): string {\n return data\n .map((item) => (typeof item === 'object' ? inspect(item, { depth: null, colors: true }) : item))\n .join(' ');\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log(prefix, ': ', this.formatData(data));\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error(prefix, ': ', this.formatData(data));\n }\n\n warn(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn(prefix, ': ', this.formatData(data));\n }\n }\n\n info(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info(prefix, ': ', this.formatData(data));\n }\n }\n}\n","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 return wabaConfig;\n};\n","import type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\n\n/**\n * Formats configuration as a terminal table\n * @param config - The WABA configuration object\n * @param apiName - The name of the API being initialized\n * @returns Formatted table string\n */\nexport function formatConfigTable(config: WabaConfigType): string {\n const configData = [\n ['App ID', config[WabaConfigEnum.AppId] || 'Not Set'],\n ['Phone Number ID', config[WabaConfigEnum.PhoneNumberId]?.toString() || 'Not Set'],\n ['Business Account ID', config[WabaConfigEnum.BusinessAcctId] || 'Not Set'],\n ['API Version', config[WabaConfigEnum.APIVersion] || 'Not Set'],\n [\n 'Access Token',\n config[WabaConfigEnum.AccessToken]\n ? `${config[WabaConfigEnum.AccessToken].substring(0, 20)}...`\n : 'Not Set',\n ],\n ['Webhook Endpoint', config[WabaConfigEnum.WebhookEndpoint] || 'Not Set'],\n [\n 'Webhook Verification Token',\n config[WabaConfigEnum.WebhookVerificationToken]\n ? `${config[WabaConfigEnum.WebhookVerificationToken].substring(0, 10)}...`\n : 'Not Set',\n ],\n ['Listener Port', config[WabaConfigEnum.ListenerPort]?.toString() || 'Not Set'],\n ['Debug Mode', config[WabaConfigEnum.Debug] ? 'Enabled' : 'Disabled'],\n ['Max Retries', config[WabaConfigEnum.MaxRetriesAfterWait]?.toString() || 'Not Set'],\n [\n 'Request Timeout',\n config[WabaConfigEnum.RequestTimeout] ? `${config[WabaConfigEnum.RequestTimeout]}ms` : 'Not Set',\n ],\n ['Private PEM', config[WabaConfigEnum.PrivatePem] ? 'Configured' : 'Not Set'],\n ['Passphrase', config[WabaConfigEnum.Passphrase] ? 'Configured' : 'Not Set'],\n ];\n\n // Calculate column widths\n const maxKeyLength = Math.max(...configData.map(([key]) => key?.length || 0));\n const maxValueLength = Math.max(...configData.map(([, value]) => value?.length || 0));\n\n const keyWidth = Math.max(maxKeyLength, 20);\n const valueWidth = Math.max(maxValueLength, 30);\n\n // Create table\n const horizontalLine = `┌${'─'.repeat(keyWidth + 2)}┬${'─'.repeat(valueWidth + 2)}┐`;\n const separator = `├${'─'.repeat(keyWidth + 2)}┼${'─'.repeat(valueWidth + 2)}┤`;\n const bottomLine = `└${'─'.repeat(keyWidth + 2)}┴${'─'.repeat(valueWidth + 2)}┘`;\n\n const header = `│ ${'Configuration'.padEnd(keyWidth)} │ ${'Value'.padEnd(valueWidth)} │`;\n\n const rows = configData.map(([key, value]) => `│ ${key?.padEnd(keyWidth)} │ ${value?.padEnd(valueWidth)} │`);\n\n return [horizontalLine, header, separator, ...rows, bottomLine].join('\\n');\n}\n","/**\n * WhatsApp Flow Encryption/Decryption Utilities\n * Handles encryption and decryption of WhatsApp Flow requests and responses\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\n\nimport crypto from 'crypto';\n\nimport { FlowEndpointRequest } from '../api/flow';\nimport { WabaConfigType } from '../types/config';\nimport Logger from './logger';\n\nconst LIB_NAME = 'FLOW_ENCRYPTION_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Environment model for encryption keys\n */\nexport type EncryptionKeyPair = {\n passphrase: string;\n privateKey: string;\n publicKey: string;\n};\n\n/**\n * Validates that the code is running in a Node.js environment\n * @throws {Error} If not running in Node.js environment\n */\nfunction validateNodeEnvironment(): void {\n // Check if crypto module exists and has required methods\n if (!crypto || typeof crypto.generateKeyPairSync !== 'function') {\n const error = new Error(\n 'This utility requires Node.js environment with crypto module. ' +\n 'It cannot be used in browser or edge runtime environments.',\n );\n LOGGER.error('Environment validation failed:', error);\n throw error;\n }\n\n // Check if running in browser\n if (typeof window !== 'undefined') {\n const error = new Error(\n 'This utility cannot run in a browser environment. ' +\n 'Please use it in a Node.js server environment only.',\n );\n LOGGER.error('Browser environment detected:', error);\n throw error;\n }\n\n // Check Node.js version (crypto.generateKeyPairSync requires Node.js 10.12.0+)\n if (process.versions && process.versions.node) {\n const nodeVersion = process.versions.node.split('.').map(Number);\n const major = nodeVersion[0] ?? 0;\n const minor = nodeVersion[1] ?? 0;\n\n if (major < 10 || (major === 10 && minor < 12)) {\n const error = new Error(\n `Node.js version ${process.versions.node} is not supported. ` +\n 'Please upgrade to Node.js 10.12.0 or higher.',\n );\n LOGGER.error('Node.js version check failed:', error);\n throw error;\n }\n }\n\n LOGGER.info('Environment validation passed');\n}\n\n/**\n * Generates RSA key pair for WhatsApp Business Flow API encryption\n *\n * This function generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from environment\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @example\n * ```typescript\n * import { WhatsApp } from 'meta-cloud-api';\n *\n * const wa = new WhatsApp();\n *\n * try {\n * // Uses FLOW_API_PASSPHRASE from environment\n * const keys = wa.generateEncryption();\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n * } catch (error) {\n * console.error('Failed to generate keys:', error.message);\n * }\n * ```\n */\nexport function generateEncryption(passphrase?: string): EncryptionKeyPair {\n LOGGER.info('Starting encryption key generation');\n\n // Validate environment first\n validateNodeEnvironment();\n\n // Get passphrase from parameter or environment variable\n const effectivePassphrase = passphrase || process.env.FLOW_API_PASSPHRASE;\n\n // Validate passphrase\n if (!effectivePassphrase || effectivePassphrase.trim().length === 0) {\n const error = new Error(\n 'Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.',\n );\n LOGGER.error('Passphrase validation failed:', error);\n throw error;\n }\n\n // Warn if passphrase is too short\n if (effectivePassphrase.length < 8) {\n LOGGER.warn(\n 'Passphrase is shorter than 8 characters. ' + 'Consider using a longer passphrase for better security.',\n );\n }\n\n try {\n LOGGER.info('Generating RSA key pair with 2048-bit modulus');\n\n // Generate RSA key pair\n const keyPair = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: effectivePassphrase,\n },\n });\n\n LOGGER.info('Key pair generated successfully');\n\n return {\n passphrase: effectivePassphrase,\n privateKey: keyPair.privateKey,\n publicKey: keyPair.publicKey,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const generationError = new Error(`Failed to generate key pair: ${errorMessage}`);\n LOGGER.error('Key generation failed:', generationError);\n throw generationError;\n }\n}\n\n/**\n * Decrypt a WhatsApp Flow request\n * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector\n * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and FLOW_API_PASSPHRASE\n * @returns Decrypted flow request body, AES key buffer, and initial vector buffer\n * @throws {Error} If required encryption properties are missing or decryption fails\n */\nexport function decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n // Handle both escaped and unescaped newlines\n let privatePem = config.FLOW_API_PRIVATE_PEM;\n if (privatePem.includes('\\\\n')) {\n privatePem = privatePem.replace(/\\\\n/g, '\\n');\n }\n\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const isPKCS1 = privatePem.includes('-----BEGIN RSA PRIVATE KEY-----');\n const isPKCS8 =\n privatePem.includes('-----BEGIN PRIVATE KEY-----') ||\n privatePem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----');\n\n LOGGER.info('Private key format check:', {\n isPKCS1,\n isPKCS8,\n hasBeginMarker: privatePem.includes('-----BEGIN'),\n hasEndMarker: privatePem.includes('-----END'),\n length: privatePem.length,\n firstLine: privatePem.split('\\n')[0],\n });\n\n let privateKey;\n try {\n // Try to create private key with passphrase\n if (passphrase) {\n privateKey = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase,\n });\n } else {\n privateKey = crypto.createPrivateKey(privatePem);\n }\n } catch (error) {\n LOGGER.error('Failed to create private key:', {\n error: error instanceof Error ? error.message : error,\n pemPreview: privatePem.substring(0, 100) + '...',\n hasPassphrase: !!passphrase,\n isPKCS1,\n isPKCS8,\n });\n\n // Provide helpful error message\n let errorMessage = `Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`;\n\n if (isPKCS1) {\n errorMessage += '\\n\\nYour key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).';\n errorMessage += '\\nPlease convert it to PKCS#8 format using:';\n errorMessage += '\\n openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem';\n errorMessage += '\\n\\nOr ensure your key uses a supported encryption algorithm (not DES-EDE3-CBC).';\n } else if (!isPKCS8) {\n errorMessage += '\\n\\nYour key format is not recognized. Please ensure it is in PKCS#8 format.';\n }\n\n throw new Error(errorMessage);\n }\n\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\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('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\n/**\n * Encrypt a WhatsApp Flow response\n * @param response - Response object to encrypt\n * @param aesKeyBuffer - AES key buffer from the decrypted request\n * @param initialVectorBuffer - Initial vector buffer from the decrypted request\n * @returns Base64-encoded encrypted response\n * @throws {Error} If encryption fails\n */\nexport function encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../../types/httpsClient';\nimport Logger from '../logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\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 '../isMetaError';\nimport Logger from '../logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\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 { readFileSync } from 'fs';\nimport { join } from 'path';\n\n/**\n * Get SDK version from package.json\n */\nexport function getVersion(): string {\n try {\n const packagePath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));\n return packageJson.version;\n } catch (error) {\n return 'unknown';\n }\n}\n\n/**\n * Generate User-Agent string following official SDK pattern\n */\nexport function getUserAgent(): string {\n const version = getVersion();\n const nodeVersion = process.version;\n return `WhatsApp-Nodejs-SDK/${version} (Node.js ${nodeVersion})`;\n}\n","import type { WabaConfigType } from './config';\n\nexport declare class BaseClass {\n constructor(config: WabaConfigType);\n}\n\nimport { HttpMethodsEnum } from './enums';\nimport type { RequesterClass } from './request';\n\nexport class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n\n protected sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.sendFormData<T>(method, endpoint, timeout, body);\n }\n\n protected sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n ): Promise<T> {\n return this.client.sendUrlEncodedForm<T>(method, endpoint, timeout, body);\n }\n}\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const queryParts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n queryParts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return queryParts.length > 0 ? `?${queryParts.join('&')}` : '';\n};\n","import { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\nimport type { WabaConfigType } from '../../types/config';\nimport * as blockUsers from './types/blockUsers';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\n/**\n * Block Users API\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users\n *\n * Limitations:\n * - Can only block users that have messaged your business in the last 24 hours\n * - 64k blocklist limit\n */\nexport default class BlockUsersApi extends BaseAPI implements blockUsers.BlockUsersClass {\n private readonly endpoint = 'block_users';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Build request body for block/unblock operations\n */\n private buildBlockUsersBody(users: string[]): blockUsers.BlockUsersRequest {\n return {\n messaging_product: 'whatsapp',\n block_users: users.map((user) => ({ user })),\n };\n }\n\n /**\n * Block one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to block\n * @returns Response with successfully blocked and failed users\n * @throws Error if users have not messaged in last 24 hours\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#block-users\n *\n * @example\n * ```typescript\n * // Block single user\n * const result = await client.blockUsers.block(['1234567890']);\n *\n * // Block multiple users\n * const result = await client.blockUsers.block(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Blocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async block(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n if (!users || users.length === 0) {\n throw new Error('At least one user must be provided to block');\n }\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unblock one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to unblock\n * @returns Response with successfully unblocked and failed users\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#unblock-users\n *\n * @example\n * ```typescript\n * // Unblock single user\n * const result = await client.blockUsers.unblock(['1234567890']);\n *\n * // Unblock multiple users\n * const result = await client.blockUsers.unblock(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Unblocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async unblock(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n if (!users || users.length === 0) {\n throw new Error('At least one user must be provided to unblock');\n }\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Get list of blocked WhatsApp users with pagination\n * @param params - Optional pagination parameters\n * @returns List of blocked users with pagination info\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#get-list-of-blocked-numbers\n *\n * @example\n * ```typescript\n * // Get first 10 blocked users\n * const result = await client.blockUsers.listBlockedUsers({ limit: 10 });\n *\n * // Pagination with cursor\n * const nextPage = await client.blockUsers.listBlockedUsers({\n * limit: 10,\n * after: result.paging?.cursors?.after\n * });\n *\n * // Get all blocked users\n * const allBlocked = await client.blockUsers.listBlockedUsers();\n * ```\n */\n async listBlockedUsers(params?: blockUsers.ListBlockedUsersParams): Promise<blockUsers.ListBlockedUsersResponse> {\n let endpoint = `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`;\n\n // Add query parameters if provided\n if (params) {\n const queryString = objectToQueryString(params);\n if (queryString) {\n endpoint += `?${queryString}`;\n }\n }\n\n return await this.sendJson<blockUsers.ListBlockedUsersResponse>(\n HttpMethodsEnum.Get,\n endpoint,\n this.config[WabaConfigEnum.RequestTimeout],\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n\nexport default class EncryptionApi extends BaseAPI implements EncryptionClass {\n private readonly endpoint = 'whatsapp_business_encryption';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getEncryptionPublicKey(): Promise<EncryptionPublicKeyResponse> {\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 async setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess> {\n const formData = new FormData();\n formData.append('business_public_key', businessPublicKey);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as flow from './types';\n\n/**\n * API for managing WhatsApp Flows.\n *\n * This API allows you to:\n * - List flows\n * - Create flows\n * - Get flow details and previews\n * - Update flow metadata and JSON\n * - Delete flows\n * - Publish and deprecate flows\n * - Migrate flows between WABAs\n * - Validate flow JSON\n */\nexport default class FlowApi extends BaseAPI implements flow.FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<flow.FlowsListResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<flow.CreateFlowResponse> {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<flow.Flow | flow.FlowPreviewResponse> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(flowId: string, invalidate: boolean = false): Promise<flow.FlowPreviewResponse> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<flow.FlowPreviewResponse>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<flow.FlowAssetsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<flow.UpdateFlowResponse> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<flow.ValidateFlowJsonResponse> {\n try {\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n const isValid = !result.validation_errors || result.validation_errors.length === 0;\n\n const enhancedResponse = {\n ...result,\n valid: isValid,\n };\n\n return enhancedResponse;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<flow.FlowMigrationResponse> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n","import { ResponseSuccess } from '../../../types';\nimport { IncomingHttpHeaders, IncomingMessage } from 'http';\n\n/**\n * Enum for Flow Status\n */\nexport enum FlowStatusEnum {\n Draft = 'DRAFT',\n Published = 'PUBLISHED',\n Throttled = 'THROTTLED',\n Blocked = 'BLOCKED',\n Deprecated = 'DEPRECATED',\n}\n\n/**\n * Enum for Flow Categories\n */\nexport enum FlowCategoryEnum {\n SignUp = 'SIGN_UP',\n SignIn = 'SIGN_IN',\n AppointmentBooking = 'APPOINTMENT_BOOKING',\n LeadGeneration = 'LEAD_GENERATION',\n ContactUs = 'CONTACT_US',\n CustomerSupport = 'CUSTOMER_SUPPORT',\n Survey = 'SURVEY',\n Other = 'OTHER',\n}\n\nexport enum FlowActionEnum {\n INIT = 'INIT',\n BACK = 'BACK',\n DATA_EXCHANGE = 'data_exchange',\n}\n\n/**\n * Enum for Flow Types in webhook handlers\n * Used to register handlers for specific flow events\n */\nexport enum FlowTypeEnum {\n /** Health check/ping requests */\n Ping = 'ping',\n /** Data exchange requests */\n Change = 'data_exchange',\n /** Error notification requests */\n Error = 'error',\n /** Match all flow action types */\n All = '*',\n}\n\nexport type FlowType = (typeof FlowTypeEnum)[keyof typeof FlowTypeEnum];\n\n/**\n * Flow Validation Error Pointer\n */\nexport interface FlowValidationErrorPointer {\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n path: string;\n}\n\n/**\n * Flow Validation Error\n */\nexport interface FlowValidationError {\n error: string;\n error_type: string;\n message: string;\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n pointers: FlowValidationErrorPointer[];\n}\n\n/**\n * Flow Item\n */\nexport interface Flow {\n id: string;\n name: string;\n status: FlowStatusEnum;\n categories: FlowCategoryEnum[];\n validation_errors: FlowValidationError[];\n}\n\n/**\n * Pagination Cursors\n */\nexport interface PaginationCursors {\n before: string;\n after: string;\n}\n\n/**\n * Pagination Object\n */\nexport interface Pagination {\n cursors: PaginationCursors;\n}\n\n/**\n * Flows List Response\n */\nexport interface FlowsListResponse {\n data: Flow[];\n paging: Pagination;\n}\n\n/**\n * Flow Asset\n */\nexport interface FlowAsset {\n name: string;\n asset_type: string;\n download_url: string;\n}\n\n/**\n * Flow Assets Response\n */\nexport interface FlowAssetsResponse {\n data: FlowAsset[];\n paging: Pagination;\n}\n\n/**\n * Flow Preview\n */\nexport interface FlowPreview {\n preview_url: string;\n expires_at: string;\n}\n\n/**\n * Flow Preview Response\n */\nexport interface FlowPreviewResponse {\n preview: FlowPreview;\n id: string;\n}\n\n/**\n * Flow Migration Result\n */\nexport interface FlowMigrationResult {\n source_name: string;\n source_id: string;\n migrated_id: string;\n}\n\n/**\n * Flow Migration Failure\n */\nexport interface FlowMigrationFailure {\n source_name: string;\n error_code: string;\n error_message: string;\n}\n\n/**\n * Create Flow Response\n */\nexport interface CreateFlowResponse {\n id: string;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Update Flow Response\n */\nexport interface UpdateFlowResponse {\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Flow Migration Response\n */\nexport interface FlowMigrationResponse {\n migrated_flows: FlowMigrationResult[];\n failed_flows: FlowMigrationFailure[];\n}\n\n/**\n * Validate Flow JSON Response\n */\nexport interface ValidateFlowJsonResponse {\n valid: boolean;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * WhatsApp Flow Endpoint - Encrypted Request Payload\n * Represents the raw encrypted data received from WhatsApp\n */\nexport interface FlowEncryptedRequestPayload {\n encrypted_aes_key: string;\n encrypted_flow_data: string;\n initial_vector: string;\n}\n\n/**\n * WhatsApp Flow Endpoint - Decrypted Request Response\n * Represents the successfully decrypted data and encryption keys\n */\nexport interface FlowDecryptedRequestResponse {\n decryptedBody: any;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n}\n\n/**\n * WhatsApp Flow Endpoint - HTTP Request with Body\n * Represents an HTTP request with the encrypted payload\n */\nexport interface FlowHttpRequest extends IncomingMessage {\n body: FlowEncryptedRequestPayload;\n headers: IncomingHttpHeaders;\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Request\n * Represents the structure of a health check request\n */\nexport interface FlowHealthCheckRequest {\n action: 'ping';\n version: '3.0';\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Response\n * The expected response structure for health check requests\n */\nexport interface FlowHealthCheckResponse {\n data: {\n status: 'active';\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Request\n * Represents the structure of a data exchange request\n */\nexport interface FlowDataExchangeRequest {\n version: '3.0';\n action: FlowActionEnum;\n screen: string;\n flow_token: string;\n data?: Record<string, any> & { error_message?: string };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Response\n * The expected response structure for data exchange requests\n */\nexport interface FlowDataExchangeResponse {\n screen?: string;\n data?: Record<string, any | { error_message?: string }>;\n}\n\n/**\n * WhatsApp Flow Endpoint - Success Screen Response\n * The expected response structure for success screen requests\n */\nexport interface FlowSuccessScreenResponse {\n screen: 'SUCCESS';\n data: {\n extension_message_response?: {\n params?: {\n flow_token: string;\n [key: string]: string;\n };\n };\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Request\n * Represents the structure of an error notification request\n */\nexport interface FlowErrorNotificationRequest {\n version: '3.0';\n action: Exclude<FlowActionEnum, FlowActionEnum.BACK>;\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Response\n * The expected response structure for error notification requests\n */\nexport interface FlowErrorNotificationResponse {\n acknowledged: boolean;\n}\n\n/**\n * WhatsApp Flow Endpoint - Comprehensive Request Object\n * A combined type that includes all possible fields from different request types\n * with all fields being optional for flexibility\n */\nexport interface FlowEndpointRequest {\n // Common fields\n version?: '3.0';\n action?: 'ping' | FlowActionEnum;\n\n screen?: string;\n flow_token?: string;\n\n data?: Record<string, any> & {\n error_key?: string;\n error_message?: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Response\n * Union type for all possible response types from a Flow endpoint\n */\nexport type FlowEndpointResponse =\n | FlowHealthCheckResponse\n | FlowDataExchangeResponse\n | FlowErrorNotificationResponse\n | FlowSuccessScreenResponse;\n\nexport interface FlowClass {\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n listFlows(wabaId: string): Promise<FlowsListResponse>;\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID\n */\n createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string;\n publish?: boolean;\n },\n ): Promise<CreateFlowResponse>;\n\n /**\n * Get Flow\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details\n */\n getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<Flow | FlowPreviewResponse>;\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update\n * @returns Promise with the success status\n */\n updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess>;\n\n /**\n * Delete Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deleteFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * List Assets (Get Flow JSON URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n listAssets(flowId: string): Promise<FlowAssetsResponse>;\n\n /**\n * Update Flow JSON\n *\n * @param flowId - The flow ID\n * @param data - The asset data including asset_type, file, and name\n * @returns Promise with the success status and validation errors\n */\n updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object;\n name?: string;\n },\n ): Promise<UpdateFlowResponse>;\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse>;\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n publishFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deprecateFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Migrate Flows\n *\n * @param wabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results\n */\n migrateFlows(\n wabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<FlowMigrationResponse>;\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as media from './types';\n\n/**\n * API for managing WhatsApp Media.\n *\n * This API allows you to:\n * - Get media information by ID\n * - Upload media files\n * - Delete media files\n * - Download media files from URLs\n */\nexport default class MediaApi extends BaseAPI implements media.MediaClass {\n private readonly endpoint = 'media';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve media information by media ID.\n *\n * @param mediaId The media ID to retrieve information for\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Media information including URL, mime type, file size, etc.\n *\n * @example\n * const mediaInfo = await whatsappClient.media.getMediaById('media_id_123');\n */\n async getMediaById(mediaId: string, phone_number_id?: string): Promise<media.MediaResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Upload a media file to WhatsApp.\n *\n * @param file The file to upload\n * @param messagingProduct The messaging product (default: 'whatsapp')\n * @returns Upload response containing the media ID\n *\n * @example\n * const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' });\n * const result = await whatsappClient.media.uploadMedia(file);\n */\n async uploadMedia(file: File, messagingProduct: string = 'whatsapp'): Promise<media.UploadMediaResponse> {\n const formData = new FormData();\n formData.append('file', file);\n formData.append('messaging_product', messagingProduct);\n formData.append('type', file.type);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Delete a media file.\n *\n * @param mediaId The media ID to delete\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.media.deleteMedia('media_id_123');\n */\n async deleteMedia(mediaId: string, phone_number_id?: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Download media from a URL.\n *\n * @param mediaUrl The URL to download media from\n * @returns Blob containing the media data\n *\n * @example\n * const blob = await whatsappClient.media.downloadMedia('https://...');\n */\n async downloadMedia(mediaUrl: string): Promise<Blob> {\n return this.sendJson(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport {\n type ComponentTypesEnum,\n HttpMethodsEnum,\n type InteractiveTypesEnum,\n MessageTypesEnum,\n WabaConfigEnum,\n} from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\n\nimport type * as m from './types';\n\n/**\n * Maps each message type to its appropriate payload type\n */\nexport type MessagePayloadType<T extends MessageTypesEnum> = T extends MessageTypesEnum.Audio\n ? m.AudioMediaObject\n : T extends MessageTypesEnum.Contacts\n ? [m.ContactObject]\n : T extends MessageTypesEnum.Document\n ? m.DocumentMediaObject\n : T extends MessageTypesEnum.Image\n ? m.ImageMediaObject\n : T extends MessageTypesEnum.Interactive\n ? m.InteractiveObject\n : T extends MessageTypesEnum.Location\n ? m.LocationObject\n : T extends MessageTypesEnum.Template\n ? m.MessageTemplateObject<ComponentTypesEnum>\n : T extends MessageTypesEnum.Sticker\n ? m.StickerMediaObject\n : T extends MessageTypesEnum.Text\n ? m.TextObject\n : T extends MessageTypesEnum.Video\n ? m.VideoMediaObject\n : T extends MessageTypesEnum.Reaction\n ? { message_id: string; emoji: string }\n : never;\n\nexport default class MessagesApi extends BaseAPI implements m.MessagesClass {\n private readonly commonMethod = HttpMethodsEnum.Post;\n private readonly commonEndpoint = 'messages';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Builds the request body for WhatsApp API messages\n * @param type The type of message to send\n * @param payload The message payload object\n * @param to The recipient's phone number\n * @param replyMessageId Optional message ID to reply to\n * @returns The formatted request body\n */\n bodyBuilder<T extends MessageTypesEnum>(\n type: T,\n payload: MessagePayloadType<T>,\n to: string,\n replyMessageId?: string,\n ) {\n const body: m.MessageRequestBody<T> = {\n messaging_product: 'whatsapp',\n recipient_type: 'individual',\n to,\n type,\n [type]: payload,\n };\n\n if (replyMessageId) body['context'] = { message_id: replyMessageId };\n\n return body;\n }\n\n /**\n * Sends a request to the WhatsApp API\n * @param body The request body to send\n * @returns Promise with the API response\n */\n private send(body: BodyInit | null): Promise<m.MessagesResponse> {\n return this.sendJson(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.commonEndpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n /**\n * Sends an audio message via WhatsApp\n * @param params The audio message parameter object\n * @returns Promise with the message response\n */\n async audio(params: m.MessageRequestParams<m.AudioMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Audio, body, to, replyMessageId)));\n }\n\n /**\n * Sends a contact card via WhatsApp\n * @param params The contact message parameter object\n * @returns Promise with the message response\n */\n async contacts(params: m.MessageRequestParams<[m.ContactObject]>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Contacts, body, to, replyMessageId)));\n }\n\n /**\n * Sends a document via WhatsApp\n * @param params The document message parameter object\n * @returns Promise with the message response\n */\n async document(params: m.MessageRequestParams<m.DocumentMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Document, body, to, replyMessageId)));\n }\n\n /**\n * Sends an image via WhatsApp\n * @param params The image message parameter object\n * @returns Promise with the message response\n */\n async image(params: m.MessageRequestParams<m.ImageMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Image, body, to, replyMessageId)));\n }\n\n /**\n * Sends an interactive message via WhatsApp\n * @param params The interactive message parameter object\n * @returns Promise with the message response\n */\n async interactive(params: m.MessageRequestParams<m.InteractiveObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId)));\n }\n\n /**\n * Sends a location via WhatsApp\n * @param params The location message parameter object\n * @returns Promise with the message response\n */\n async location(params: m.MessageRequestParams<m.LocationObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Location, body, to, replyMessageId)));\n }\n\n /**\n * Sends a sticker via WhatsApp\n * @param params The sticker message parameter object\n * @returns Promise with the message response\n */\n async sticker(params: m.MessageRequestParams<m.StickerMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Sticker, body, to, replyMessageId)));\n }\n\n /**\n * Sends a template message via WhatsApp\n * @param params The template message parameter object\n * @returns Promise with the message response\n */\n async template(\n params: m.MessageRequestParams<m.MessageTemplateObject<ComponentTypesEnum>>,\n ): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Template, body, to, replyMessageId)));\n }\n\n /**\n * Sends a text message via WhatsApp\n * @param params The text message parameter object\n * @returns Promise with the message response\n */\n async text(params: m.TextMessageParams): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, previewUrl } = params;\n\n // Handle both string and TextObject types\n const textPayload: m.TextObject =\n typeof body === 'string'\n ? { body, preview_url: previewUrl ?? true }\n : { ...body, preview_url: previewUrl ?? body.preview_url ?? true };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Text, textPayload, to, replyMessageId)));\n }\n\n /**\n * Sends a video message via WhatsApp\n * @param params The video message parameter object\n * @returns Promise with the message response\n */\n async video(params: m.MessageRequestParams<m.VideoMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Video, body, to, replyMessageId)));\n }\n\n /**\n * Updates message status (mark as read, etc.)\n * @param params The status update parameters\n * @returns Promise with the API response\n */\n async status(params: m.StatusParams): Promise<m.MessagesResponse> {\n const body = {\n messaging_product: 'whatsapp',\n status: params.status,\n message_id: params.messageId,\n ...(params.typingIndicator && { typing_indicator: params.typingIndicator }),\n };\n\n return this.send(JSON.stringify(body));\n }\n\n /**\n * Marks a message as read\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async markAsRead(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n });\n }\n\n /**\n * Shows typing indicator\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async showTypingIndicator(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n typingIndicator: { type: 'text' },\n });\n }\n\n /**\n * Sends a list interactive message\n * @param params The list interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveList(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a CTA URL interactive message\n * @param params The CTA URL interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveCtaUrl(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a location request interactive message\n * @param params The location request interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveLocationRequest(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.LocationRequest }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends an address message interactive message\n * @param params The address message interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveAddressMessage(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.AddressMessage }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reply buttons interactive message\n * @param params The reply buttons interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveReplyButtons(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a flow interactive message\n * @param params The flow interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveFlow(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reaction to a message\n * @param params The reaction parameters\n * @returns Promise with the message response\n */\n async reaction(params: m.ReactionParams): Promise<m.MessagesResponse> {\n const reactionPayload = {\n message_id: params.messageId,\n emoji: params.emoji,\n };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Reaction, reactionPayload, params.to)));\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as phoneNumber from './types';\n\n/**\n * API for managing WhatsApp Phone Numb ers.\n *\n * This API allows you to:\n * - Get phone number information by ID\n * - Get all phone numbers for a business account\n * - Request verification codes for phone numbers\n * - Verify phone numbers with codes\n */\nexport default class PhoneNumberApi extends BaseAPI implements phoneNumber.PhoneNumberClass {\n private readonly endpoint = 'phone_numbers';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get phone number information by ID.\n *\n * @param fields Optional comma-separated list of fields to include in the response\n * @returns Phone number information including verification status, quality rating, etc.\n *\n * @example\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById();\n * const phoneNumberWithFields = await whatsappClient.phoneNumber.getPhoneNumberById('display_phone_number,verified_name');\n */\n async getPhoneNumberById(fields?: string): Promise<phoneNumber.PhoneNumberResponse> {\n const queryParams = fields ? objectToQueryString({ fields }) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all phone numbers for the business account.\n *\n * @returns List of phone numbers associated with the business account\n *\n * @example\n * const phoneNumbers = await whatsappClient.phoneNumber.getPhoneNumbers();\n */\n async getPhoneNumbers(): Promise<phoneNumber.PhoneNumbersResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Request a verification code for the phone number.\n *\n * @param request Verification code request containing method and language\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.requestVerificationCode({\n * code_method: 'SMS',\n * language: 'en_US'\n * });\n */\n async requestVerificationCode(request: phoneNumber.RequestVerificationCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/request_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Verify the phone number with the received code.\n *\n * @param request Verification request containing the code\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.verifyCode({\n * code: '123456'\n * });\n */\n async verifyCode(request: phoneNumber.VerifyCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/verify_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Configure conversational automation features (Welcome Messages, Ice Breakers, Commands).\n *\n * @param request Configuration for conversational components\n * @returns Response indicating success or failure\n *\n * @example\n * // Enable welcome message\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true\n * });\n *\n * @example\n * // Configure commands\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * commands: [\n * { command_name: 'tickets', command_description: 'Book flight tickets' },\n * { command_name: 'hotel', command_description: 'Book hotel' }\n * ]\n * });\n *\n * @example\n * // Configure ice breakers (prompts)\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * prompts: ['Book a flight', 'Plan a vacation']\n * });\n *\n * @example\n * // Configure all features\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true,\n * commands: [\n * { command_name: 'tickets', command_description: 'Book flight tickets' }\n * ],\n * prompts: ['Book a flight']\n * });\n */\n async setConversationalAutomation(request: phoneNumber.ConversationalAutomationRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/conversational_automation`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Get the current configuration of conversational automation features.\n *\n * @returns Current configuration including welcome message status, commands, and prompts\n *\n * @example\n * const config = await whatsappClient.phoneNumber.getConversationalAutomation();\n * console.log(config.enable_welcome_message); // true/false\n * console.log(config.commands); // Array of commands\n * console.log(config.prompts); // Array of ice breakers\n */\n async getConversationalAutomation(): Promise<phoneNumber.ConversationalAutomationResponse> {\n const queryParams = objectToQueryString({ fields: 'conversational_automation' });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get the current throughput level for the phone number.\n *\n * Throughput represents the maximum messages per second (mps) that can be sent/received.\n * - Default: 80 mps\n * - Automatic upgrade to 1,000 mps available for eligible numbers\n * - WhatsApp Business app coexistence numbers: fixed at 5 mps\n *\n * @returns Current throughput information including the level (STANDARD, HIGH, or NOT_APPLICABLE)\n *\n * @example\n * const throughput = await whatsappClient.phoneNumber.getThroughput();\n * console.log(throughput.throughput.level); // 'STANDARD' | 'HIGH' | 'NOT_APPLICABLE'\n */\n async getThroughput(): Promise<phoneNumber.ThroughputResponse> {\n const queryParams = objectToQueryString({ fields: 'throughput' });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","export function buildFieldsQueryString(fields?: string[] | string): string {\n if (!fields) return '';\n\n let fieldParams = '';\n\n if (Array.isArray(fields)) {\n fieldParams = fields.join(',');\n } else if (typeof fields === 'string') {\n fieldParams = fields;\n } else {\n fieldParams = Object.entries(fields)\n .filter(([_, value]) => value)\n .map(([key]) => key)\n .join(',');\n }\n\n return fieldParams ? `?fields=${fieldParams}` : '';\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as bp from './types';\n\n/**\n * API for managing WhatsApp Business Profiles and profile pictures.\n *\n * This API allows you to:\n * - Get business profile information\n * - Update business profile details\n * - Upload profile pictures using a three-step process:\n * 1. Create an upload session\n * 2. Upload the image binary data\n * 3. Get the upload handle to use when updating the profile\n */\nexport default class BusinessProfileApi extends BaseAPI implements bp.BusinessProfileClass {\n private readonly endpoint = 'whatsapp_business_profile';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get your business profile information.\n *\n * Use this method to retrieve details about your WhatsApp business profile, including\n * about text, address, description, email, profile picture URL, websites, and vertical.\n *\n * @param fields Fields to be returned in the response. If not specified, all fields will be returned.\n * Possible values: about, address, description, email, profile_picture_url, websites, vertical\n * @returns The business profile information.\n *\n * @example\n * // Get all business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile();\n *\n * // Get specific business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile('about,address,email');\n *\n * // Using the BusinessProfileFieldsParam type\n * const profile = await whatsappClient.businessProfile.getBusinessProfile(['about', 'address', 'email']);\n */\n async getBusinessProfile(fields?: bp.BusinessProfileFieldsParam): Promise<bp.BusinessProfileResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${buildFieldsQueryString(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update your business profile.\n *\n * Use this method to update one or more fields of your WhatsApp business profile.\n *\n * @param updateRequest The request object containing the fields to update.\n * - messaging_product: Required. Always set to \"whatsapp\".\n * - about: Optional. Business's About text (1-139 characters).\n * - address: Optional. Business address (max 256 characters).\n * - description: Optional. Business description (max 512 characters).\n * - vertical: Optional. Business category (use BusinessVerticalEnum for type safety).\n * - email: Optional. Contact email (valid format, max 128 characters).\n * - websites: Optional. Up to 2 URLs (max 256 characters each).\n * - profile_picture_handle: Optional. Handle from upload process.\n * @returns Response indicating success or failure.\n *\n * @example\n * // Update business profile with multiple fields including vertical using enum\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * about: 'We provide excellent service',\n * email: 'contact@example.com',\n * websites: ['https://example.com'],\n * vertical: BusinessVerticalEnum.RETAIL\n * });\n */\n async updateBusinessProfile(updateRequest: bp.UpdateBusinessProfileRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(updateRequest),\n );\n }\n\n /**\n * Create an upload session for a profile picture.\n *\n * This is the first step in the profile picture upload process.\n *\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file with extension.\n * @returns Response containing the upload session ID needed for the next step.\n *\n * @example\n * // Create upload session for profile picture\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length,\n * 'image/jpeg',\n * 'profile.jpg'\n * );\n * const uploadSessionId = session.upload_session_id;\n */\n async createUploadSession(\n fileLength: number,\n fileType: string,\n fileName: string,\n ): Promise<bp.UploadSessionResponse> {\n const queryParams = objectToQueryString({\n file_length: fileLength,\n file_type: fileType,\n file_name: fileName,\n });\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `app/uploads/${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Upload media file to the upload session.\n *\n * This is the second step in the profile picture upload process.\n * Upload the binary content of the file to the previously created upload session.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @param file The binary data of the file (Buffer).\n * @returns Response indicating success or failure.\n *\n * @example\n * // Upload the actual file content\n * await whatsappClient.businessProfile.uploadMedia(\n * uploadSessionId,\n * fileBuffer\n * );\n */\n async uploadMedia(uploadId: string, file: Buffer): Promise<bp.UploadBusinessProfileResponse> {\n return this.sendJson(HttpMethodsEnum.Post, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], file);\n }\n\n /**\n * Get the upload handle information.\n *\n * This is the third step in the profile picture upload process.\n * After uploading the file, get the handle to use when updating the profile.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @returns Response containing the upload handle information.\n *\n * @example\n * // Complete profile picture update process\n * // 1. Create upload session\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length, 'image/jpeg', 'profile.jpg'\n * );\n *\n * // 2. Upload the image data\n * await whatsappClient.businessProfile.uploadMedia(\n * session.upload_session_id, fileBuffer\n * );\n *\n * // 3. Get the handle for the uploaded file\n * const handleInfo = await whatsappClient.businessProfile.getUploadHandle(\n * session.upload_session_id\n * );\n *\n * // 4. Update profile with new picture and business information\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * profile_picture_handle: handleInfo.handle,\n * vertical: BusinessVerticalEnum.RESTAURANT,\n * about: 'Delicious food served daily'\n * });\n */\n async getUploadHandle(uploadId: string): Promise<bp.UploadHandle> {\n return this.sendJson(HttpMethodsEnum.Get, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../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","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as registration from './types';\n\n/**\n * API for managing WhatsApp Business Account registration.\n *\n * This API allows you to:\n * - Register a WhatsApp Business Account with a PIN\n * - Deregister a WhatsApp Business Account\n */\nexport default class RegistrationApi extends BaseAPI implements registration.RegistrationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Register a WhatsApp Business Account using a PIN.\n *\n * @param pin The registration PIN received via SMS or voice call\n * @param dataLocalizationRegion Optional data localization region\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.register('123456', DataLocalizationRegionEnum.Asia);\n */\n async register(pin: string, dataLocalizationRegion?: DataLocalizationRegionEnum): Promise<ResponseSuccess> {\n const body: registration.RegistrationRequest = {\n messaging_product: 'whatsapp',\n pin,\n ...(dataLocalizationRegion && { data_localization_region: dataLocalizationRegion }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/register`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Deregister a WhatsApp Business Account.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.deregister();\n */\n async deregister(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/deregister`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponsePagination, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../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","import { CategoryEnum } from '../../../types/enums';\nimport type {\n ComponentTypes,\n MediaCarouselCard,\n ProductCarouselCard,\n TemplateBody,\n TemplateButton,\n TemplateButtons,\n TemplateFooter,\n TemplateHeader,\n TemplateRequestBody,\n} from '../types';\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';\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,\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 });\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' }],\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 ],\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 ],\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 ],\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 });\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: MediaCarouselCard[] = [];\n options.cards.forEach((card, index) => {\n const cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[] = [];\n\n // Add header (media)\n cardComponents.push({\n type: 'HEADER' as const,\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) as TemplateButtons[]));\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 });\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 ],\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: ProductCarouselCard[] = options.cards.map((card, index) => ({\n card_index: index,\n components: [\n {\n type: 'HEADER' as const,\n format: 'PRODUCT' as const,\n example: {\n header_handle: [card.product_retailer_id],\n },\n },\n ],\n }));\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n });\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 ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as twoStepVerification from './types';\n\n/**\n * API for managing WhatsApp Two-Step Verification.\n *\n * This API allows you to:\n * - Set a two-step verification PIN code\n * - Manage two-step verification settings\n */\nexport default class TwoStepVerificationApi extends BaseAPI implements twoStepVerification.TwoStepVerificationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Set a two-step verification PIN code.\n *\n * @param pin The PIN code to set for two-step verification (6-digit numeric string)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.twoStepVerification.setTwoStepVerificationCode('123456');\n */\n async setTwoStepVerificationCode(pin: string): Promise<ResponseSuccess> {\n const body = {\n pin,\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\n\nimport type * as waba from './types';\n\n/**\n * API for managing WhatsApp Business Account (WABA).\n *\n * This API allows you to:\n * - Get WABA account information\n * - Manage WABA subscriptions\n * - Subscribe/unsubscribe from WABA webhooks\n * - Update subscription settings\n */\nexport default class WabaApi extends BaseAPI implements waba.WABAClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve WhatsApp Business Account information.\n *\n * @param fields Optional array of specific fields to retrieve\n * @returns WABA account information including status, health, verification status, etc.\n *\n * @example\n * const account = await whatsappClient.waba.getWabaAccount(['id', 'name', 'status']);\n */\n async getWabaAccount(fields?: waba.WabaAccountFieldsParam): Promise<waba.WabaAccount> {\n const queryString = buildFieldsQueryString(fields)?.replace(/,/g, '%2C');\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all WABA subscriptions for the business account.\n *\n * @returns List of all subscribed apps and their configurations\n *\n * @example\n * const subscriptions = await whatsappClient.waba.getAllWabaSubscriptions();\n */\n async getAllWabaSubscriptions(): Promise<waba.WabaSubscriptions> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update WABA subscription configuration.\n *\n * @param params Configuration parameters including callback URI and verify token\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.updateWabaSubscription({\n * override_callback_uri: 'https://example.com/webhook',\n * verify_token: 'your_verify_token'\n * });\n */\n async updateWabaSubscription({\n override_callback_uri,\n verify_token,\n }: waba.UpdateWabaSubscription): Promise<ResponseSuccess> {\n const body = {\n override_callback_uri,\n verify_token,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unsubscribe from WABA webhooks.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.unsubscribeFromWaba();\n */\n async unsubscribeFromWaba(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","export function printLogo() {\n // 테스트 환경에서는 로고를 출력하지 않음\n if (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n (typeof global !== 'undefined' && (global as any).__VITEST__)\n ) {\n return;\n }\n\n console.log(\n '\\x1b[36m%s\\x1b[0m',\n `\n██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗\n██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║\n╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║\n ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n`,\n );\n}\n","import { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport { generateEncryption, EncryptionKeyPair } from '../../utils/flowEncryptionUtils';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nimport {\n BlockUsersApi,\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MediaApi,\n MessageApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { printLogo } from '../../utils/logoConsole';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WhatsApp SDK Main Class following official patterns\n * Provides unified access to WhatsApp Cloud API and Flows API\n */\nexport default class WhatsApp {\n config: WabaConfigType;\n requester: Readonly<Requester>;\n blockUsers: BlockUsersApi;\n messages: MessageApi;\n media: MediaApi;\n phoneNumbers: PhoneNumberApi;\n twoStepVerification: TwoStepVerificationApi;\n flows: FlowApi;\n businessProfile: BusinessProfileApi;\n templates: TemplateApi;\n encryption: EncryptionApi;\n qrCode: QrCodeApi;\n registration: RegistrationApi;\n waba: WabaApi;\n\n constructor(config?: WhatsAppConfig) {\n printLogo();\n this.config = importConfig(config);\n\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.getUserAgent(),\n );\n\n this.blockUsers = new BlockUsersApi(this.config, this.requester);\n this.messages = new MessageApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.flows = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n\n LOGGER.log('\\n' + formatConfigTable(this.config));\n }\n\n /**\n * Runtime configuration updates following official patterns\n */\n updateTimeout(timeout: number): void {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = timeout;\n if ('updateTimeout' in this.requester) {\n (this.requester as any).updateTimeout(timeout);\n }\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateSenderNumberId(phoneNumberId: number): void {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Sender number ID updated to ${phoneNumberId}`);\n }\n\n updateAccessToken(accessToken: string): void {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n if ('updateAccessToken' in this.requester) {\n (this.requester as any).updateAccessToken(accessToken);\n }\n LOGGER.log('Access token updated');\n }\n\n /**\n * Get SDK version\n */\n version(): string {\n return getVersion();\n }\n\n /**\n * Static enums access\n */\n static get Enums() {\n return SDKEnums;\n }\n\n /**\n * Get User-Agent string\n */\n getUserAgent(): string {\n return getUserAgent();\n }\n\n /**\n * Generate RSA encryption key pair for WhatsApp Business Flow API\n *\n * This method generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Optional passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from config\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n *\n * @example\n * ```typescript\n * const wa = new WhatsApp();\n *\n * // Uses FLOW_API_PASSPHRASE from environment/config\n * const keys = wa.generateEncryption();\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n *\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n * ```\n */\n generateEncryption(passphrase?: string): EncryptionKeyPair {\n // If no passphrase provided, try to use from config\n const effectivePassphrase = passphrase || this.config[SDKEnums.WabaConfigEnum.Passphrase];\n return generateEncryption(effectivePassphrase);\n }\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '../api/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 crypto from 'crypto';\n\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { decryptFlowRequest, encryptFlowResponse } from '../../../utils/flowEncryptionUtils';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport WhatsApp from '../../whatsapp/WhatsApp';\nimport { MessageWebhookValue, StatusWebhook, StatusWebhookValue, WebhookValue, WhatsAppMessage } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Processed message with metadata for handlers\n */\nexport type ProcessedMessage = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n profileName: string;\n message: WhatsAppMessage;\n /**\n * The message ID extracted from the appropriate location based on message type.\n * For most messages, this comes from message.id\n * For certain types like nfm_reply, this comes from message.context.id\n */\n messageId: string;\n};\n\n/**\n * Processed status with metadata for handlers\n */\nexport type ProcessedStatus = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n status: StatusWebhook;\n};\n\n// Type-specific processed messages for specialized handlers\nexport type TextProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Text }>;\n};\n\nexport type ImageProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Image }>;\n};\n\nexport type VideoProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Video }>;\n};\n\nexport type AudioProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Audio }>;\n};\n\nexport type DocumentProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Document }>;\n};\n\nexport type StickerProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Sticker }>;\n};\n\nexport type InteractiveProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Interactive }>;\n};\n\nexport type ButtonProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Button }>;\n};\n\nexport type LocationProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Location }>;\n};\n\nexport type ContactsProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Contacts }>;\n};\n\nexport type ReactionProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Reaction }>;\n};\n\nexport type OrderProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Order }>;\n};\n\nexport type SystemProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.System }>;\n};\n\nexport type MessageHandler = (whatsapp: WhatsApp, processed: ProcessedMessage) => void | Promise<void>;\nexport type StatusHandler = (whatsapp: WhatsApp, processed: ProcessedStatus) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n// Type-specific handlers for specialized methods\nexport type TextMessageHandler = (whatsapp: WhatsApp, processed: TextProcessedMessage) => void | Promise<void>;\nexport type ImageMessageHandler = (whatsapp: WhatsApp, processed: ImageProcessedMessage) => void | Promise<void>;\nexport type VideoMessageHandler = (whatsapp: WhatsApp, processed: VideoProcessedMessage) => void | Promise<void>;\nexport type AudioMessageHandler = (whatsapp: WhatsApp, processed: AudioProcessedMessage) => void | Promise<void>;\nexport type DocumentMessageHandler = (whatsapp: WhatsApp, processed: DocumentProcessedMessage) => void | Promise<void>;\nexport type StickerMessageHandler = (whatsapp: WhatsApp, processed: StickerProcessedMessage) => void | Promise<void>;\nexport type InteractiveMessageHandler = (\n whatsapp: WhatsApp,\n processed: InteractiveProcessedMessage,\n) => void | Promise<void>;\nexport type ButtonMessageHandler = (whatsapp: WhatsApp, processed: ButtonProcessedMessage) => void | Promise<void>;\nexport type LocationMessageHandler = (whatsapp: WhatsApp, processed: LocationProcessedMessage) => void | Promise<void>;\nexport type ContactsMessageHandler = (whatsapp: WhatsApp, processed: ContactsProcessedMessage) => void | Promise<void>;\nexport type ReactionMessageHandler = (whatsapp: WhatsApp, processed: ReactionProcessedMessage) => void | Promise<void>;\nexport type OrderMessageHandler = (whatsapp: WhatsApp, processed: OrderProcessedMessage) => void | Promise<void>;\nexport type SystemMessageHandler = (whatsapp: WhatsApp, processed: SystemProcessedMessage) => void | Promise<void>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n statusHandler?: StatusHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n const body = await request.json();\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.warn(errorMsg);\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Create a standard ping response for WhatsApp Flow health checks\n * @returns Flow ping response object\n */\nexport function createFlowPingResponse() {\n return {\n version: '3.0',\n data: { status: 'active' },\n };\n}\n\n/**\n * Create a standard error response for WhatsApp Flow error notifications\n * @returns Acknowledgement response for error notification\n */\nexport function createFlowErrorResponse() {\n return {\n data: {\n acknowledged: true,\n },\n };\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature');\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n\n // Decrypt the request and get decrypted AES key and IV\n const { decryptedBody, aesKeyBuffer, initialVectorBuffer } = decryptFlowRequest(data, config);\n\n // Determine flow type\n const isPing = isFlowPingRequest(decryptedBody);\n const isError = isFlowErrorRequest(decryptedBody);\n const isDataExchange = isFlowDataExchangeRequest(decryptedBody);\n\n let flowType: FlowTypeEnum;\n if (isPing) {\n flowType = FlowTypeEnum.Ping;\n } else if (isError) {\n flowType = FlowTypeEnum.Error;\n } else if (isDataExchange) {\n flowType = FlowTypeEnum.Change;\n } else {\n flowType = FlowTypeEnum.All;\n }\n\n // Get the flow handler based on type\n let handler = flowHandlers.get(flowType);\n\n // For Ping and Error, use default handlers if not registered\n if (!handler) {\n if (flowType === FlowTypeEnum.Ping) {\n handler = () => createFlowPingResponse();\n } else if (flowType === FlowTypeEnum.Error) {\n handler = () => createFlowErrorResponse();\n } else {\n // For Change and other types, try All handler as fallback\n handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow type:', { flowType, action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n }\n }\n\n // Call the user's handler for the flow type\n const result = await handler(whatsapp, decryptedBody);\n\n // Return response based on flow type\n if (isError) {\n LOGGER.warn('Flow error notification received', { error: decryptedBody.data });\n\n // If user handler didn't return a response, use default acknowledgement\n const errorResponse = result || createFlowErrorResponse();\n\n return new Response(JSON.stringify(errorResponse), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Both ping and data_exchange responses need to be encrypted\n if (isPing || isDataExchange) {\n // Encrypt the response using decrypted AES key and IV\n const encryptedResponse = encryptFlowResponse(result, aesKeyBuffer, initialVectorBuffer);\n\n // Meta expects the encrypted response as a plain base64 string (not wrapped in JSON)\n return new Response(encryptedResponse, {\n status: 200,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Extract message ID based on message type\n * Some message types (like nfm_reply) have ID in context instead of root level\n */\nfunction extractMessageId(message: WhatsAppMessage): string {\n // If message has id at root level, use it\n if (message.id) {\n return message.id;\n }\n\n // For interactive and button messages, check context.id\n if (message.type === MessageTypesEnum.Interactive || message.type === MessageTypesEnum.Button) {\n const msgWithContext = message as any;\n if (msgWithContext.context?.id) {\n return msgWithContext.context.id;\n }\n }\n\n // Fallback to empty string if no ID found\n return '';\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n statusHandler?: StatusHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n\n // Handle status webhooks\n if ('statuses' in value && value.statuses) {\n const statusValue = value as StatusWebhookValue;\n for (const status of statusValue.statuses) {\n const processed: ProcessedStatus = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n status,\n };\n\n await executeStatusHandler(handlers.statusHandler, whatsapp, processed);\n }\n return;\n }\n\n // Handle message webhooks\n if ('messages' in value && value.messages) {\n const messageValue = value as MessageWebhookValue;\n const profileName = messageValue.contacts?.[0]?.profile?.name || '';\n\n for (const message of messageValue.messages) {\n const processed: ProcessedMessage = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n message,\n messageId: extractMessageId(message),\n };\n\n const messageType = message.type;\n\n // Execute handlers in sequence\n await executeMessageHandler(handlers.preProcessHandler, whatsapp, processed, 'pre-process');\n await executeMessageHandler(handlers.messageHandlers.get(messageType), whatsapp, processed, messageType);\n await executeMessageHandler(handlers.postProcessHandler, whatsapp, processed, 'post-process');\n }\n }\n}\n\nasync function executeMessageHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed);\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: processed.messageId });\n }\n }\n}\n\nasync function executeStatusHandler(\n handler: StatusHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedStatus,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed);\n } catch (error) {\n LOGGER.error('Error in status handler:', { error, statusId: processed.status.id });\n }\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\n\nimport {\n AudioMessageHandler,\n ButtonMessageHandler,\n ContactsMessageHandler,\n DocumentMessageHandler,\n FlowHandler,\n ImageMessageHandler,\n InteractiveMessageHandler,\n LocationMessageHandler,\n MessageHandler,\n OrderMessageHandler,\n ReactionMessageHandler,\n StatusHandler,\n StickerMessageHandler,\n SystemMessageHandler,\n TextMessageHandler,\n VideoMessageHandler,\n processFlowRequest,\n processWebhookMessages,\n} from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private statusHandler: StatusHandler | undefined = undefined;\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n statusHandler: this.statusHandler,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'text/plain';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n if (type === ('statuses' as MessageTypesEnum)) {\n throw new Error(\n 'MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)',\n );\n }\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onStatus(handler: StatusHandler): void {\n this.statusHandler = handler;\n LOGGER.log('Registered status handler');\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n // ============================================================================\n // Specialized type-safe message handlers\n // ============================================================================\n\n /**\n * Register a handler for text messages\n * @param handler Type-safe handler that receives text messages with guaranteed text field\n */\n onText(handler: TextMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Text, handler as MessageHandler);\n LOGGER.log('Registered text message handler');\n }\n\n /**\n * Register a handler for image messages\n * @param handler Type-safe handler that receives image messages with guaranteed image field\n */\n onImage(handler: ImageMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Image, handler as MessageHandler);\n LOGGER.log('Registered image message handler');\n }\n\n /**\n * Register a handler for video messages\n * @param handler Type-safe handler that receives video messages with guaranteed video field\n */\n onVideo(handler: VideoMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Video, handler as MessageHandler);\n LOGGER.log('Registered video message handler');\n }\n\n /**\n * Register a handler for audio messages\n * @param handler Type-safe handler that receives audio messages with guaranteed audio field\n */\n onAudio(handler: AudioMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Audio, handler as MessageHandler);\n LOGGER.log('Registered audio message handler');\n }\n\n /**\n * Register a handler for document messages\n * @param handler Type-safe handler that receives document messages with guaranteed document field\n */\n onDocument(handler: DocumentMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Document, handler as MessageHandler);\n LOGGER.log('Registered document message handler');\n }\n\n /**\n * Register a handler for sticker messages\n * @param handler Type-safe handler that receives sticker messages with guaranteed sticker field\n */\n onSticker(handler: StickerMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Sticker, handler as MessageHandler);\n LOGGER.log('Registered sticker message handler');\n }\n\n /**\n * Register a handler for interactive messages (buttons, lists, flows)\n * @param handler Type-safe handler that receives interactive messages with guaranteed interactive field\n */\n onInteractive(handler: InteractiveMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Interactive, handler as MessageHandler);\n LOGGER.log('Registered interactive message handler');\n }\n\n /**\n * Register a handler for button messages\n * @param handler Type-safe handler that receives button messages with guaranteed button field\n */\n onButton(handler: ButtonMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Button, handler as MessageHandler);\n LOGGER.log('Registered button message handler');\n }\n\n /**\n * Register a handler for location messages\n * @param handler Type-safe handler that receives location messages with guaranteed location field\n */\n onLocation(handler: LocationMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Location, handler as MessageHandler);\n LOGGER.log('Registered location message handler');\n }\n\n /**\n * Register a handler for contact messages\n * @param handler Type-safe handler that receives contact messages with guaranteed contacts field\n */\n onContacts(handler: ContactsMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Contacts, handler as MessageHandler);\n LOGGER.log('Registered contacts message handler');\n }\n\n /**\n * Register a handler for reaction messages\n * @param handler Type-safe handler that receives reaction messages with guaranteed reaction field\n */\n onReaction(handler: ReactionMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Reaction, handler as MessageHandler);\n LOGGER.log('Registered reaction message handler');\n }\n\n /**\n * Register a handler for order messages\n * @param handler Type-safe handler that receives order messages with guaranteed order field\n */\n onOrder(handler: OrderMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Order, handler as MessageHandler);\n LOGGER.log('Registered order message handler');\n }\n\n /**\n * Register a handler for system messages\n * @param handler Type-safe handler that receives system messages with guaranteed system field\n */\n onSystem(handler: SystemMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.System, handler as MessageHandler);\n LOGGER.log('Registered system message handler');\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n","import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Generic request/response interfaces for framework abstraction\nexport interface BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query?: Record<string, any> | URLSearchParams;\n rawBody?: any;\n}\n\nexport interface BaseResponse<T = any> {\n status(code: number): T;\n json?(data: any): T | void;\n send?(data?: any): T | void;\n setHeader?(name: string, value: string): void;\n}\n\n// Base configuration interface\nexport interface BaseWebhookConfig extends WhatsAppConfig {\n // Framework-specific configs can extend this\n}\n\n// Response result interface for consistent return types\nexport interface WebhookResult {\n status: number;\n headers: Record<string, string>;\n body: any;\n}\n\n/**\n * Abstract base class for framework-agnostic webhook handlers\n * Provides common architecture and functionality across all frameworks\n */\nexport abstract class BaseWebhookHandler<TRequest extends BaseRequest, TResponse extends BaseResponse> {\n protected processor: WebhookProcessor;\n\n constructor(config: BaseWebhookConfig) {\n this.processor = new WebhookProcessor(config);\n }\n\n /**\n * Abstract method for handling GET requests (webhook verification)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleGet(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling POST requests (webhook processing)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handlePost(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling flow requests\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleFlow(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Common webhook verification logic\n */\n protected async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResult> {\n return await this.processor.processVerification(mode, token, challenge);\n }\n\n /**\n * Common webhook processing logic\n */\n protected async processWebhook(request: Request): Promise<WebhookResult> {\n return await this.processor.processWebhook(request);\n }\n\n /**\n * Common flow processing logic\n */\n protected async processFlow(request: Request): Promise<WebhookResult> {\n return await this.processor.processFlow(request);\n }\n\n /**\n * Helper to construct full URL from headers and path\n */\n protected constructFullUrl(headers: Record<string, string | string[] | undefined>, url: string = ''): string {\n return constructFullUrl(headers, url);\n }\n\n /**\n * Helper to apply result headers to response\n */\n protected applyHeaders(result: WebhookResult, res: TResponse): void {\n if (res.setHeader) {\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader!(key, value);\n });\n }\n }\n\n /**\n * Auto-routing method handler that dispatches based on request method\n */\n protected async autoRoute(req: TRequest, res: TResponse, ...args: any[]): Promise<any> {\n const method = req.method?.toUpperCase();\n\n switch (method) {\n case 'GET':\n return await this.handleGet(req, res, ...args);\n case 'POST':\n return await this.handlePost(req, res, ...args);\n default:\n if (res.status && res.json) {\n return res.status(405).json({ error: 'Method Not Allowed' });\n }\n throw new Error('Method Not Allowed');\n }\n }\n\n /**\n * Get the processor instance for handler registration\n */\n get webhookProcessor(): WebhookProcessor {\n return this.processor;\n }\n\n /**\n * Abstract method to return the clean handler object\n * Each framework implements this to return their specific handler structure\n */\n abstract getHandlers(): {\n GET: (...args: any[]) => Promise<any>;\n POST: (...args: any[]) => Promise<any>;\n webhook: (...args: any[]) => Promise<any>;\n flow: (...args: any[]) => Promise<any>;\n processor: WebhookProcessor;\n };\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from '../handler';\nimport { WebhookResponse } from '../../WebhookProcessor';\n\n// Express-like interfaces to avoid direct Express dependency\nexport interface ExpressRequest extends BaseRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Record<string, any>;\n rawBody?: any;\n}\n\nexport interface ExpressResponse extends BaseResponse<ExpressResponse> {\n status(code: number): ExpressResponse;\n json(data: any): ExpressResponse;\n send(data?: any): ExpressResponse;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextFunction {\n (error?: any): void;\n}\n\nexport interface ExpressWebhookConfig extends BaseWebhookConfig {\n path?: string;\n}\n\n/**\n * Express-specific webhook handler extending the base handler\n */\nclass ExpressWebhookHandler extends BaseWebhookHandler<ExpressRequest, ExpressResponse> {\n constructor(config: ExpressWebhookConfig) {\n super(config);\n }\n\n protected async handleGet(req: ExpressRequest, res: ExpressResponse, next: NextFunction): Promise<WebhookResponse> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(error);\n throw error;\n }\n }\n\n protected async handlePost(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(error);\n throw error;\n }\n }\n\n protected async handleFlow(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody || (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(error);\n throw error;\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleGet(req, res, next),\n POST: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handlePost(req, res, next),\n\n // Auto-routing webhook handler\n webhook: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.autoRoute(req, res, next),\n\n // Flow handler\n flow: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleFlow(req, res, next),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\nexport function expressWebhookHandler(config: ExpressWebhookConfig) {\n const handler = new ExpressWebhookHandler(config);\n return handler.getHandlers();\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from '../handler';\nimport { WebhookResponse } from '../../WebhookProcessor';\n\n// Next.js specific interfaces\nexport interface BaseApiRequest extends BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Partial<Record<string, string | string[]>>;\n rawBody?: any;\n}\n\nexport interface BaseApiResponse extends BaseResponse {\n status(code: number): any;\n json(data: any): void | any;\n send(data?: any): void | any;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextJsWebhookConfig extends BaseWebhookConfig {\n // Next.js specific config can be added here\n}\n\n/**\n * Next.js Page Router webhook handler extending the base handler\n */\nclass NextJsWebhookHandler<\n TRequest extends BaseApiRequest,\n TResponse extends BaseApiResponse,\n> extends BaseWebhookHandler<TRequest, TResponse> {\n constructor(config: NextJsWebhookConfig) {\n super(config);\n }\n\n // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest, preserveRaw: boolean = false): Promise<void> {\n if (req.method === 'POST' && !req.body) {\n const chunks: Buffer[] = [];\n\n // Check if req is a stream (has Symbol.asyncIterator)\n if (typeof (req as any)[Symbol.asyncIterator] === 'function') {\n for await (const chunk of req as any) {\n chunks.push(chunk);\n }\n\n const body = Buffer.concat(chunks).toString();\n\n // Store raw body if requested (for signature verification)\n if (preserveRaw) {\n req.rawBody = body;\n }\n\n // Only attempt to parse if there's actual content\n if (body.trim()) {\n try {\n req.body = JSON.parse(body);\n } catch (error) {\n throw new Error('Invalid JSON in request body');\n }\n } else {\n req.body = {};\n }\n }\n }\n }\n\n protected async handleGet(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook verification error:', error);\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n }\n\n protected async handlePost(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req);\n } catch (error) {\n console.error('Webhook processing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n res.status(400).json({ error: 'Invalid JSON' });\n throw error;\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook processing error:', error);\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n }\n\n protected async handleFlow(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Parse body and preserve raw body for signature verification\n await this.parseRequestBody(req, true);\n } catch (error) {\n console.error('Flow body parsing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n res.status(400).json({ error: 'Invalid JSON' });\n throw error;\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody || (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n\n // Return result for user's custom handling\n return result;\n } catch (error) {\n console.error('Flow error:', error);\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: TRequest, res: TResponse) => this.handleGet(req, res),\n POST: (req: TRequest, res: TResponse) => this.handlePost(req, res),\n\n // Auto-routing webhook handler\n webhook: (req: TRequest, res: TResponse) => this.autoRoute(req, res),\n\n // Flow handler\n flow: (req: TRequest, res: TResponse) => this.handleFlow(req, res),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\n// Next.js Pages Router webhook handler\nexport function nextjsPagesWebhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n return handler.getHandlers();\n}\n","import { WhatsAppConfig } from '../../../../types/config';\nimport { WebhookProcessor } from '../../WebhookProcessor';\n\n// Define Next.js types locally to avoid requiring Next.js as a dependency\nexport interface NextRequest extends Request {\n nextUrl: {\n searchParams: URLSearchParams;\n };\n}\n\nexport interface NextResponse {\n json(data: any): NextResponse;\n}\n\nexport interface NextJsAppWebhookConfig extends WhatsAppConfig {\n // App Router specific config (currently none, but interface reserved for future use)\n}\n\n// Next.js App Router webhook handler\nexport function nextjsAppWebhookHandler(config: NextJsAppWebhookConfig) {\n const processor = new WebhookProcessor(config);\n\n return {\n // Clean GET/POST handlers following whatsapp-api-js methodology\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n\n // Return plain text response for webhook verification\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n\n // Return JSON response for webhook processing\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n // Legacy webhook object for backward compatibility\n webhook: {\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n },\n\n // Flow handler for App Router\n flow: {\n GET: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow GET error:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow POST error:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n },\n\n // Expose processor for handler registration\n processor,\n };\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","import type { ResponseSuccess } from '../../../types/request';\n\n/**\n * WhatsApp Business Account subscription configuration\n */\nexport type WabaSubscription = {\n whatsapp_business_api_data: {\n id: string;\n link: string;\n name: string;\n category: string;\n };\n override_callback_uri?: string;\n};\n\n/**\n * Parameters for updating WABA subscription\n */\nexport interface UpdateWabaSubscription {\n override_callback_uri: string;\n verify_token: string;\n}\n\n/**\n * Response containing all WABA subscriptions\n */\nexport interface WabaSubscriptions {\n data: Array<WabaSubscription>;\n}\n\n/**\n * WABA account review status enumeration\n */\nexport enum WabaAccountReviewStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * WABA health status for message sending capability\n */\nexport enum WabaHealthStatusCanSendMessage {\n Blocked = 'BLOCKED',\n Limited = 'LIMITED',\n Available = 'AVAILABLE',\n}\n\n/**\n * WABA account status enumeration\n */\nexport enum WabaAccountStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * Business verification status enumeration\n */\nexport enum WabaBusinessVerificationStatus {\n Verified = 'verified',\n PendingSubmission = 'pending_submission',\n Unverified = 'unverified',\n Rejected = 'rejected',\n}\n\n/**\n * WABA health status error details\n */\nexport interface WabaHealthStatusError {\n error_code?: number;\n error_description?: string;\n possible_solution?: string;\n}\n\n/**\n * WABA health status entity information\n */\nexport interface WabaHealthStatusEntity {\n entity_type?: string;\n id?: string;\n can_send_message?: string;\n errors?: WabaHealthStatusError[];\n}\n\n/**\n * Overall WABA health status\n */\nexport interface WabaHealthStatus {\n can_send_message?: WabaHealthStatusCanSendMessage;\n entities?: WabaHealthStatusEntity[];\n}\n\n/**\n * WhatsApp Business Account information\n */\nexport interface WabaAccount {\n account_review_status?: WabaAccountReviewStatus;\n id?: string;\n health_status?: WabaHealthStatus;\n status?: WabaAccountStatus;\n business_verification_status?: WabaBusinessVerificationStatus;\n message_template_namespace?: string;\n name?: string;\n ownership_type?: string;\n currency?: string;\n}\n\n/**\n * Available fields for WABA account queries\n */\nexport type WabaAccountFields =\n | 'id'\n | 'name'\n | 'account_review_status'\n | 'auth_international_rate_eligibility'\n | 'business_verification_status'\n | 'country'\n | 'currency'\n | 'health_status'\n | 'status'\n | 'ownership_type'\n | 'message_template_namespace';\n\n/**\n * Parameter type for specifying which WABA account fields to retrieve\n */\nexport type WabaAccountFieldsParam = WabaAccountFields[];\n\n/**\n * Interface defining all WABA API methods\n */\nexport interface WABAClass {\n getWabaAccount(fields?: WabaAccountFieldsParam): Promise<WabaAccount>;\n getAllWabaSubscriptions(): Promise<WabaSubscriptions>;\n updateWabaSubscription(params: UpdateWabaSubscription): Promise<ResponseSuccess>;\n unsubscribeFromWaba(): Promise<ResponseSuccess>;\n}\n"],"mappings":"41BAAA,IAAY,EAAA,SAAA,EAAL,OACH,GAAA,eAAA,iBACA,EAAA,UAAA,YACA,EAAA,QAAA,iBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,SAAA,WACA,EAAA,QAAA,UACA,EAAA,SAAA,kBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,IAAA,MACA,EAAA,KAAA,OACA,EAAA,IAAA,MACA,EAAA,OAAA,gBAGQ,EAAA,SAAA,EAAL,O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IL,MAAa,IAAsB,EAAc,IACtCC,EAAO,WAAW,SAAU,EAAU,CAAC,OAAO,EAAM,QAAQ,CAAC,OAAO,MAAM,CC8BrF,IAAY,GAAA,SAAA,EAAL,OACH,GAAA,SAAA,WACA,EAAA,OAAA,SACA,EAAA,SAAA,WACA,EAAA,SAAA,kBAMQ,GAAA,SAAA,EAAL,OACH,GAAA,QAAA,UACA,EAAA,QAAA,UACA,EAAA,UAAA,mBAMQ,GAAA,SAAA,EAAL,OACH,GAAA,SAAA,WACA,EAAA,OAAA,SACA,EAAA,SAAA,WACA,EAAA,SAAA,kBAMQ,GAAA,SAAA,EAAL,OACH,GAAA,SAAA,WACA,EAAA,kBAAA,qBACA,EAAA,WAAA,aACA,EAAA,SAAA"}
1
+ {"version":3,"file":"index.js","names":["LOGGER","LOGGER","decryptedAesKey: Buffer","flipped_iv: number[]","LOGGER","LOGGER","headers: HeadersInit","queryParts: string[]","fileContent: Blob","body: m.MessageRequestBody<T>","textPayload: m.TextObject","body: registration.RegistrationRequest","header: TemplateHeader","body: TemplateBody","buttons: TemplateButton[]","urlButton: any","flowButton: any","components: ComponentTypes[]","carouselComponents: ComponentTypes[]","carouselCards: MediaCarouselCard[]","cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[]","carouselCards: ProductCarouselCard[]","LOGGER","MessageApi","SDKEnums","LOGGER","errors: string[]","flowType: FlowTypeEnum","processed: ProcessedStatus","processed: ProcessedMessage","chunks: Buffer[]","crypto"],"sources":["../src/types/enums.ts","../src/utils/logger.ts","../src/config/importConfig.ts","../src/utils/configTable.ts","../src/utils/flowEncryptionUtils.ts","../src/utils/isMetaError.ts","../src/utils/http/httpsClient.ts","../src/utils/http/request.ts","../src/utils/version.ts","../src/types/base.ts","../src/utils/objectToQueryString.ts","../src/api/blockUsers/BlockUsersApi.ts","../src/api/encryption/EncryptionApi.ts","../src/api/flow/FlowApi.ts","../src/api/flow/types/common.ts","../src/api/media/MediaApi.ts","../src/api/messages/MessageApi.ts","../src/api/phone/PhoneNumberApi.ts","../src/utils/buildFieldsQueryString.ts","../src/api/profile/BusinessProfileApi.ts","../src/api/qrCode/QrCodeApi.ts","../src/api/registration/RegistrationApi.ts","../src/api/template/TemplateApi.ts","../src/api/template/factories/index.ts","../src/api/twoStepVerification/TwoStepVerificationApi.ts","../src/api/waba/WabaApi.ts","../src/utils/logoConsole.ts","../src/core/whatsapp/WhatsApp.ts","../src/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts","../src/core/webhook/frameworks/handler.ts","../src/core/webhook/frameworks/express/express.ts","../src/core/webhook/frameworks/nextjs-page/nextjs-page.ts","../src/core/webhook/frameworks/nextjs-app/nextjs-app.ts","../src/core/webhook/utils/generateXHub256Sig.ts","../src/api/waba/types/common.ts"],"sourcesContent":["export enum CategoryEnum {\n Authentication = 'AUTHENTICATION',\n Marketing = 'MARKETING',\n Utility = 'UTILITY',\n}\n\nexport enum TemplateStatusEnum {\n Approved = 'APPROVED',\n Pending = 'PENDING',\n Rejected = 'REJECTED',\n}\n\nexport enum HttpMethodsEnum {\n Get = 'GET',\n Post = 'POST',\n Put = 'PUT',\n Delete = 'DELETE',\n}\n\nexport enum MessageTypesEnum {\n Audio = 'audio',\n Contacts = 'contacts',\n Document = 'document',\n Image = 'image',\n Interactive = 'interactive',\n Location = 'location',\n Reaction = 'reaction',\n Sticker = 'sticker',\n Template = 'template',\n Text = 'text',\n Video = 'video',\n Button = 'button',\n Order = 'order',\n System = 'system',\n Unsupported = 'unsupported',\n Unknown = 'unknown',\n /**\n * @deprecated Use WebhookProcessor.onStatus() instead of onMessage(MessageTypesEnum.Statuses)\n */\n Statuses = 'statuses',\n '*' = '*',\n}\n\nexport enum ParametersTypesEnum {\n Action = 'ACTION',\n CouponCode = 'COUPON_CODE',\n Currency = 'CURRENCY',\n DateTime = 'DATE_TIME',\n Document = 'DOCUMENT',\n ExpirationTimeMs = 'EXPIRATION_TIME_MS',\n Image = 'IMAGE',\n LimitedTimeOffer = 'LIMITED_TIME_OFFER',\n Location = 'LOCATION',\n OrderStatus = 'ORDER_STATUS',\n Payload = 'PAYLOAD',\n Product = 'PRODUCT',\n Text = 'TEXT',\n TtlMinutes = 'TTL_MINUTES',\n Video = 'VIDEO',\n WebviewInteraction = 'WEBVIEW_INTERACTION',\n WebviewPresentation = 'WEBVIEW_PRESENTATION',\n}\n\nexport enum InteractiveTypesEnum {\n Button = 'button',\n List = 'list',\n Product = 'product',\n ProductList = 'product_list',\n CtaUrl = 'cta_url',\n LocationRequest = 'location_request_message',\n AddressMessage = 'address_message',\n Flow = 'flow',\n}\n\nexport enum ButtonPositionEnum {\n First = 1,\n Second = 2,\n Third = 3,\n Fourth = 4,\n Fifth = 5,\n}\n\nexport enum SubTypeEnum {\n Catalog = 'CATALOG',\n CopyCode = 'COPY_CODE',\n Flow = 'FLOW',\n Mpm = 'MPM',\n OrderDetails = 'ORDER_DETAILS',\n QuickReply = 'QUICK_REPLY',\n Reminder = 'REMINDER',\n Url = 'URL',\n VoiceCall = 'VOICE_CALL',\n}\n\nexport enum ComponentTypesEnum {\n Header = 'HEADER',\n Body = 'BODY',\n Button = 'BUTTON',\n Footer = 'FOOTER',\n}\n\nexport enum WabaConfigEnum {\n AppId = 'M4D_APP_ID',\n Port = 'WA_PORT',\n AppSecret = 'M4D_APP_SECRET',\n PhoneNumberId = 'WA_PHONE_NUMBER_ID',\n BusinessAcctId = 'WA_BUSINESS_ACCOUNT_ID',\n APIVersion = 'CLOUD_API_VERSION',\n AccessToken = 'CLOUD_API_ACCESS_TOKEN',\n WebhookEndpoint = 'WEBHOOK_ENDPOINT',\n WebhookVerificationToken = 'WEBHOOK_VERIFICATION_TOKEN',\n ListenerPort = 'LISTENER_PORT',\n MaxRetriesAfterWait = 'MAX_RETRIES_AFTER_WAIT',\n RequestTimeout = 'REQUEST_TIMEOUT',\n Debug = 'DEBUG',\n PrivatePem = 'FLOW_API_PRIVATE_PEM',\n Passphrase = 'FLOW_API_PASSPHRASE',\n}\n\nexport enum ConversationTypesEnum {\n BusinessInitiated = 'business_initiated',\n CustomerInitiated = 'customer_initiated',\n ReferralConversion = 'referral_conversion',\n}\n\nexport enum StatusEnum {\n Delivered = 'delivered',\n Read = 'read',\n Sent = 'sent',\n}\n\nexport enum VideoMediaTypesEnum {\n Mp4 = 'video/mp4',\n Threegp = 'video/3gp',\n}\n\nexport enum StickerMediaTypesEnum {\n Webp = 'image/webp',\n}\n\nexport enum ImageMediaTypesEnum {\n Jpeg = 'image/jpeg',\n Png = 'image/png',\n}\n\nexport enum DocumentMediaTypesEnum {\n Text = 'text/plain',\n Pdf = 'application/pdf',\n Ppt = 'application/vnd.ms-powerpoint',\n Word = 'application/msword',\n Excel = 'application/vnd.ms-excel',\n OpenDoc = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n OpenPres = 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n OpenSheet = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n}\n\nexport enum AudioMediaTypesEnum {\n Aac = 'audio/aac',\n Mp4 = 'audio/mp4',\n Mpeg = 'audio/mpeg',\n Amr = 'audio/amr',\n Ogg = 'audio/ogg',\n}\n\nexport enum WebhookTypesEnum {\n Audio = 'audio',\n Button = 'button',\n Document = 'document',\n Text = 'text',\n Image = 'image',\n Interactive = 'interactive',\n Order = 'order',\n Sticker = 'sticker',\n System = 'system',\n Unknown = 'unknown',\n Video = 'video',\n}\n\nexport enum SystemChangeTypesEnum {\n CustomerChangedNumber = 'customer_changed_number',\n CustomerIdentityChanged = 'customer_identity_changed',\n}\n\nexport enum ReferralSourceTypesEnum {\n Ad = 'ad',\n Post = 'post',\n}\n\nexport enum RequestCodeMethodsEnum {\n Sms = 'SMS',\n Voice = 'VOICE',\n}\n\nexport enum LanguagesEnum {\n Afrikaans = 'af',\n Albanian = 'sq',\n Arabic = 'ar',\n Azerbaijani = 'az',\n Bengali = 'bn',\n Bulgarian = 'bg',\n Catalan = 'ca',\n Chinese_CHN = 'zh_CN',\n Chinese_HKG = 'zh_HK',\n Chinese_TAI = 'zh_TW',\n Croatian = 'hr',\n Czech = 'cs',\n Danish = 'da',\n Dutch = 'nl',\n English = 'en',\n English_UK = 'en_GB',\n English_US = 'en_US',\n Estonian = 'et',\n Filipino = 'fil',\n Finnish = 'fi',\n French = 'fr',\n Georgian = 'ka',\n German = 'de',\n Greek = 'el',\n Gujarati = 'gu',\n Hausa = 'ha',\n Hebrew = 'he',\n Hindi = 'hi',\n Hungarian = 'hu',\n Indonesian = 'id',\n Irish = 'ga',\n Italian = 'it',\n Japanese = 'ja',\n Kannada = 'kn',\n Kazakh = 'kk',\n Kinyarwanda = 'rw_RW',\n Korean = 'ko',\n Kyrgyz_Kyrgyzstan = 'ky_KG',\n Lao = 'lo',\n Latvian = 'lv',\n Lithuanian = 'lt',\n Macedonian = 'mk',\n Malay = 'ms',\n Malayalam = 'ml',\n Marathi = 'mr',\n Norwegian = 'nb',\n Persian = 'fa',\n Polish = 'pl',\n Portuguese_BR = 'pt_BR',\n Portuguese_POR = 'pt_PT',\n Punjabi = 'pa',\n Romanian = 'ro',\n Russian = 'ru',\n Serbian = 'sr',\n Slovak = 'sk',\n Slovenian = 'sl',\n Spanish = 'es',\n Spanish_ARG = 'es_AR',\n Spanish_SPA = 'es_ES',\n Spanish_MEX = 'es_MX',\n Swahili = 'sw',\n Swedish = 'sv',\n Tamil = 'ta',\n Telugu = 'te',\n Thai = 'th',\n Turkish = 'tr',\n Ukrainian = 'uk',\n Urdu = 'ur',\n Uzbek = 'uz',\n Vietnamese = 'vi',\n Zulu = 'zu',\n}\n\nexport enum CurrencyCodesEnum {\n AFN = 'AFN',\n EUR = 'EUR',\n ALL = 'ALL',\n DZD = 'DZD',\n USD = 'USD',\n AOA = 'AOA',\n XCD = 'XCD',\n ARS = 'ARS',\n AMD = 'AMD',\n AWG = 'AWG',\n AUD = 'AUD',\n AZN = 'AZN',\n BSD = 'BSD',\n BHD = 'BHD',\n BDT = 'BDT',\n BBD = 'BBD',\n BYN = 'BYN',\n BZD = 'BZD',\n XOF = 'XOF',\n BMD = 'BMD',\n INR = 'INR',\n BTN = 'BTN',\n BOB = 'BOB',\n BOV = 'BOV',\n BAM = 'BAM',\n BWP = 'BWP',\n NOK = 'NOK',\n BRL = 'BRL',\n BND = 'BND',\n BGN = 'BGN',\n BIF = 'BIF',\n CVE = 'CVE',\n KHR = 'KHR',\n XAF = 'XAF',\n CAD = 'CAD',\n KYD = 'KYD',\n CLP = 'CLP',\n CLF = 'CLF',\n CNY = 'CNY',\n COP = 'COP',\n COU = 'COU',\n KMF = 'KMF',\n CDF = 'CDF',\n NZD = 'NZD',\n CRC = 'CRC',\n HRK = 'HRK',\n CUP = 'CUP',\n CUC = 'CUC',\n ANG = 'ANG',\n CZK = 'CZK',\n DKK = 'DKK',\n DJF = 'DJF',\n DOP = 'DOP',\n EGP = 'EGP',\n SVC = 'SVC',\n ERN = 'ERN',\n SZL = 'SZL',\n ETB = 'ETB',\n FKP = 'FKP',\n FJD = 'FJD',\n XPF = 'XPF',\n GMD = 'GMD',\n GEL = 'GEL',\n GHS = 'GHS',\n GIP = 'GIP',\n GTQ = 'GTQ',\n GBP = 'GBP',\n GNF = 'GNF',\n GYD = 'GYD',\n HTG = 'HTG',\n HNL = 'HNL',\n HKD = 'HKD',\n HUF = 'HUF',\n ISK = 'ISK',\n IDR = 'IDR',\n XDR = 'XDR',\n IRR = 'IRR',\n IQD = 'IQD',\n ILS = 'ILS',\n JMD = 'JMD',\n JPY = 'JPY',\n JOD = 'JOD',\n KZT = 'KZT',\n KES = 'KES',\n KPW = 'KPW',\n KRW = 'KRW',\n KWD = 'KWD',\n KGS = 'KGS',\n LAK = 'LAK',\n LBP = 'LBP',\n LSL = 'LSL',\n ZAR = 'ZAR',\n LRD = 'LRD',\n LYD = 'LYD',\n CHF = 'CHF',\n MOP = 'MOP',\n MKD = 'MKD',\n MGA = 'MGA',\n MWK = 'MWK',\n MYR = 'MYR',\n MVR = 'MVR',\n MRU = 'MRU',\n MUR = 'MUR',\n XUA = 'XUA',\n MXN = 'MXN',\n MXV = 'MXV',\n MDL = 'MDL',\n MNT = 'MNT',\n MAD = 'MAD',\n MZN = 'MZN',\n MMK = 'MMK',\n NAD = 'NAD',\n NPR = 'NPR',\n NIO = 'NIO',\n NGN = 'NGN',\n OMR = 'OMR',\n PKR = 'PKR',\n PAB = 'PAB',\n PGK = 'PGK',\n PYG = 'PYG',\n PEN = 'PEN',\n PHP = 'PHP',\n PLN = 'PLN',\n QAR = 'QAR',\n RON = 'RON',\n RUB = 'RUB',\n RWF = 'RWF',\n SHP = 'SHP',\n WST = 'WST',\n STN = 'STN',\n SAR = 'SAR',\n RSD = 'RSD',\n SCR = 'SCR',\n SLL = 'SLL',\n SGD = 'SGD',\n XSU = 'XSU',\n SBD = 'SBD',\n SOS = 'SOS',\n SSP = 'SSP',\n LKR = 'LKR',\n SDG = 'SDG',\n SRD = 'SRD',\n SEK = 'SEK',\n CHE = 'CHE',\n CHW = 'CHW',\n SYP = 'SYP',\n TWD = 'TWD',\n TJS = 'TJS',\n TZS = 'TZS',\n THB = 'THB',\n TOP = 'TOP',\n TTD = 'TTD',\n TND = 'TND',\n TRY = 'TRY',\n TMT = 'TMT',\n UGX = 'UGX',\n UAH = 'UAH',\n AED = 'AED',\n USN = 'USN',\n UYU = 'UYU',\n UYI = 'UYI',\n UYW = 'UYW',\n UZS = 'UZS',\n VUV = 'VUV',\n VES = 'VES',\n VND = 'VND',\n YER = 'YER',\n ZMW = 'ZMW',\n ZWL = 'ZWL',\n XBA = 'XBA',\n XBB = 'XBB',\n XBC = 'XBC',\n XBD = 'XBD',\n XTS = 'XTS',\n XXX = 'XXX',\n XAU = 'XAU',\n XPD = 'XPD',\n XPT = 'XPT',\n XAG = 'XAG',\n AFA = 'AFA',\n FIM = 'FIM',\n ALK = 'ALK',\n ADP = 'ADP',\n ESP = 'ESP',\n FRF = 'FRF',\n AOK = 'AOK',\n AON = 'AON',\n AOR = 'AOR',\n ARA = 'ARA',\n ARP = 'ARP',\n ARY = 'ARY',\n RUR = 'RUR',\n ATS = 'ATS',\n AYM = 'AYM',\n AZM = 'AZM',\n BYB = 'BYB',\n BYR = 'BYR',\n BEC = 'BEC',\n BEF = 'BEF',\n BEL = 'BEL',\n BOP = 'BOP',\n BAD = 'BAD',\n BRB = 'BRB',\n BRC = 'BRC',\n BRE = 'BRE',\n BRN = 'BRN',\n BRR = 'BRR',\n BGJ = 'BGJ',\n BGK = 'BGK',\n BGL = 'BGL',\n BUK = 'BUK',\n HRD = 'HRD',\n CYP = 'CYP',\n CSJ = 'CSJ',\n CSK = 'CSK',\n ECS = 'ECS',\n ECV = 'ECV',\n GQE = 'GQE',\n EEK = 'EEK',\n XEU = 'XEU',\n GEK = 'GEK',\n DDM = 'DDM',\n DEM = 'DEM',\n GHC = 'GHC',\n GHP = 'GHP',\n GRD = 'GRD',\n GNE = 'GNE',\n GNS = 'GNS',\n GWE = 'GWE',\n GWP = 'GWP',\n ITL = 'ITL',\n ISJ = 'ISJ',\n IEP = 'IEP',\n ILP = 'ILP',\n ILR = 'ILR',\n LAJ = 'LAJ',\n LVL = 'LVL',\n LVR = 'LVR',\n LSM = 'LSM',\n ZAL = 'ZAL',\n LTL = 'LTL',\n LTT = 'LTT',\n LUC = 'LUC',\n LUF = 'LUF',\n LUL = 'LUL',\n MGF = 'MGF',\n MVQ = 'MVQ',\n MLF = 'MLF',\n MTL = 'MTL',\n MTP = 'MTP',\n MRO = 'MRO',\n MXP = 'MXP',\n MZE = 'MZE',\n MZM = 'MZM',\n NLG = 'NLG',\n NIC = 'NIC',\n PEH = 'PEH',\n PEI = 'PEI',\n PES = 'PES',\n PLZ = 'PLZ',\n PTE = 'PTE',\n ROK = 'ROK',\n ROL = 'ROL',\n STD = 'STD',\n CSD = 'CSD',\n SKK = 'SKK',\n SIT = 'SIT',\n RHD = 'RHD',\n ESA = 'ESA',\n ESB = 'ESB',\n SDD = 'SDD',\n SDP = 'SDP',\n SRG = 'SRG',\n CHC = 'CHC',\n TJR = 'TJR',\n TPE = 'TPE',\n TRL = 'TRL',\n TMM = 'TMM',\n UGS = 'UGS',\n UGW = 'UGW',\n UAK = 'UAK',\n SUR = 'SUR',\n USS = 'USS',\n UYN = 'UYN',\n UYP = 'UYP',\n VEB = 'VEB',\n VEF = 'VEF',\n VNC = 'VNC',\n YDD = 'YDD',\n YUD = 'YUD',\n YUM = 'YUM',\n YUN = 'YUN',\n ZRN = 'ZRN',\n ZRZ = 'ZRZ',\n ZMK = 'ZMK',\n ZWC = 'ZWC',\n ZWD = 'ZWD',\n ZWN = 'ZWN',\n ZWR = 'ZWR',\n XFO = 'XFO',\n XRE = 'XRE',\n XFU = 'XFU',\n}\n\nexport enum DataLocalizationRegionEnum {\n // APAC\n AU = 'AU', // Australia\n ID = 'ID', // Indonesia\n IN = 'IN', // India\n JP = 'JP', // Japan\n SG = 'SG', // Singapore\n KR = 'KR', // South Korea\n\n // Europe\n DE = 'DE', // EU (Germany)\n CH = 'CH', // Switzerland\n GB = 'GB', // United Kingdom\n\n // LATAM\n BR = 'BR', // Brazil\n\n // MEA\n BH = 'BH', // Bahrain\n ZA = 'ZA', // South Africa\n AE = 'AE', // United Arab Emirates\n\n // NORAM\n CA = 'CA', // Canada\n}\n\n/**\n * Business category values for WhatsApp Business Profile.\n * These values map to specific strings displayed in the WhatsApp client.\n */\nexport enum BusinessVerticalEnum {\n /**\n * Alcoholic Beverages\n */\n ALCOHOL = 'ALCOHOL',\n /**\n * Clothing and Apparel\n */\n APPAREL = 'APPAREL',\n /**\n * Automotive\n */\n AUTO = 'AUTO',\n /**\n * Beauty, Spa and Salon\n */\n BEAUTY = 'BEAUTY',\n /**\n * Education\n */\n EDU = 'EDU',\n /**\n * Entertainment\n */\n ENTERTAIN = 'ENTERTAIN',\n /**\n * Event Planning and Service\n */\n EVENT_PLAN = 'EVENT_PLAN',\n /**\n * Finance and Banking\n */\n FINANCE = 'FINANCE',\n /**\n * Public Service\n */\n GOVT = 'GOVT',\n /**\n * Food and Grocery\n */\n GROCERY = 'GROCERY',\n /**\n * Medical and Health\n */\n HEALTH = 'HEALTH',\n /**\n * Hotel and Lodging\n */\n HOTEL = 'HOTEL',\n /**\n * Non-profit\n */\n NONPROFIT = 'NONPROFIT',\n /**\n * Online Gambling & Gaming\n */\n ONLINE_GAMBLING = 'ONLINE_GAMBLING',\n /**\n * Over-the-Counter Drugs\n */\n OTC_DRUGS = 'OTC_DRUGS',\n /**\n * Other\n */\n OTHER = 'OTHER',\n /**\n * Non-Online Gambling & Gaming (E.g. Brick and mortar)\n */\n PHYSICAL_GAMBLING = 'PHYSICAL_GAMBLING',\n /**\n * Professional Services\n */\n PROF_SERVICES = 'PROF_SERVICES',\n /**\n * Restaurant\n */\n RESTAURANT = 'RESTAURANT',\n /**\n * Shopping and Retail\n */\n RETAIL = 'RETAIL',\n /**\n * Travel and Transportation\n */\n TRAVEL = 'TRAVEL',\n}\n","// @ts-nocheck\nimport { inspect } from 'util';\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n private formatData(data: any[]): string {\n return data\n .map((item) => (typeof item === 'object' ? inspect(item, { depth: null, colors: true }) : item))\n .join(' ');\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log(prefix, ': ', this.formatData(data));\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error(prefix, ': ', this.formatData(data));\n }\n\n warn(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn(prefix, ': ', this.formatData(data));\n }\n }\n\n info(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info(prefix, ': ', this.formatData(data));\n }\n }\n}\n","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 return wabaConfig;\n};\n","import type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\n\n/**\n * Formats configuration as a terminal table\n * @param config - The WABA configuration object\n * @param apiName - The name of the API being initialized\n * @returns Formatted table string\n */\nexport function formatConfigTable(config: WabaConfigType): string {\n const configData = [\n ['App ID', config[WabaConfigEnum.AppId] || 'Not Set'],\n ['Phone Number ID', config[WabaConfigEnum.PhoneNumberId]?.toString() || 'Not Set'],\n ['Business Account ID', config[WabaConfigEnum.BusinessAcctId] || 'Not Set'],\n ['API Version', config[WabaConfigEnum.APIVersion] || 'Not Set'],\n [\n 'Access Token',\n config[WabaConfigEnum.AccessToken]\n ? `${config[WabaConfigEnum.AccessToken].substring(0, 20)}...`\n : 'Not Set',\n ],\n ['Webhook Endpoint', config[WabaConfigEnum.WebhookEndpoint] || 'Not Set'],\n [\n 'Webhook Verification Token',\n config[WabaConfigEnum.WebhookVerificationToken]\n ? `${config[WabaConfigEnum.WebhookVerificationToken].substring(0, 10)}...`\n : 'Not Set',\n ],\n ['Listener Port', config[WabaConfigEnum.ListenerPort]?.toString() || 'Not Set'],\n ['Debug Mode', config[WabaConfigEnum.Debug] ? 'Enabled' : 'Disabled'],\n ['Max Retries', config[WabaConfigEnum.MaxRetriesAfterWait]?.toString() || 'Not Set'],\n [\n 'Request Timeout',\n config[WabaConfigEnum.RequestTimeout] ? `${config[WabaConfigEnum.RequestTimeout]}ms` : 'Not Set',\n ],\n ['Private PEM', config[WabaConfigEnum.PrivatePem] ? 'Configured' : 'Not Set'],\n ['Passphrase', config[WabaConfigEnum.Passphrase] ? 'Configured' : 'Not Set'],\n ];\n\n // Calculate column widths\n const maxKeyLength = Math.max(...configData.map(([key]) => key?.length || 0));\n const maxValueLength = Math.max(...configData.map(([, value]) => value?.length || 0));\n\n const keyWidth = Math.max(maxKeyLength, 20);\n const valueWidth = Math.max(maxValueLength, 30);\n\n // Create table\n const horizontalLine = `┌${'─'.repeat(keyWidth + 2)}┬${'─'.repeat(valueWidth + 2)}┐`;\n const separator = `├${'─'.repeat(keyWidth + 2)}┼${'─'.repeat(valueWidth + 2)}┤`;\n const bottomLine = `└${'─'.repeat(keyWidth + 2)}┴${'─'.repeat(valueWidth + 2)}┘`;\n\n const header = `│ ${'Configuration'.padEnd(keyWidth)} │ ${'Value'.padEnd(valueWidth)} │`;\n\n const rows = configData.map(([key, value]) => `│ ${key?.padEnd(keyWidth)} │ ${value?.padEnd(valueWidth)} │`);\n\n return [horizontalLine, header, separator, ...rows, bottomLine].join('\\n');\n}\n","/**\n * WhatsApp Flow Encryption/Decryption Utilities\n * Handles encryption and decryption of WhatsApp Flow requests and responses\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\n\nimport crypto from 'crypto';\n\nimport { FlowEndpointRequest } from '../api/flow';\nimport { WabaConfigType } from '../types/config';\nimport Logger from './logger';\n\nconst LIB_NAME = 'FLOW_ENCRYPTION_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Environment model for encryption keys\n */\nexport type EncryptionKeyPair = {\n passphrase: string;\n privateKey: string;\n publicKey: string;\n};\n\n/**\n * Validates that the code is running in a Node.js environment\n * @throws {Error} If not running in Node.js environment\n */\nfunction validateNodeEnvironment(): void {\n // Check if crypto module exists and has required methods\n if (!crypto || typeof crypto.generateKeyPairSync !== 'function') {\n const error = new Error(\n 'This utility requires Node.js environment with crypto module. ' +\n 'It cannot be used in browser or edge runtime environments.',\n );\n LOGGER.error('Environment validation failed:', error);\n throw error;\n }\n\n // Check if running in browser\n if (typeof window !== 'undefined') {\n const error = new Error(\n 'This utility cannot run in a browser environment. ' +\n 'Please use it in a Node.js server environment only.',\n );\n LOGGER.error('Browser environment detected:', error);\n throw error;\n }\n\n // Check Node.js version (crypto.generateKeyPairSync requires Node.js 10.12.0+)\n if (process.versions && process.versions.node) {\n const nodeVersion = process.versions.node.split('.').map(Number);\n const major = nodeVersion[0] ?? 0;\n const minor = nodeVersion[1] ?? 0;\n\n if (major < 10 || (major === 10 && minor < 12)) {\n const error = new Error(\n `Node.js version ${process.versions.node} is not supported. ` +\n 'Please upgrade to Node.js 10.12.0 or higher.',\n );\n LOGGER.error('Node.js version check failed:', error);\n throw error;\n }\n }\n}\n\n/**\n * Generates RSA key pair for WhatsApp Business Flow API encryption\n *\n * This function generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from environment\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @example\n * ```typescript\n * import { WhatsApp } from 'meta-cloud-api';\n *\n * const wa = new WhatsApp();\n *\n * try {\n * // Uses FLOW_API_PASSPHRASE from environment\n * const keys = wa.generateEncryption();\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n * } catch (error) {\n * console.error('Failed to generate keys:', error.message);\n * }\n * ```\n */\nexport function generateEncryption(passphrase?: string): EncryptionKeyPair {\n LOGGER.info('[generateEncryption] Starting key pair generation');\n\n // Validate environment first\n validateNodeEnvironment();\n\n // Get passphrase from parameter or environment variable\n const effectivePassphrase = passphrase || process.env.FLOW_API_PASSPHRASE;\n\n // Validate passphrase\n if (!effectivePassphrase || effectivePassphrase.trim().length === 0) {\n const error = new Error(\n 'Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.',\n );\n LOGGER.error('[generateEncryption] Passphrase validation failed:', error);\n throw error;\n }\n\n // Warn if passphrase is too short\n if (effectivePassphrase.length < 8) {\n LOGGER.warn(\n '[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.',\n );\n }\n\n try {\n LOGGER.info('[generateEncryption] Generating 2048-bit RSA key pair');\n\n // Generate RSA key pair\n const keyPair = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: effectivePassphrase,\n },\n });\n\n LOGGER.info('[generateEncryption] Key pair generated successfully');\n\n return {\n passphrase: effectivePassphrase,\n privateKey: keyPair.privateKey,\n publicKey: keyPair.publicKey,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const generationError = new Error(`Failed to generate key pair: ${errorMessage}`);\n LOGGER.error('[generateEncryption] Key generation failed:', generationError);\n throw generationError;\n }\n}\n\n/**\n * Decrypt a WhatsApp Flow request\n * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector\n * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and FLOW_API_PASSPHRASE\n * @returns Decrypted flow request body, AES key buffer, and initial vector buffer\n * @throws {Error} If required encryption properties are missing or decryption fails\n */\nexport function decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('[decryptFlowRequest] Starting Flow request decryption');\n\n // Validate required environment variables\n if (!config.FLOW_API_PRIVATE_PEM || config.FLOW_API_PRIVATE_PEM.trim() === '') {\n const error = new Error(\n 'Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.',\n );\n LOGGER.error('[decryptFlowRequest] Configuration error:', error);\n throw error;\n }\n\n if (!config.FLOW_API_PASSPHRASE || config.FLOW_API_PASSPHRASE.trim() === '') {\n const error = new Error(\n 'Missing FLOW_API_PASSPHRASE. Please set the FLOW_API_PASSPHRASE environment variable or pass passphrase via config.',\n );\n LOGGER.error('[decryptFlowRequest] Configuration error:', error);\n throw error;\n }\n\n LOGGER.info('[decryptFlowRequest] Configuration validated');\n\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('[decryptFlowRequest] Missing required encryption properties in request body');\n throw new Error('Missing required encryption properties');\n }\n\n LOGGER.info('[decryptFlowRequest] Request body validated');\n\n // Handle both escaped and unescaped newlines\n let privatePem = config.FLOW_API_PRIVATE_PEM;\n if (privatePem.includes('\\\\n')) {\n privatePem = privatePem.replace(/\\\\n/g, '\\n');\n }\n\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const isPKCS1 = privatePem.includes('-----BEGIN RSA PRIVATE KEY-----');\n const isPKCS8 =\n privatePem.includes('-----BEGIN PRIVATE KEY-----') ||\n privatePem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----');\n\n LOGGER.info('[decryptFlowRequest] Loading private key', {\n format: isPKCS8 ? 'PKCS#8' : isPKCS1 ? 'PKCS#1' : 'Unknown',\n });\n\n let privateKey;\n try {\n // Try to create private key with passphrase\n if (passphrase) {\n privateKey = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase,\n });\n } else {\n privateKey = crypto.createPrivateKey(privatePem);\n }\n LOGGER.info('[decryptFlowRequest] Private key loaded successfully');\n } catch (error) {\n LOGGER.error('[decryptFlowRequest] Failed to load private key:', {\n error: error instanceof Error ? error.message : error,\n hasPassphrase: !!passphrase,\n format: isPKCS8 ? 'PKCS#8' : isPKCS1 ? 'PKCS#1' : 'Unknown',\n });\n\n // Provide helpful error message\n let errorMessage = `Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`;\n\n if (isPKCS1) {\n errorMessage += '\\n\\nYour key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).';\n errorMessage += '\\nPlease convert it to PKCS#8 format using:';\n errorMessage += '\\n openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem';\n errorMessage += '\\n\\nOr ensure your key uses a supported encryption algorithm (not DES-EDE3-CBC).';\n } else if (!isPKCS8) {\n errorMessage += '\\n\\nYour key format is not recognized. Please ensure it is in PKCS#8 format.';\n }\n\n throw new Error(errorMessage);\n }\n\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('[decryptFlowRequest] Decrypting AES key with RSA private key');\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 LOGGER.info('[decryptFlowRequest] AES key decrypted successfully');\n } catch (error) {\n LOGGER.error('[decryptFlowRequest] Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('[decryptFlowRequest] Decrypting flow data with AES-128-GCM');\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('[decryptFlowRequest] Flow request decrypted successfully');\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\n/**\n * Encrypt a WhatsApp Flow response\n * @param response - Response object to encrypt\n * @param aesKeyBuffer - AES key buffer from the decrypted request\n * @param initialVectorBuffer - Initial vector buffer from the decrypted request\n * @returns Base64-encoded encrypted response\n * @throws {Error} If encryption fails\n */\nexport function encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('[encryptFlowResponse] Starting Flow response encryption');\n\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 LOGGER.info('[encryptFlowResponse] Encrypting response with AES-128-GCM');\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('[encryptFlowResponse] Flow response encrypted successfully');\n\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('[encryptFlowResponse] Response encryption failed:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../../types/httpsClient';\nimport Logger from '../logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\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 '../isMetaError';\nimport Logger from '../logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\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 { readFileSync } from 'fs';\nimport { join } from 'path';\n\n/**\n * Get SDK version from package.json\n */\nexport function getVersion(): string {\n try {\n const packagePath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));\n return packageJson.version;\n } catch (error) {\n return 'unknown';\n }\n}\n\n/**\n * Generate User-Agent string following official SDK pattern\n */\nexport function getUserAgent(): string {\n const version = getVersion();\n const nodeVersion = process.version;\n return `WhatsApp-Nodejs-SDK/${version} (Node.js ${nodeVersion})`;\n}\n","import type { WabaConfigType } from './config';\n\nexport declare class BaseClass {\n constructor(config: WabaConfigType);\n}\n\nimport { HttpMethodsEnum } from './enums';\nimport type { RequesterClass } from './request';\n\nexport class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n\n protected sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.sendFormData<T>(method, endpoint, timeout, body);\n }\n\n protected sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n ): Promise<T> {\n return this.client.sendUrlEncodedForm<T>(method, endpoint, timeout, body);\n }\n}\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const queryParts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n queryParts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return queryParts.length > 0 ? `?${queryParts.join('&')}` : '';\n};\n","import { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\nimport type { WabaConfigType } from '../../types/config';\nimport * as blockUsers from './types/blockUsers';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\n/**\n * Block Users API\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users\n *\n * Limitations:\n * - Can only block users that have messaged your business in the last 24 hours\n * - 64k blocklist limit\n */\nexport default class BlockUsersApi extends BaseAPI implements blockUsers.BlockUsersClass {\n private readonly endpoint = 'block_users';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Build request body for block/unblock operations\n */\n private buildBlockUsersBody(users: string[]): blockUsers.BlockUsersRequest {\n return {\n messaging_product: 'whatsapp',\n block_users: users.map((user) => ({ user })),\n };\n }\n\n /**\n * Block one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to block\n * @returns Response with successfully blocked and failed users\n * @throws Error if users have not messaged in last 24 hours\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#block-users\n *\n * @example\n * ```typescript\n * // Block single user\n * const result = await client.blockUsers.block(['1234567890']);\n *\n * // Block multiple users\n * const result = await client.blockUsers.block(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Blocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async block(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n if (!users || users.length === 0) {\n throw new Error('At least one user must be provided to block');\n }\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unblock one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to unblock\n * @returns Response with successfully unblocked and failed users\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#unblock-users\n *\n * @example\n * ```typescript\n * // Unblock single user\n * const result = await client.blockUsers.unblock(['1234567890']);\n *\n * // Unblock multiple users\n * const result = await client.blockUsers.unblock(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Unblocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async unblock(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n if (!users || users.length === 0) {\n throw new Error('At least one user must be provided to unblock');\n }\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Get list of blocked WhatsApp users with pagination\n * @param params - Optional pagination parameters\n * @returns List of blocked users with pagination info\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/block-users#get-list-of-blocked-numbers\n *\n * @example\n * ```typescript\n * // Get first 10 blocked users\n * const result = await client.blockUsers.listBlockedUsers({ limit: 10 });\n *\n * // Pagination with cursor\n * const nextPage = await client.blockUsers.listBlockedUsers({\n * limit: 10,\n * after: result.paging?.cursors?.after\n * });\n *\n * // Get all blocked users\n * const allBlocked = await client.blockUsers.listBlockedUsers();\n * ```\n */\n async listBlockedUsers(params?: blockUsers.ListBlockedUsersParams): Promise<blockUsers.ListBlockedUsersResponse> {\n let endpoint = `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`;\n\n // Add query parameters if provided\n if (params) {\n const queryString = objectToQueryString(params);\n if (queryString) {\n endpoint += `?${queryString}`;\n }\n }\n\n return await this.sendJson<blockUsers.ListBlockedUsersResponse>(\n HttpMethodsEnum.Get,\n endpoint,\n this.config[WabaConfigEnum.RequestTimeout],\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n\nexport default class EncryptionApi extends BaseAPI implements EncryptionClass {\n private readonly endpoint = 'whatsapp_business_encryption';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getEncryptionPublicKey(): Promise<EncryptionPublicKeyResponse> {\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 async setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess> {\n const formData = new FormData();\n formData.append('business_public_key', businessPublicKey);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as flow from './types';\n\n/**\n * API for managing WhatsApp Flows.\n *\n * This API allows you to:\n * - List flows\n * - Create flows\n * - Get flow details and previews\n * - Update flow metadata and JSON\n * - Delete flows\n * - Publish and deprecate flows\n * - Migrate flows between WABAs\n * - Validate flow JSON\n */\nexport default class FlowApi extends BaseAPI implements flow.FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<flow.FlowsListResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<flow.CreateFlowResponse> {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<flow.Flow | flow.FlowPreviewResponse> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(flowId: string, invalidate: boolean = false): Promise<flow.FlowPreviewResponse> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<flow.FlowPreviewResponse>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<flow.FlowAssetsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<flow.UpdateFlowResponse> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<flow.ValidateFlowJsonResponse> {\n try {\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n const isValid = !result.validation_errors || result.validation_errors.length === 0;\n\n const enhancedResponse = {\n ...result,\n valid: isValid,\n };\n\n return enhancedResponse;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<flow.FlowMigrationResponse> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n","import { ResponseSuccess } from '../../../types';\nimport { IncomingHttpHeaders, IncomingMessage } from 'http';\n\n/**\n * Enum for Flow Status\n */\nexport enum FlowStatusEnum {\n Draft = 'DRAFT',\n Published = 'PUBLISHED',\n Throttled = 'THROTTLED',\n Blocked = 'BLOCKED',\n Deprecated = 'DEPRECATED',\n}\n\n/**\n * Enum for Flow Categories\n */\nexport enum FlowCategoryEnum {\n SignUp = 'SIGN_UP',\n SignIn = 'SIGN_IN',\n AppointmentBooking = 'APPOINTMENT_BOOKING',\n LeadGeneration = 'LEAD_GENERATION',\n ContactUs = 'CONTACT_US',\n CustomerSupport = 'CUSTOMER_SUPPORT',\n Survey = 'SURVEY',\n Other = 'OTHER',\n}\n\nexport enum FlowActionEnum {\n INIT = 'INIT',\n BACK = 'BACK',\n DATA_EXCHANGE = 'data_exchange',\n}\n\n/**\n * Enum for Flow Types in webhook handlers\n * Used to register handlers for specific flow events\n */\nexport enum FlowTypeEnum {\n /** Health check/ping requests */\n Ping = 'ping',\n /** Data exchange requests */\n Change = 'data_exchange',\n /** Error notification requests */\n Error = 'error',\n /** Match all flow action types */\n All = '*',\n}\n\nexport type FlowType = (typeof FlowTypeEnum)[keyof typeof FlowTypeEnum];\n\n/**\n * Flow Validation Error Pointer\n */\nexport interface FlowValidationErrorPointer {\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n path: string;\n}\n\n/**\n * Flow Validation Error\n */\nexport interface FlowValidationError {\n error: string;\n error_type: string;\n message: string;\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n pointers: FlowValidationErrorPointer[];\n}\n\n/**\n * Flow Item\n */\nexport interface Flow {\n id: string;\n name: string;\n status: FlowStatusEnum;\n categories: FlowCategoryEnum[];\n validation_errors: FlowValidationError[];\n}\n\n/**\n * Pagination Cursors\n */\nexport interface PaginationCursors {\n before: string;\n after: string;\n}\n\n/**\n * Pagination Object\n */\nexport interface Pagination {\n cursors: PaginationCursors;\n}\n\n/**\n * Flows List Response\n */\nexport interface FlowsListResponse {\n data: Flow[];\n paging: Pagination;\n}\n\n/**\n * Flow Asset\n */\nexport interface FlowAsset {\n name: string;\n asset_type: string;\n download_url: string;\n}\n\n/**\n * Flow Assets Response\n */\nexport interface FlowAssetsResponse {\n data: FlowAsset[];\n paging: Pagination;\n}\n\n/**\n * Flow Preview\n */\nexport interface FlowPreview {\n preview_url: string;\n expires_at: string;\n}\n\n/**\n * Flow Preview Response\n */\nexport interface FlowPreviewResponse {\n preview: FlowPreview;\n id: string;\n}\n\n/**\n * Flow Migration Result\n */\nexport interface FlowMigrationResult {\n source_name: string;\n source_id: string;\n migrated_id: string;\n}\n\n/**\n * Flow Migration Failure\n */\nexport interface FlowMigrationFailure {\n source_name: string;\n error_code: string;\n error_message: string;\n}\n\n/**\n * Create Flow Response\n */\nexport interface CreateFlowResponse {\n id: string;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Update Flow Response\n */\nexport interface UpdateFlowResponse {\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Flow Migration Response\n */\nexport interface FlowMigrationResponse {\n migrated_flows: FlowMigrationResult[];\n failed_flows: FlowMigrationFailure[];\n}\n\n/**\n * Validate Flow JSON Response\n */\nexport interface ValidateFlowJsonResponse {\n valid: boolean;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * WhatsApp Flow Endpoint - Encrypted Request Payload\n * Represents the raw encrypted data received from WhatsApp\n */\nexport interface FlowEncryptedRequestPayload {\n encrypted_aes_key: string;\n encrypted_flow_data: string;\n initial_vector: string;\n}\n\n/**\n * WhatsApp Flow Endpoint - Decrypted Request Response\n * Represents the successfully decrypted data and encryption keys\n */\nexport interface FlowDecryptedRequestResponse {\n decryptedBody: any;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n}\n\n/**\n * WhatsApp Flow Endpoint - HTTP Request with Body\n * Represents an HTTP request with the encrypted payload\n */\nexport interface FlowHttpRequest extends IncomingMessage {\n body: FlowEncryptedRequestPayload;\n headers: IncomingHttpHeaders;\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Request\n * Represents the structure of a health check request\n */\nexport interface FlowHealthCheckRequest {\n action: 'ping';\n version: '3.0';\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Response\n * The expected response structure for health check requests\n */\nexport interface FlowHealthCheckResponse {\n data: {\n status: 'active';\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Request\n * Represents the structure of a data exchange request\n */\nexport interface FlowDataExchangeRequest {\n version: '3.0';\n action: FlowActionEnum;\n screen: string;\n flow_token: string;\n data?: Record<string, any> & { error_message?: string };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Response\n * The expected response structure for data exchange requests\n */\nexport interface FlowDataExchangeResponse {\n screen?: string;\n data?: Record<string, any | { error_message?: string }>;\n}\n\n/**\n * WhatsApp Flow Endpoint - Success Screen Response\n * The expected response structure for success screen requests\n */\nexport interface FlowSuccessScreenResponse {\n screen: 'SUCCESS';\n data: {\n extension_message_response?: {\n params?: {\n flow_token: string;\n [key: string]: string;\n };\n };\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Request\n * Represents the structure of an error notification request\n */\nexport interface FlowErrorNotificationRequest {\n version: '3.0';\n action: Exclude<FlowActionEnum, FlowActionEnum.BACK>;\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Response\n * The expected response structure for error notification requests\n */\nexport interface FlowErrorNotificationResponse {\n acknowledged: boolean;\n}\n\n/**\n * WhatsApp Flow Endpoint - Comprehensive Request Object\n * A combined type that includes all possible fields from different request types\n * with all fields being optional for flexibility\n */\nexport interface FlowEndpointRequest {\n // Common fields\n version?: '3.0';\n action?: 'ping' | FlowActionEnum;\n\n screen?: string;\n flow_token?: string;\n\n data?: Record<string, any> & {\n error_key?: string;\n error_message?: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Response\n * Union type for all possible response types from a Flow endpoint\n */\nexport type FlowEndpointResponse =\n | FlowHealthCheckResponse\n | FlowDataExchangeResponse\n | FlowErrorNotificationResponse\n | FlowSuccessScreenResponse;\n\nexport interface FlowClass {\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n listFlows(wabaId: string): Promise<FlowsListResponse>;\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID\n */\n createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string;\n publish?: boolean;\n },\n ): Promise<CreateFlowResponse>;\n\n /**\n * Get Flow\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details\n */\n getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<Flow | FlowPreviewResponse>;\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update\n * @returns Promise with the success status\n */\n updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess>;\n\n /**\n * Delete Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deleteFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * List Assets (Get Flow JSON URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n listAssets(flowId: string): Promise<FlowAssetsResponse>;\n\n /**\n * Update Flow JSON\n *\n * @param flowId - The flow ID\n * @param data - The asset data including asset_type, file, and name\n * @returns Promise with the success status and validation errors\n */\n updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object;\n name?: string;\n },\n ): Promise<UpdateFlowResponse>;\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse>;\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n publishFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deprecateFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Migrate Flows\n *\n * @param wabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results\n */\n migrateFlows(\n wabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<FlowMigrationResponse>;\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as media from './types';\n\n/**\n * API for managing WhatsApp Media.\n *\n * This API allows you to:\n * - Get media information by ID\n * - Upload media files\n * - Delete media files\n * - Download media files from URLs\n */\nexport default class MediaApi extends BaseAPI implements media.MediaClass {\n private readonly endpoint = 'media';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve media information by media ID.\n *\n * @param mediaId The media ID to retrieve information for\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Media information including URL, mime type, file size, etc.\n *\n * @example\n * const mediaInfo = await whatsappClient.media.getMediaById('media_id_123');\n */\n async getMediaById(mediaId: string, phone_number_id?: string): Promise<media.MediaResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Upload a media file to WhatsApp.\n *\n * @param file The file to upload\n * @param messagingProduct The messaging product (default: 'whatsapp')\n * @returns Upload response containing the media ID\n *\n * @example\n * const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' });\n * const result = await whatsappClient.media.uploadMedia(file);\n */\n async uploadMedia(file: File, messagingProduct: string = 'whatsapp'): Promise<media.UploadMediaResponse> {\n const formData = new FormData();\n formData.append('file', file);\n formData.append('messaging_product', messagingProduct);\n formData.append('type', file.type);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Delete a media file.\n *\n * @param mediaId The media ID to delete\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.media.deleteMedia('media_id_123');\n */\n async deleteMedia(mediaId: string, phone_number_id?: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Download media from a URL.\n *\n * @param mediaUrl The URL to download media from\n * @returns Blob containing the media data\n *\n * @example\n * const blob = await whatsappClient.media.downloadMedia('https://...');\n */\n async downloadMedia(mediaUrl: string): Promise<Blob> {\n return this.sendJson(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport {\n type ComponentTypesEnum,\n HttpMethodsEnum,\n type InteractiveTypesEnum,\n MessageTypesEnum,\n WabaConfigEnum,\n} from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\n\nimport type * as m from './types';\n\n/**\n * Maps each message type to its appropriate payload type\n */\nexport type MessagePayloadType<T extends MessageTypesEnum> = T extends MessageTypesEnum.Audio\n ? m.AudioMediaObject\n : T extends MessageTypesEnum.Contacts\n ? [m.ContactObject]\n : T extends MessageTypesEnum.Document\n ? m.DocumentMediaObject\n : T extends MessageTypesEnum.Image\n ? m.ImageMediaObject\n : T extends MessageTypesEnum.Interactive\n ? m.InteractiveObject\n : T extends MessageTypesEnum.Location\n ? m.LocationObject\n : T extends MessageTypesEnum.Template\n ? m.MessageTemplateObject<ComponentTypesEnum>\n : T extends MessageTypesEnum.Sticker\n ? m.StickerMediaObject\n : T extends MessageTypesEnum.Text\n ? m.TextObject\n : T extends MessageTypesEnum.Video\n ? m.VideoMediaObject\n : T extends MessageTypesEnum.Reaction\n ? { message_id: string; emoji: string }\n : never;\n\nexport default class MessagesApi extends BaseAPI implements m.MessagesClass {\n private readonly commonMethod = HttpMethodsEnum.Post;\n private readonly commonEndpoint = 'messages';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Builds the request body for WhatsApp API messages\n * @param type The type of message to send\n * @param payload The message payload object\n * @param to The recipient's phone number\n * @param replyMessageId Optional message ID to reply to\n * @returns The formatted request body\n */\n bodyBuilder<T extends MessageTypesEnum>(\n type: T,\n payload: MessagePayloadType<T>,\n to: string,\n replyMessageId?: string,\n ) {\n const body: m.MessageRequestBody<T> = {\n messaging_product: 'whatsapp',\n recipient_type: 'individual',\n to,\n type,\n [type]: payload,\n };\n\n if (replyMessageId) body['context'] = { message_id: replyMessageId };\n\n return body;\n }\n\n /**\n * Sends a request to the WhatsApp API\n * @param body The request body to send\n * @returns Promise with the API response\n */\n private send(body: BodyInit | null): Promise<m.MessagesResponse> {\n return this.sendJson(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.commonEndpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n /**\n * Sends an audio message via WhatsApp\n * @param params The audio message parameter object\n * @returns Promise with the message response\n */\n async audio(params: m.MessageRequestParams<m.AudioMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Audio, body, to, replyMessageId)));\n }\n\n /**\n * Sends a contact card via WhatsApp\n * @param params The contact message parameter object\n * @returns Promise with the message response\n */\n async contacts(params: m.MessageRequestParams<[m.ContactObject]>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Contacts, body, to, replyMessageId)));\n }\n\n /**\n * Sends a document via WhatsApp\n * @param params The document message parameter object\n * @returns Promise with the message response\n */\n async document(params: m.MessageRequestParams<m.DocumentMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Document, body, to, replyMessageId)));\n }\n\n /**\n * Sends an image via WhatsApp\n * @param params The image message parameter object\n * @returns Promise with the message response\n */\n async image(params: m.MessageRequestParams<m.ImageMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Image, body, to, replyMessageId)));\n }\n\n /**\n * Sends an interactive message via WhatsApp\n * @param params The interactive message parameter object\n * @returns Promise with the message response\n */\n async interactive(params: m.MessageRequestParams<m.InteractiveObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId)));\n }\n\n /**\n * Sends a location via WhatsApp\n * @param params The location message parameter object\n * @returns Promise with the message response\n */\n async location(params: m.MessageRequestParams<m.LocationObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Location, body, to, replyMessageId)));\n }\n\n /**\n * Sends a sticker via WhatsApp\n * @param params The sticker message parameter object\n * @returns Promise with the message response\n */\n async sticker(params: m.MessageRequestParams<m.StickerMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Sticker, body, to, replyMessageId)));\n }\n\n /**\n * Sends a template message via WhatsApp\n * @param params The template message parameter object\n * @returns Promise with the message response\n */\n async template(\n params: m.MessageRequestParams<m.MessageTemplateObject<ComponentTypesEnum>>,\n ): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Template, body, to, replyMessageId)));\n }\n\n /**\n * Sends a text message via WhatsApp\n * @param params The text message parameter object\n * @returns Promise with the message response\n */\n async text(params: m.TextMessageParams): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, previewUrl } = params;\n\n // Handle both string and TextObject types\n const textPayload: m.TextObject =\n typeof body === 'string'\n ? { body, preview_url: previewUrl ?? true }\n : { ...body, preview_url: previewUrl ?? body.preview_url ?? true };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Text, textPayload, to, replyMessageId)));\n }\n\n /**\n * Sends a video message via WhatsApp\n * @param params The video message parameter object\n * @returns Promise with the message response\n */\n async video(params: m.MessageRequestParams<m.VideoMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Video, body, to, replyMessageId)));\n }\n\n /**\n * Updates message status (mark as read, etc.)\n * @param params The status update parameters\n * @returns Promise with the API response\n */\n async status(params: m.StatusParams): Promise<m.MessagesResponse> {\n const body = {\n messaging_product: 'whatsapp',\n status: params.status,\n message_id: params.messageId,\n ...(params.typingIndicator && { typing_indicator: params.typingIndicator }),\n };\n\n return this.send(JSON.stringify(body));\n }\n\n /**\n * Marks a message as read\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async markAsRead(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n });\n }\n\n /**\n * Shows typing indicator\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async showTypingIndicator(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n typingIndicator: { type: 'text' },\n });\n }\n\n /**\n * Sends a list interactive message\n * @param params The list interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveList(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a CTA URL interactive message\n * @param params The CTA URL interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveCtaUrl(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a location request interactive message\n * @param params The location request interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveLocationRequest(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.LocationRequest }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends an address message interactive message\n * @param params The address message interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveAddressMessage(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.AddressMessage }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reply buttons interactive message\n * @param params The reply buttons interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveReplyButtons(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a flow interactive message\n * @param params The flow interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveFlow(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reaction to a message\n * @param params The reaction parameters\n * @returns Promise with the message response\n */\n async reaction(params: m.ReactionParams): Promise<m.MessagesResponse> {\n const reactionPayload = {\n message_id: params.messageId,\n emoji: params.emoji,\n };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Reaction, reactionPayload, params.to)));\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as phoneNumber from './types';\n\n/**\n * API for managing WhatsApp Phone Numb ers.\n *\n * This API allows you to:\n * - Get phone number information by ID\n * - Get all phone numbers for a business account\n * - Request verification codes for phone numbers\n * - Verify phone numbers with codes\n */\nexport default class PhoneNumberApi extends BaseAPI implements phoneNumber.PhoneNumberClass {\n private readonly endpoint = 'phone_numbers';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get phone number information by ID.\n *\n * @param fields Optional comma-separated list of fields to include in the response\n * @returns Phone number information including verification status, quality rating, etc.\n *\n * @example\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById();\n * const phoneNumberWithFields = await whatsappClient.phoneNumber.getPhoneNumberById('display_phone_number,verified_name');\n */\n async getPhoneNumberById(fields?: string): Promise<phoneNumber.PhoneNumberResponse> {\n const queryParams = fields ? objectToQueryString({ fields }) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all phone numbers for the business account.\n *\n * @returns List of phone numbers associated with the business account\n *\n * @example\n * const phoneNumbers = await whatsappClient.phoneNumber.getPhoneNumbers();\n */\n async getPhoneNumbers(): Promise<phoneNumber.PhoneNumbersResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Request a verification code for the phone number.\n *\n * @param request Verification code request containing method and language\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.requestVerificationCode({\n * code_method: 'SMS',\n * language: 'en_US'\n * });\n */\n async requestVerificationCode(request: phoneNumber.RequestVerificationCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/request_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Verify the phone number with the received code.\n *\n * @param request Verification request containing the code\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.verifyCode({\n * code: '123456'\n * });\n */\n async verifyCode(request: phoneNumber.VerifyCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/verify_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Configure conversational automation features (Welcome Messages, Ice Breakers, Commands).\n *\n * @param request Configuration for conversational components\n * @returns Response indicating success or failure\n *\n * @example\n * // Enable welcome message\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true\n * });\n *\n * @example\n * // Configure commands\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * commands: [\n * { command_name: 'tickets', command_description: 'Book flight tickets' },\n * { command_name: 'hotel', command_description: 'Book hotel' }\n * ]\n * });\n *\n * @example\n * // Configure ice breakers (prompts)\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * prompts: ['Book a flight', 'Plan a vacation']\n * });\n *\n * @example\n * // Configure all features\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true,\n * commands: [\n * { command_name: 'tickets', command_description: 'Book flight tickets' }\n * ],\n * prompts: ['Book a flight']\n * });\n */\n async setConversationalAutomation(request: phoneNumber.ConversationalAutomationRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/conversational_automation`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Get the current configuration of conversational automation features.\n *\n * @returns Current configuration including welcome message status, commands, and prompts\n *\n * @example\n * const config = await whatsappClient.phoneNumber.getConversationalAutomation();\n * console.log(config.enable_welcome_message); // true/false\n * console.log(config.commands); // Array of commands\n * console.log(config.prompts); // Array of ice breakers\n */\n async getConversationalAutomation(): Promise<phoneNumber.ConversationalAutomationResponse> {\n const queryParams = objectToQueryString({ fields: 'conversational_automation' });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get the current throughput level for the phone number.\n *\n * Throughput represents the maximum messages per second (mps) that can be sent/received.\n * - Default: 80 mps\n * - Automatic upgrade to 1,000 mps available for eligible numbers\n * - WhatsApp Business app coexistence numbers: fixed at 5 mps\n *\n * @returns Current throughput information including the level (STANDARD, HIGH, or NOT_APPLICABLE)\n *\n * @example\n * const throughput = await whatsappClient.phoneNumber.getThroughput();\n * console.log(throughput.throughput.level); // 'STANDARD' | 'HIGH' | 'NOT_APPLICABLE'\n */\n async getThroughput(): Promise<phoneNumber.ThroughputResponse> {\n const queryParams = objectToQueryString({ fields: 'throughput' });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","export function buildFieldsQueryString(fields?: string[] | string): string {\n if (!fields) return '';\n\n let fieldParams = '';\n\n if (Array.isArray(fields)) {\n fieldParams = fields.join(',');\n } else if (typeof fields === 'string') {\n fieldParams = fields;\n } else {\n fieldParams = Object.entries(fields)\n .filter(([_, value]) => value)\n .map(([key]) => key)\n .join(',');\n }\n\n return fieldParams ? `?fields=${fieldParams}` : '';\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as bp from './types';\n\n/**\n * API for managing WhatsApp Business Profiles and profile pictures.\n *\n * This API allows you to:\n * - Get business profile information\n * - Update business profile details\n * - Upload profile pictures using a three-step process:\n * 1. Create an upload session\n * 2. Upload the image binary data\n * 3. Get the upload handle to use when updating the profile\n */\nexport default class BusinessProfileApi extends BaseAPI implements bp.BusinessProfileClass {\n private readonly endpoint = 'whatsapp_business_profile';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get your business profile information.\n *\n * Use this method to retrieve details about your WhatsApp business profile, including\n * about text, address, description, email, profile picture URL, websites, and vertical.\n *\n * @param fields Fields to be returned in the response. If not specified, all fields will be returned.\n * Possible values: about, address, description, email, profile_picture_url, websites, vertical\n * @returns The business profile information.\n *\n * @example\n * // Get all business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile();\n *\n * // Get specific business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile('about,address,email');\n *\n * // Using the BusinessProfileFieldsParam type\n * const profile = await whatsappClient.businessProfile.getBusinessProfile(['about', 'address', 'email']);\n */\n async getBusinessProfile(fields?: bp.BusinessProfileFieldsParam): Promise<bp.BusinessProfileResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${buildFieldsQueryString(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update your business profile.\n *\n * Use this method to update one or more fields of your WhatsApp business profile.\n *\n * @param updateRequest The request object containing the fields to update.\n * - messaging_product: Required. Always set to \"whatsapp\".\n * - about: Optional. Business's About text (1-139 characters).\n * - address: Optional. Business address (max 256 characters).\n * - description: Optional. Business description (max 512 characters).\n * - vertical: Optional. Business category (use BusinessVerticalEnum for type safety).\n * - email: Optional. Contact email (valid format, max 128 characters).\n * - websites: Optional. Up to 2 URLs (max 256 characters each).\n * - profile_picture_handle: Optional. Handle from upload process.\n * @returns Response indicating success or failure.\n *\n * @example\n * // Update business profile with multiple fields including vertical using enum\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * about: 'We provide excellent service',\n * email: 'contact@example.com',\n * websites: ['https://example.com'],\n * vertical: BusinessVerticalEnum.RETAIL\n * });\n */\n async updateBusinessProfile(updateRequest: bp.UpdateBusinessProfileRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(updateRequest),\n );\n }\n\n /**\n * Create an upload session for a profile picture.\n *\n * This is the first step in the profile picture upload process.\n *\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file with extension.\n * @returns Response containing the upload session ID needed for the next step.\n *\n * @example\n * // Create upload session for profile picture\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length,\n * 'image/jpeg',\n * 'profile.jpg'\n * );\n * const uploadSessionId = session.upload_session_id;\n */\n async createUploadSession(\n fileLength: number,\n fileType: string,\n fileName: string,\n ): Promise<bp.UploadSessionResponse> {\n const queryParams = objectToQueryString({\n file_length: fileLength,\n file_type: fileType,\n file_name: fileName,\n });\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `app/uploads/${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Upload media file to the upload session.\n *\n * This is the second step in the profile picture upload process.\n * Upload the binary content of the file to the previously created upload session.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @param file The binary data of the file (Buffer).\n * @returns Response indicating success or failure.\n *\n * @example\n * // Upload the actual file content\n * await whatsappClient.businessProfile.uploadMedia(\n * uploadSessionId,\n * fileBuffer\n * );\n */\n async uploadMedia(uploadId: string, file: Buffer): Promise<bp.UploadBusinessProfileResponse> {\n return this.sendJson(HttpMethodsEnum.Post, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], file);\n }\n\n /**\n * Get the upload handle information.\n *\n * This is the third step in the profile picture upload process.\n * After uploading the file, get the handle to use when updating the profile.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @returns Response containing the upload handle information.\n *\n * @example\n * // Complete profile picture update process\n * // 1. Create upload session\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length, 'image/jpeg', 'profile.jpg'\n * );\n *\n * // 2. Upload the image data\n * await whatsappClient.businessProfile.uploadMedia(\n * session.upload_session_id, fileBuffer\n * );\n *\n * // 3. Get the handle for the uploaded file\n * const handleInfo = await whatsappClient.businessProfile.getUploadHandle(\n * session.upload_session_id\n * );\n *\n * // 4. Update profile with new picture and business information\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * profile_picture_handle: handleInfo.handle,\n * vertical: BusinessVerticalEnum.RESTAURANT,\n * about: 'Delicious food served daily'\n * });\n */\n async getUploadHandle(uploadId: string): Promise<bp.UploadHandle> {\n return this.sendJson(HttpMethodsEnum.Get, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../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","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as registration from './types';\n\n/**\n * API for managing WhatsApp Business Account registration.\n *\n * This API allows you to:\n * - Register a WhatsApp Business Account with a PIN\n * - Deregister a WhatsApp Business Account\n */\nexport default class RegistrationApi extends BaseAPI implements registration.RegistrationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Register a WhatsApp Business Account using a PIN.\n *\n * @param pin The registration PIN received via SMS or voice call\n * @param dataLocalizationRegion Optional data localization region\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.register('123456', DataLocalizationRegionEnum.Asia);\n */\n async register(pin: string, dataLocalizationRegion?: DataLocalizationRegionEnum): Promise<ResponseSuccess> {\n const body: registration.RegistrationRequest = {\n messaging_product: 'whatsapp',\n pin,\n ...(dataLocalizationRegion && { data_localization_region: dataLocalizationRegion }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/register`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Deregister a WhatsApp Business Account.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.deregister();\n */\n async deregister(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/deregister`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponsePagination, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../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","import { CategoryEnum } from '../../../types/enums';\nimport type {\n ComponentTypes,\n MediaCarouselCard,\n ProductCarouselCard,\n TemplateBody,\n TemplateButton,\n TemplateButtons,\n TemplateFooter,\n TemplateHeader,\n TemplateRequestBody,\n} from '../types';\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';\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,\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 });\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' }],\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 ],\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 ],\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 ],\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 });\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: MediaCarouselCard[] = [];\n options.cards.forEach((card, index) => {\n const cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[] = [];\n\n // Add header (media)\n cardComponents.push({\n type: 'HEADER' as const,\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) as TemplateButtons[]));\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 });\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 ],\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: ProductCarouselCard[] = options.cards.map((card, index) => ({\n card_index: index,\n components: [\n {\n type: 'HEADER' as const,\n format: 'PRODUCT' as const,\n example: {\n header_handle: [card.product_retailer_id],\n },\n },\n ],\n }));\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n });\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 ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as twoStepVerification from './types';\n\n/**\n * API for managing WhatsApp Two-Step Verification.\n *\n * This API allows you to:\n * - Set a two-step verification PIN code\n * - Manage two-step verification settings\n */\nexport default class TwoStepVerificationApi extends BaseAPI implements twoStepVerification.TwoStepVerificationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Set a two-step verification PIN code.\n *\n * @param pin The PIN code to set for two-step verification (6-digit numeric string)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.twoStepVerification.setTwoStepVerificationCode('123456');\n */\n async setTwoStepVerificationCode(pin: string): Promise<ResponseSuccess> {\n const body = {\n pin,\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\n\nimport type * as waba from './types';\n\n/**\n * API for managing WhatsApp Business Account (WABA).\n *\n * This API allows you to:\n * - Get WABA account information\n * - Manage WABA subscriptions\n * - Subscribe/unsubscribe from WABA webhooks\n * - Update subscription settings\n */\nexport default class WabaApi extends BaseAPI implements waba.WABAClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve WhatsApp Business Account information.\n *\n * @param fields Optional array of specific fields to retrieve\n * @returns WABA account information including status, health, verification status, etc.\n *\n * @example\n * const account = await whatsappClient.waba.getWabaAccount(['id', 'name', 'status']);\n */\n async getWabaAccount(fields?: waba.WabaAccountFieldsParam): Promise<waba.WabaAccount> {\n const queryString = buildFieldsQueryString(fields)?.replace(/,/g, '%2C');\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all WABA subscriptions for the business account.\n *\n * @returns List of all subscribed apps and their configurations\n *\n * @example\n * const subscriptions = await whatsappClient.waba.getAllWabaSubscriptions();\n */\n async getAllWabaSubscriptions(): Promise<waba.WabaSubscriptions> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update WABA subscription configuration.\n *\n * @param params Configuration parameters including callback URI and verify token\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.updateWabaSubscription({\n * override_callback_uri: 'https://example.com/webhook',\n * verify_token: 'your_verify_token'\n * });\n */\n async updateWabaSubscription({\n override_callback_uri,\n verify_token,\n }: waba.UpdateWabaSubscription): Promise<ResponseSuccess> {\n const body = {\n override_callback_uri,\n verify_token,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unsubscribe from WABA webhooks.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.unsubscribeFromWaba();\n */\n async unsubscribeFromWaba(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","export function printLogo() {\n // 테스트 환경에서는 로고를 출력하지 않음\n if (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n (typeof global !== 'undefined' && (global as any).__VITEST__)\n ) {\n return;\n }\n\n console.log(\n '\\x1b[36m%s\\x1b[0m',\n `\n██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗\n██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║\n╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║\n ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n`,\n );\n}\n","import { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport { generateEncryption, EncryptionKeyPair } from '../../utils/flowEncryptionUtils';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nimport {\n BlockUsersApi,\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MediaApi,\n MessageApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { printLogo } from '../../utils/logoConsole';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WhatsApp SDK Main Class following official patterns\n * Provides unified access to WhatsApp Cloud API and Flows API\n */\nexport default class WhatsApp {\n config: WabaConfigType;\n requester: Readonly<Requester>;\n blockUsers: BlockUsersApi;\n messages: MessageApi;\n media: MediaApi;\n phoneNumbers: PhoneNumberApi;\n twoStepVerification: TwoStepVerificationApi;\n flows: FlowApi;\n businessProfile: BusinessProfileApi;\n templates: TemplateApi;\n encryption: EncryptionApi;\n qrCode: QrCodeApi;\n registration: RegistrationApi;\n waba: WabaApi;\n\n constructor(config?: WhatsAppConfig) {\n printLogo();\n this.config = importConfig(config);\n\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.getUserAgent(),\n );\n\n this.blockUsers = new BlockUsersApi(this.config, this.requester);\n this.messages = new MessageApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.flows = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n\n LOGGER.log('\\n' + formatConfigTable(this.config));\n }\n\n /**\n * Runtime configuration updates following official patterns\n */\n updateTimeout(timeout: number): void {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = timeout;\n if ('updateTimeout' in this.requester) {\n (this.requester as any).updateTimeout(timeout);\n }\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateSenderNumberId(phoneNumberId: number): void {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Sender number ID updated to ${phoneNumberId}`);\n }\n\n updateAccessToken(accessToken: string): void {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n if ('updateAccessToken' in this.requester) {\n (this.requester as any).updateAccessToken(accessToken);\n }\n LOGGER.log('Access token updated');\n }\n\n /**\n * Get SDK version\n */\n version(): string {\n return getVersion();\n }\n\n /**\n * Static enums access\n */\n static get Enums() {\n return SDKEnums;\n }\n\n /**\n * Get User-Agent string\n */\n getUserAgent(): string {\n return getUserAgent();\n }\n\n /**\n * Generate RSA encryption key pair for WhatsApp Business Flow API\n *\n * This method generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Optional passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from config\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n *\n * @example\n * ```typescript\n * const wa = new WhatsApp();\n *\n * // Uses FLOW_API_PASSPHRASE from environment/config\n * const keys = wa.generateEncryption();\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n *\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n * ```\n */\n generateEncryption(passphrase?: string): EncryptionKeyPair {\n // If no passphrase provided, try to use from config\n const effectivePassphrase = passphrase || this.config[SDKEnums.WabaConfigEnum.Passphrase];\n return generateEncryption(effectivePassphrase);\n }\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '../api/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 crypto from 'crypto';\n\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { decryptFlowRequest, encryptFlowResponse } from '../../../utils/flowEncryptionUtils';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport WhatsApp from '../../whatsapp/WhatsApp';\nimport { MessageWebhookValue, StatusWebhook, StatusWebhookValue, WebhookValue, WhatsAppMessage } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Processed message with metadata for handlers\n */\nexport type ProcessedMessage = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n profileName: string;\n message: WhatsAppMessage;\n /**\n * The message ID extracted from the appropriate location based on message type.\n * For most messages, this comes from message.id\n * For certain types like nfm_reply, this comes from message.context.id\n */\n messageId: string;\n};\n\n/**\n * Processed status with metadata for handlers\n */\nexport type ProcessedStatus = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n status: StatusWebhook;\n};\n\n// Type-specific processed messages for specialized handlers\nexport type TextProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Text }>;\n};\n\nexport type ImageProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Image }>;\n};\n\nexport type VideoProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Video }>;\n};\n\nexport type AudioProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Audio }>;\n};\n\nexport type DocumentProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Document }>;\n};\n\nexport type StickerProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Sticker }>;\n};\n\nexport type InteractiveProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Interactive }>;\n};\n\nexport type ButtonProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Button }>;\n};\n\nexport type LocationProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Location }>;\n};\n\nexport type ContactsProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Contacts }>;\n};\n\nexport type ReactionProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Reaction }>;\n};\n\nexport type OrderProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Order }>;\n};\n\nexport type SystemProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.System }>;\n};\n\nexport type MessageHandler = (whatsapp: WhatsApp, processed: ProcessedMessage) => void | Promise<void>;\nexport type StatusHandler = (whatsapp: WhatsApp, processed: ProcessedStatus) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n// Type-specific handlers for specialized methods\nexport type TextMessageHandler = (whatsapp: WhatsApp, processed: TextProcessedMessage) => void | Promise<void>;\nexport type ImageMessageHandler = (whatsapp: WhatsApp, processed: ImageProcessedMessage) => void | Promise<void>;\nexport type VideoMessageHandler = (whatsapp: WhatsApp, processed: VideoProcessedMessage) => void | Promise<void>;\nexport type AudioMessageHandler = (whatsapp: WhatsApp, processed: AudioProcessedMessage) => void | Promise<void>;\nexport type DocumentMessageHandler = (whatsapp: WhatsApp, processed: DocumentProcessedMessage) => void | Promise<void>;\nexport type StickerMessageHandler = (whatsapp: WhatsApp, processed: StickerProcessedMessage) => void | Promise<void>;\nexport type InteractiveMessageHandler = (\n whatsapp: WhatsApp,\n processed: InteractiveProcessedMessage,\n) => void | Promise<void>;\nexport type ButtonMessageHandler = (whatsapp: WhatsApp, processed: ButtonProcessedMessage) => void | Promise<void>;\nexport type LocationMessageHandler = (whatsapp: WhatsApp, processed: LocationProcessedMessage) => void | Promise<void>;\nexport type ContactsMessageHandler = (whatsapp: WhatsApp, processed: ContactsProcessedMessage) => void | Promise<void>;\nexport type ReactionMessageHandler = (whatsapp: WhatsApp, processed: ReactionProcessedMessage) => void | Promise<void>;\nexport type OrderMessageHandler = (whatsapp: WhatsApp, processed: OrderProcessedMessage) => void | Promise<void>;\nexport type SystemMessageHandler = (whatsapp: WhatsApp, processed: SystemProcessedMessage) => void | Promise<void>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n statusHandler?: StatusHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n const body = await request.json();\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.warn(errorMsg);\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Create a standard ping response for WhatsApp Flow health checks\n * @returns Flow ping response object\n */\nexport function createFlowPingResponse() {\n return {\n version: '3.0',\n data: { status: 'active' },\n };\n}\n\n/**\n * Create a standard error response for WhatsApp Flow error notifications\n * @returns Acknowledgement response for error notification\n */\nexport function createFlowErrorResponse() {\n return {\n data: {\n acknowledged: true,\n },\n };\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature');\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n\n // Decrypt the request and get decrypted AES key and IV\n const { decryptedBody, aesKeyBuffer, initialVectorBuffer } = decryptFlowRequest(data, config);\n\n // Determine flow type\n const isPing = isFlowPingRequest(decryptedBody);\n const isError = isFlowErrorRequest(decryptedBody);\n const isDataExchange = isFlowDataExchangeRequest(decryptedBody);\n\n let flowType: FlowTypeEnum;\n if (isPing) {\n flowType = FlowTypeEnum.Ping;\n } else if (isError) {\n flowType = FlowTypeEnum.Error;\n } else if (isDataExchange) {\n flowType = FlowTypeEnum.Change;\n } else {\n flowType = FlowTypeEnum.All;\n }\n\n // Get the flow handler based on type\n let handler = flowHandlers.get(flowType);\n\n // For Ping and Error, use default handlers if not registered\n if (!handler) {\n if (flowType === FlowTypeEnum.Ping) {\n handler = () => createFlowPingResponse();\n } else if (flowType === FlowTypeEnum.Error) {\n handler = () => createFlowErrorResponse();\n } else {\n // For Change and other types, try All handler as fallback\n handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow type:', { flowType, action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n }\n }\n\n // Call the user's handler for the flow type\n const result = await handler(whatsapp, decryptedBody);\n\n // Return response based on flow type\n if (isError) {\n LOGGER.warn('Flow error notification received', { error: decryptedBody.data });\n\n // If user handler didn't return a response, use default acknowledgement\n const errorResponse = result || createFlowErrorResponse();\n\n return new Response(JSON.stringify(errorResponse), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Both ping and data_exchange responses need to be encrypted\n if (isPing || isDataExchange) {\n // Encrypt the response using decrypted AES key and IV\n const encryptedResponse = encryptFlowResponse(result, aesKeyBuffer, initialVectorBuffer);\n\n // Meta expects the encrypted response as a plain base64 string (not wrapped in JSON)\n return new Response(encryptedResponse, {\n status: 200,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Extract message ID based on message type\n * Some message types (like nfm_reply) have ID in context instead of root level\n */\nfunction extractMessageId(message: WhatsAppMessage): string {\n // If message has id at root level, use it\n if (message.id) {\n return message.id;\n }\n\n // For interactive and button messages, check context.id\n if (message.type === MessageTypesEnum.Interactive || message.type === MessageTypesEnum.Button) {\n const msgWithContext = message as any;\n if (msgWithContext.context?.id) {\n return msgWithContext.context.id;\n }\n }\n\n // Fallback to empty string if no ID found\n return '';\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n statusHandler?: StatusHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n\n // Handle status webhooks\n if ('statuses' in value && value.statuses) {\n const statusValue = value as StatusWebhookValue;\n for (const status of statusValue.statuses) {\n const processed: ProcessedStatus = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n status,\n };\n\n await executeStatusHandler(handlers.statusHandler, whatsapp, processed);\n }\n return;\n }\n\n // Handle message webhooks\n if ('messages' in value && value.messages) {\n const messageValue = value as MessageWebhookValue;\n const profileName = messageValue.contacts?.[0]?.profile?.name || '';\n\n for (const message of messageValue.messages) {\n const processed: ProcessedMessage = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n message,\n messageId: extractMessageId(message),\n };\n\n const messageType = message.type;\n\n // Execute handlers in sequence\n await executeMessageHandler(handlers.preProcessHandler, whatsapp, processed, 'pre-process');\n await executeMessageHandler(handlers.messageHandlers.get(messageType), whatsapp, processed, messageType);\n await executeMessageHandler(handlers.postProcessHandler, whatsapp, processed, 'post-process');\n }\n }\n}\n\nasync function executeMessageHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed);\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: processed.messageId });\n }\n }\n}\n\nasync function executeStatusHandler(\n handler: StatusHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedStatus,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed);\n } catch (error) {\n LOGGER.error('Error in status handler:', { error, statusId: processed.status.id });\n }\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\n\nimport {\n AudioMessageHandler,\n ButtonMessageHandler,\n ContactsMessageHandler,\n DocumentMessageHandler,\n FlowHandler,\n ImageMessageHandler,\n InteractiveMessageHandler,\n LocationMessageHandler,\n MessageHandler,\n OrderMessageHandler,\n ReactionMessageHandler,\n StatusHandler,\n StickerMessageHandler,\n SystemMessageHandler,\n TextMessageHandler,\n VideoMessageHandler,\n processFlowRequest,\n processWebhookMessages,\n} from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private statusHandler: StatusHandler | undefined = undefined;\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n statusHandler: this.statusHandler,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'text/plain';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n if (type === ('statuses' as MessageTypesEnum)) {\n throw new Error(\n 'MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)',\n );\n }\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onStatus(handler: StatusHandler): void {\n this.statusHandler = handler;\n LOGGER.log('Registered status handler');\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n // ============================================================================\n // Specialized type-safe message handlers\n // ============================================================================\n\n /**\n * Register a handler for text messages\n * @param handler Type-safe handler that receives text messages with guaranteed text field\n */\n onText(handler: TextMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Text, handler as MessageHandler);\n LOGGER.log('Registered text message handler');\n }\n\n /**\n * Register a handler for image messages\n * @param handler Type-safe handler that receives image messages with guaranteed image field\n */\n onImage(handler: ImageMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Image, handler as MessageHandler);\n LOGGER.log('Registered image message handler');\n }\n\n /**\n * Register a handler for video messages\n * @param handler Type-safe handler that receives video messages with guaranteed video field\n */\n onVideo(handler: VideoMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Video, handler as MessageHandler);\n LOGGER.log('Registered video message handler');\n }\n\n /**\n * Register a handler for audio messages\n * @param handler Type-safe handler that receives audio messages with guaranteed audio field\n */\n onAudio(handler: AudioMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Audio, handler as MessageHandler);\n LOGGER.log('Registered audio message handler');\n }\n\n /**\n * Register a handler for document messages\n * @param handler Type-safe handler that receives document messages with guaranteed document field\n */\n onDocument(handler: DocumentMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Document, handler as MessageHandler);\n LOGGER.log('Registered document message handler');\n }\n\n /**\n * Register a handler for sticker messages\n * @param handler Type-safe handler that receives sticker messages with guaranteed sticker field\n */\n onSticker(handler: StickerMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Sticker, handler as MessageHandler);\n LOGGER.log('Registered sticker message handler');\n }\n\n /**\n * Register a handler for interactive messages (buttons, lists, flows)\n * @param handler Type-safe handler that receives interactive messages with guaranteed interactive field\n */\n onInteractive(handler: InteractiveMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Interactive, handler as MessageHandler);\n LOGGER.log('Registered interactive message handler');\n }\n\n /**\n * Register a handler for button messages\n * @param handler Type-safe handler that receives button messages with guaranteed button field\n */\n onButton(handler: ButtonMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Button, handler as MessageHandler);\n LOGGER.log('Registered button message handler');\n }\n\n /**\n * Register a handler for location messages\n * @param handler Type-safe handler that receives location messages with guaranteed location field\n */\n onLocation(handler: LocationMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Location, handler as MessageHandler);\n LOGGER.log('Registered location message handler');\n }\n\n /**\n * Register a handler for contact messages\n * @param handler Type-safe handler that receives contact messages with guaranteed contacts field\n */\n onContacts(handler: ContactsMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Contacts, handler as MessageHandler);\n LOGGER.log('Registered contacts message handler');\n }\n\n /**\n * Register a handler for reaction messages\n * @param handler Type-safe handler that receives reaction messages with guaranteed reaction field\n */\n onReaction(handler: ReactionMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Reaction, handler as MessageHandler);\n LOGGER.log('Registered reaction message handler');\n }\n\n /**\n * Register a handler for order messages\n * @param handler Type-safe handler that receives order messages with guaranteed order field\n */\n onOrder(handler: OrderMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Order, handler as MessageHandler);\n LOGGER.log('Registered order message handler');\n }\n\n /**\n * Register a handler for system messages\n * @param handler Type-safe handler that receives system messages with guaranteed system field\n */\n onSystem(handler: SystemMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.System, handler as MessageHandler);\n LOGGER.log('Registered system message handler');\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n","import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Generic request/response interfaces for framework abstraction\nexport interface BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query?: Record<string, any> | URLSearchParams;\n rawBody?: any;\n}\n\nexport interface BaseResponse<T = any> {\n status(code: number): T;\n json?(data: any): T | void;\n send?(data?: any): T | void;\n setHeader?(name: string, value: string): void;\n}\n\n// Base configuration interface\nexport interface BaseWebhookConfig extends WhatsAppConfig {\n // Framework-specific configs can extend this\n}\n\n// Response result interface for consistent return types\nexport interface WebhookResult {\n status: number;\n headers: Record<string, string>;\n body: any;\n}\n\n/**\n * Abstract base class for framework-agnostic webhook handlers\n * Provides common architecture and functionality across all frameworks\n */\nexport abstract class BaseWebhookHandler<TRequest extends BaseRequest, TResponse extends BaseResponse> {\n protected processor: WebhookProcessor;\n\n constructor(config: BaseWebhookConfig) {\n this.processor = new WebhookProcessor(config);\n }\n\n /**\n * Abstract method for handling GET requests (webhook verification)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleGet(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling POST requests (webhook processing)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handlePost(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling flow requests\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleFlow(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Common webhook verification logic\n */\n protected async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResult> {\n return await this.processor.processVerification(mode, token, challenge);\n }\n\n /**\n * Common webhook processing logic\n */\n protected async processWebhook(request: Request): Promise<WebhookResult> {\n return await this.processor.processWebhook(request);\n }\n\n /**\n * Common flow processing logic\n */\n protected async processFlow(request: Request): Promise<WebhookResult> {\n return await this.processor.processFlow(request);\n }\n\n /**\n * Helper to construct full URL from headers and path\n */\n protected constructFullUrl(headers: Record<string, string | string[] | undefined>, url: string = ''): string {\n return constructFullUrl(headers, url);\n }\n\n /**\n * Helper to apply result headers to response\n */\n protected applyHeaders(result: WebhookResult, res: TResponse): void {\n if (res.setHeader) {\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader!(key, value);\n });\n }\n }\n\n /**\n * Auto-routing method handler that dispatches based on request method\n */\n protected async autoRoute(req: TRequest, res: TResponse, ...args: any[]): Promise<any> {\n const method = req.method?.toUpperCase();\n\n switch (method) {\n case 'GET':\n return await this.handleGet(req, res, ...args);\n case 'POST':\n return await this.handlePost(req, res, ...args);\n default:\n if (res.status && res.json) {\n return res.status(405).json({ error: 'Method Not Allowed' });\n }\n throw new Error('Method Not Allowed');\n }\n }\n\n /**\n * Get the processor instance for handler registration\n */\n get webhookProcessor(): WebhookProcessor {\n return this.processor;\n }\n\n /**\n * Abstract method to return the clean handler object\n * Each framework implements this to return their specific handler structure\n */\n abstract getHandlers(): {\n GET: (...args: any[]) => Promise<any>;\n POST: (...args: any[]) => Promise<any>;\n webhook: (...args: any[]) => Promise<any>;\n flow: (...args: any[]) => Promise<any>;\n processor: WebhookProcessor;\n };\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from '../handler';\nimport { WebhookResponse } from '../../WebhookProcessor';\n\n// Express-like interfaces to avoid direct Express dependency\nexport interface ExpressRequest extends BaseRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Record<string, any>;\n rawBody?: any;\n}\n\nexport interface ExpressResponse extends BaseResponse<ExpressResponse> {\n status(code: number): ExpressResponse;\n json(data: any): ExpressResponse;\n send(data?: any): ExpressResponse;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextFunction {\n (error?: any): void;\n}\n\nexport interface ExpressWebhookConfig extends BaseWebhookConfig {\n path?: string;\n}\n\n/**\n * Express-specific webhook handler extending the base handler\n */\nclass ExpressWebhookHandler extends BaseWebhookHandler<ExpressRequest, ExpressResponse> {\n constructor(config: ExpressWebhookConfig) {\n super(config);\n }\n\n protected async handleGet(req: ExpressRequest, res: ExpressResponse, next: NextFunction): Promise<WebhookResponse> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(error);\n throw error;\n }\n }\n\n protected async handlePost(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(error);\n throw error;\n }\n }\n\n protected async handleFlow(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody || (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(error);\n throw error;\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleGet(req, res, next),\n POST: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handlePost(req, res, next),\n\n // Auto-routing webhook handler\n webhook: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.autoRoute(req, res, next),\n\n // Flow handler\n flow: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleFlow(req, res, next),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\nexport function expressWebhookHandler(config: ExpressWebhookConfig) {\n const handler = new ExpressWebhookHandler(config);\n return handler.getHandlers();\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from '../handler';\nimport { WebhookResponse } from '../../WebhookProcessor';\n\n// Next.js specific interfaces\nexport interface BaseApiRequest extends BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Partial<Record<string, string | string[]>>;\n rawBody?: any;\n}\n\nexport interface BaseApiResponse extends BaseResponse {\n status(code: number): any;\n json(data: any): void | any;\n send(data?: any): void | any;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextJsWebhookConfig extends BaseWebhookConfig {\n // Next.js specific config can be added here\n}\n\n/**\n * Next.js Page Router webhook handler extending the base handler\n */\nclass NextJsWebhookHandler<\n TRequest extends BaseApiRequest,\n TResponse extends BaseApiResponse,\n> extends BaseWebhookHandler<TRequest, TResponse> {\n constructor(config: NextJsWebhookConfig) {\n super(config);\n }\n\n // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest, preserveRaw: boolean = false): Promise<void> {\n if (req.method === 'POST' && !req.body) {\n const chunks: Buffer[] = [];\n\n // Check if req is a stream (has Symbol.asyncIterator)\n if (typeof (req as any)[Symbol.asyncIterator] === 'function') {\n for await (const chunk of req as any) {\n chunks.push(chunk);\n }\n\n const body = Buffer.concat(chunks).toString();\n\n // Store raw body if requested (for signature verification)\n if (preserveRaw) {\n req.rawBody = body;\n }\n\n // Only attempt to parse if there's actual content\n if (body.trim()) {\n try {\n req.body = JSON.parse(body);\n } catch (error) {\n throw new Error('Invalid JSON in request body');\n }\n } else {\n req.body = {};\n }\n }\n }\n }\n\n protected async handleGet(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook verification error:', error);\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n }\n\n protected async handlePost(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req);\n } catch (error) {\n console.error('Webhook processing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n res.status(400).json({ error: 'Invalid JSON' });\n throw error;\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook processing error:', error);\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n }\n\n protected async handleFlow(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Parse body and preserve raw body for signature verification\n await this.parseRequestBody(req, true);\n } catch (error) {\n console.error('Flow body parsing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n res.status(400).json({ error: 'Invalid JSON' });\n throw error;\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody || (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n\n // Return result for user's custom handling\n return result;\n } catch (error) {\n console.error('Flow error:', error);\n res.status(500).json({ error: 'Internal Server Error' });\n throw error;\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: TRequest, res: TResponse) => this.handleGet(req, res),\n POST: (req: TRequest, res: TResponse) => this.handlePost(req, res),\n\n // Auto-routing webhook handler\n webhook: (req: TRequest, res: TResponse) => this.autoRoute(req, res),\n\n // Flow handler\n flow: (req: TRequest, res: TResponse) => this.handleFlow(req, res),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\n// Next.js Pages Router webhook handler\nexport function nextjsPagesWebhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n return handler.getHandlers();\n}\n","import { WhatsAppConfig } from '../../../../types/config';\nimport { WebhookProcessor } from '../../WebhookProcessor';\n\n// Define Next.js types locally to avoid requiring Next.js as a dependency\nexport interface NextRequest extends Request {\n nextUrl: {\n searchParams: URLSearchParams;\n };\n}\n\nexport interface NextResponse {\n json(data: any): NextResponse;\n}\n\nexport interface NextJsAppWebhookConfig extends WhatsAppConfig {\n // App Router specific config (currently none, but interface reserved for future use)\n}\n\n// Next.js App Router webhook handler\nexport function nextjsAppWebhookHandler(config: NextJsAppWebhookConfig) {\n const processor = new WebhookProcessor(config);\n\n return {\n // Clean GET/POST handlers following whatsapp-api-js methodology\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n\n // Return plain text response for webhook verification\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n\n // Return JSON response for webhook processing\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n // Legacy webhook object for backward compatibility\n webhook: {\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n },\n\n // Flow handler for App Router\n flow: {\n GET: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow GET error:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow POST error:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n },\n\n // Expose processor for handler registration\n processor,\n };\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","import type { ResponseSuccess } from '../../../types/request';\n\n/**\n * WhatsApp Business Account subscription configuration\n */\nexport type WabaSubscription = {\n whatsapp_business_api_data: {\n id: string;\n link: string;\n name: string;\n category: string;\n };\n override_callback_uri?: string;\n};\n\n/**\n * Parameters for updating WABA subscription\n */\nexport interface UpdateWabaSubscription {\n override_callback_uri: string;\n verify_token: string;\n}\n\n/**\n * Response containing all WABA subscriptions\n */\nexport interface WabaSubscriptions {\n data: Array<WabaSubscription>;\n}\n\n/**\n * WABA account review status enumeration\n */\nexport enum WabaAccountReviewStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * WABA health status for message sending capability\n */\nexport enum WabaHealthStatusCanSendMessage {\n Blocked = 'BLOCKED',\n Limited = 'LIMITED',\n Available = 'AVAILABLE',\n}\n\n/**\n * WABA account status enumeration\n */\nexport enum WabaAccountStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * Business verification status enumeration\n */\nexport enum WabaBusinessVerificationStatus {\n Verified = 'verified',\n PendingSubmission = 'pending_submission',\n Unverified = 'unverified',\n Rejected = 'rejected',\n}\n\n/**\n * WABA health status error details\n */\nexport interface WabaHealthStatusError {\n error_code?: number;\n error_description?: string;\n possible_solution?: string;\n}\n\n/**\n * WABA health status entity information\n */\nexport interface WabaHealthStatusEntity {\n entity_type?: string;\n id?: string;\n can_send_message?: string;\n errors?: WabaHealthStatusError[];\n}\n\n/**\n * Overall WABA health status\n */\nexport interface WabaHealthStatus {\n can_send_message?: WabaHealthStatusCanSendMessage;\n entities?: WabaHealthStatusEntity[];\n}\n\n/**\n * WhatsApp Business Account information\n */\nexport interface WabaAccount {\n account_review_status?: WabaAccountReviewStatus;\n id?: string;\n health_status?: WabaHealthStatus;\n status?: WabaAccountStatus;\n business_verification_status?: WabaBusinessVerificationStatus;\n message_template_namespace?: string;\n name?: string;\n ownership_type?: string;\n currency?: string;\n}\n\n/**\n * Available fields for WABA account queries\n */\nexport type WabaAccountFields =\n | 'id'\n | 'name'\n | 'account_review_status'\n | 'auth_international_rate_eligibility'\n | 'business_verification_status'\n | 'country'\n | 'currency'\n | 'health_status'\n | 'status'\n | 'ownership_type'\n | 'message_template_namespace';\n\n/**\n * Parameter type for specifying which WABA account fields to retrieve\n */\nexport type WabaAccountFieldsParam = WabaAccountFields[];\n\n/**\n * Interface defining all WABA API methods\n */\nexport interface WABAClass {\n getWabaAccount(fields?: WabaAccountFieldsParam): Promise<WabaAccount>;\n getAllWabaSubscriptions(): Promise<WabaSubscriptions>;\n updateWabaSubscription(params: UpdateWabaSubscription): Promise<ResponseSuccess>;\n unsubscribeFromWaba(): Promise<ResponseSuccess>;\n}\n"],"mappings":"41BAAA,IAAY,EAAA,SAAA,EAAL,OACH,GAAA,eAAA,iBACA,EAAA,UAAA,YACA,EAAA,QAAA,iBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,SAAA,WACA,EAAA,QAAA,UACA,EAAA,SAAA,kBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,IAAA,MACA,EAAA,KAAA,OACA,EAAA,IAAA,MACA,EAAA,OAAA,gBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,MAAA,QACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,MAAA,QACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,QAAA,UACA,EAAA,SAAA,WACA,EAAA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