{"version":3,"file":"index.mjs","names":["LOGGER","LOGGER","LOGGER","LOGGER","LOGGER","MessageApi","SDKEnums","LOGGER","handlerCache","getCacheKey","handlerCache","getCacheKey","crypto"],"sources":["../src/config/defaults.ts","../src/types/base.ts","../src/types/enums.ts","../src/utils/objectToQueryString.ts","../src/utils/isMetaError.ts","../src/utils/validate.ts","../src/api/blockUsers/BlockUsersApi.ts","../src/api/business/BusinessApi.ts","../src/api/calling/CallingApi.ts","../src/api/commerce/CommerceApi.ts","../src/api/encryption/EncryptionApi.ts","../src/api/flow/FlowApi.ts","../src/api/flow/types/common.ts","../src/api/groups/GroupsApi.ts","../src/api/marketingMessages/MarketingMessagesApi.ts","../src/api/media/MediaApi.ts","../src/api/messageHistory/MessageHistoryApi.ts","../src/api/messages/MessageApi.ts","../src/api/payments/PaymentsApi.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/solutions/SolutionsApi.ts","../src/api/template/factories/index.ts","../src/api/template/TemplateApi.ts","../src/api/twoStepVerification/TwoStepVerificationApi.ts","../src/api/waba/WabaApi.ts","../src/api/waba/types/common.ts","../src/utils/logger.ts","../src/config/importConfig.ts","../src/utils/configTable.ts","../src/utils/flowEncryptionUtils.ts","../src/utils/http/httpsClient.ts","../src/utils/http/request.ts","../src/utils/logoConsole.ts","../src/utils/version.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-app/nextjs-app.ts","../src/core/webhook/frameworks/nextjs-page/nextjs-page.ts","../src/core/webhook/utils/extractMessageText.ts","../src/core/webhook/utils/generateXHub256Sig.ts","../src/core/webhook/utils/messageHelpers.ts","../src/types/constants.ts"],"sourcesContent":["export const DEFAULT_CLOUD_API_VERSION = 'v23.0';\nexport const DEFAULT_LISTENER_PORT = 3000;\nexport const DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nexport const DEFAULT_REQUEST_TIMEOUT = 20000;\n\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 3;\nexport const DEFAULT_RETRY_INITIAL_DELAY_MS = 1000;\nexport const DEFAULT_RETRY_BACKOFF = 'exponential';\n\nexport const GRAPH_API_HOST = 'graph.facebook.com';\nexport const GRAPH_API_PROTOCOL = 'https:';\n\nexport const WHATSAPP_MESSAGING_PRODUCT = 'whatsapp';\n","import type { WabaConfigType } from './config';\n\nexport declare class BaseClass {\n    constructor(config: WabaConfigType);\n}\n\nimport type { HttpMethodsEnum } from './enums';\nimport type { RequesterClass, UrlEncodedFormBody } 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: UrlEncodedFormBody,\n    ): Promise<T> {\n        return this.client.sendUrlEncodedForm<T>(method, endpoint, timeout, body);\n    }\n}\n","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    CatalogMessage = 'catalog_message',\n    CallPermissionRequest = 'call_permission_request',\n    CtaUrl = 'cta_url',\n    Carousel = 'carousel',\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    PhoneNumber = 'PHONE_NUMBER',\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","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","export type MetaErrorData = {\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\nexport interface MetaError extends Error {\n    error: MetaErrorData;\n}\n\nexport const WHATSAPP_ERROR_CODES = [\n    0, 1, 2, 3, 4, 10, 33, 100, 190, 200, 299, 368, 613, 80007, 130429, 130472, 130497, 131000, 131005, 131008, 131009,\n    131016, 131020, 131021, 131026, 131030, 131031, 131037, 131041, 131042, 131044, 131045, 131047, 131048, 131049,\n    131050, 131051, 131052, 131053, 131055, 131056, 131057, 131059, 131201, 131202, 131203, 131204, 131207, 131208,\n    131209, 131210, 131211, 131212, 131213, 131214, 131215, 132000, 132001, 132005, 132007, 132008, 132012, 132015,\n    132016, 132068, 132069, 133000, 133004, 133005, 133006, 133008, 133009, 133010, 133015, 133016, 134011, 134100,\n    134101, 134102, 135000, 137000, 138000, 138001, 138002, 138003, 138004, 138005, 138006, 138007, 138009, 138012,\n    138013, 138018, 139000, 139001, 139002, 139003, 139004, 139100, 139101, 139102, 139103, 200005, 200006, 200007,\n    1752041, 2388001, 2388012, 2388019, 2388040, 2388047, 2388072, 2388073, 2388091, 2388093, 2388103, 2388293, 2388299,\n    2494100, 2593079, 2593085, 2593107, 2593108,\n] as const;\n\nconst WHATSAPP_ERROR_CODE_SET = new Set<number>(WHATSAPP_ERROR_CODES);\n\nexport type ApiPermissionErrorCode = number;\nexport type WhatsAppErrorCode = (typeof WHATSAPP_ERROR_CODES)[number] | ApiPermissionErrorCode;\n\nexport const AUTHORIZATION_ERROR_CODES = [0, 3, 10, 190] as const;\nexport const THROTTLING_ERROR_CODES = [4, 80007, 130429, 131048, 131056] as const;\nexport const INTEGRITY_ERROR_CODES = [368, 130497, 131031] as const;\nexport const SEND_MESSAGE_ERROR_CODES = [\n    130472, 131000, 131005, 131008, 131009, 131016, 131021, 131026, 131030, 131042, 131044, 131045, 131047, 131050,\n    131051, 131052, 131053, 131056, 131057, 131048, 132000, 132001, 132005, 132007, 132008, 132012, 132015, 132016,\n    132068, 132069, 135000, 137000,\n] as const;\nexport const FLOW_ERROR_CODES = [139000, 139001, 139002, 139003, 139004] as const;\nexport const BLOCK_USER_ERROR_CODES = [139100, 139101, 139102, 139103] as const;\nexport const CALLING_ERROR_CODES = [\n    138000, 138001, 138002, 138003, 138004, 138005, 138006, 138007, 138009, 138012, 138013, 138018, 613,\n] as const;\nexport const GROUP_ERROR_CODES = [\n    131020, 131041, 131059, 131201, 131202, 131203, 131204, 131207, 131208, 131209, 131210, 131211, 131212, 131213,\n    131214, 131215,\n] as const;\n\nconst AUTHORIZATION_ERROR_CODE_SET = new Set<number>(AUTHORIZATION_ERROR_CODES);\nconst THROTTLING_ERROR_CODE_SET = new Set<number>(THROTTLING_ERROR_CODES);\nconst INTEGRITY_ERROR_CODE_SET = new Set<number>(INTEGRITY_ERROR_CODES);\nconst SEND_MESSAGE_ERROR_CODE_SET = new Set<number>(SEND_MESSAGE_ERROR_CODES);\nconst FLOW_ERROR_CODE_SET = new Set<number>(FLOW_ERROR_CODES);\nconst BLOCK_USER_ERROR_CODE_SET = new Set<number>(BLOCK_USER_ERROR_CODES);\nconst CALLING_ERROR_CODE_SET = new Set<number>(CALLING_ERROR_CODES);\nconst GROUP_ERROR_CODE_SET = new Set<number>(GROUP_ERROR_CODES);\n\nexport function isWhatsAppErrorCode(code: number): code is WhatsAppErrorCode {\n    if (isApiPermissionErrorCode(code)) return true;\n    return WHATSAPP_ERROR_CODE_SET.has(code);\n}\n\nexport function isApiPermissionErrorCode(code: number): code is ApiPermissionErrorCode {\n    return code >= 200 && code < 300;\n}\n\nexport function isAuthorizationErrorCode(\n    code: number,\n): code is ApiPermissionErrorCode | (typeof AUTHORIZATION_ERROR_CODES)[number] {\n    return isApiPermissionErrorCode(code) || AUTHORIZATION_ERROR_CODE_SET.has(code);\n}\n\nexport function isThrottlingErrorCode(code: number): code is (typeof THROTTLING_ERROR_CODES)[number] {\n    return THROTTLING_ERROR_CODE_SET.has(code);\n}\n\nexport function isIntegrityErrorCode(code: number): code is (typeof INTEGRITY_ERROR_CODES)[number] {\n    return INTEGRITY_ERROR_CODE_SET.has(code);\n}\n\nexport function isSendMessageErrorCode(code: number): code is (typeof SEND_MESSAGE_ERROR_CODES)[number] {\n    return SEND_MESSAGE_ERROR_CODE_SET.has(code);\n}\n\nexport function isFlowErrorCode(code: number): code is (typeof FLOW_ERROR_CODES)[number] {\n    return FLOW_ERROR_CODE_SET.has(code);\n}\n\nexport function isBlockUserErrorCode(code: number): code is (typeof BLOCK_USER_ERROR_CODES)[number] {\n    return BLOCK_USER_ERROR_CODE_SET.has(code);\n}\n\nexport function isCallingErrorCode(code: number): code is (typeof CALLING_ERROR_CODES)[number] {\n    return CALLING_ERROR_CODE_SET.has(code);\n}\n\nexport function isGroupErrorCode(code: number): code is (typeof GROUP_ERROR_CODES)[number] {\n    return GROUP_ERROR_CODE_SET.has(code);\n}\n\nexport class WhatsAppError extends Error {\n    constructor(message: string) {\n        super(message);\n        this.name = 'WhatsAppError';\n    }\n}\n\nexport class WhatsAppApiError extends WhatsAppError {\n    readonly error: MetaErrorData;\n    readonly statusCode?: number;\n\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message);\n        this.name = 'WhatsAppApiError';\n        this.error = error;\n        this.statusCode = statusCode;\n    }\n}\n\nexport class WhatsAppAuthorizationError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppAuthorizationError';\n    }\n}\n\nexport class WhatsAppThrottlingError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppThrottlingError';\n    }\n}\n\nexport class WhatsAppIntegrityError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppIntegrityError';\n    }\n}\n\nexport class WhatsAppSendMessageError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppSendMessageError';\n    }\n}\n\nexport class WhatsAppFlowError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppFlowError';\n    }\n}\n\nexport class WhatsAppBlockUserError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppBlockUserError';\n    }\n}\n\nexport class WhatsAppCallingError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppCallingError';\n    }\n}\n\nexport class WhatsAppGroupError extends WhatsAppApiError {\n    constructor(message: string, error: MetaErrorData, statusCode?: number) {\n        super(message, error, statusCode);\n        this.name = 'WhatsAppGroupError';\n    }\n}\n\nexport function createWhatsAppApiError(error: MetaErrorData, statusCode?: number): WhatsAppApiError {\n    const code = error.code;\n\n    if (isAuthorizationErrorCode(code)) {\n        return new WhatsAppAuthorizationError(error.message, error, statusCode);\n    }\n    if (isThrottlingErrorCode(code)) {\n        return new WhatsAppThrottlingError(error.message, error, statusCode);\n    }\n    if (isIntegrityErrorCode(code)) {\n        return new WhatsAppIntegrityError(error.message, error, statusCode);\n    }\n    if (isSendMessageErrorCode(code)) {\n        return new WhatsAppSendMessageError(error.message, error, statusCode);\n    }\n    if (isFlowErrorCode(code)) {\n        return new WhatsAppFlowError(error.message, error, statusCode);\n    }\n    if (isBlockUserErrorCode(code)) {\n        return new WhatsAppBlockUserError(error.message, error, statusCode);\n    }\n    if (isCallingErrorCode(code)) {\n        return new WhatsAppCallingError(error.message, error, statusCode);\n    }\n    if (isGroupErrorCode(code)) {\n        return new WhatsAppGroupError(error.message, error, statusCode);\n    }\n\n    return new WhatsAppApiError(error.message, error, statusCode);\n}\n\nexport class WhatsAppNetworkError extends WhatsAppError {\n    readonly cause?: unknown;\n\n    constructor(message: string, cause?: unknown) {\n        super(message);\n        this.name = 'WhatsAppNetworkError';\n        this.cause = cause;\n    }\n}\n\nexport class WhatsAppUnknownError extends WhatsAppError {\n    readonly cause?: unknown;\n\n    constructor(message: string, cause?: unknown) {\n        super(message);\n        this.name = 'WhatsAppUnknownError';\n        this.cause = cause;\n    }\n}\n\n/**\n * Thrown when an API method receives invalid input (e.g., malformed phone number,\n * empty required array). This error is thrown client-side before any API call is made.\n */\nexport class WhatsAppValidationError extends Error {\n    constructor(message: string) {\n        super(message);\n        this.name = 'WhatsAppValidationError';\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    if (error == null || typeof error !== 'object') return false;\n    if (!('error' in error) || typeof error.error !== 'object' || error.error == null) return false;\n\n    const metaError = error.error as Record<string, unknown>;\n\n    if (typeof metaError.message !== 'string') return false;\n    if (typeof metaError.type !== 'string') return false;\n    if (typeof metaError.code !== 'number') return false;\n    if (typeof metaError.fbtrace_id !== 'string') return false;\n\n    if ('error_data' in metaError && metaError.error_data != null) {\n        if (typeof metaError.error_data !== 'object') return false;\n        const errorData = metaError.error_data as Record<string, unknown>;\n        if ('messaging_product' in errorData && errorData.messaging_product !== 'whatsapp') return false;\n        if ('details' in errorData && typeof errorData.details !== 'string') return false;\n    }\n\n    if ('error_subcode' in metaError && typeof metaError.error_subcode !== 'number') return false;\n\n    return true;\n}\n\nexport function isWhatsAppApiErrorResponse(error: any): error is MetaError & { error: { code: WhatsAppErrorCode } } {\n    return isMetaError(error) && isWhatsAppErrorCode(error.error.code);\n}\n\nexport function isWhatsAppAuthorizationError(error: unknown): error is WhatsAppAuthorizationError {\n    return error instanceof WhatsAppAuthorizationError;\n}\n\nexport function isWhatsAppThrottlingError(error: unknown): error is WhatsAppThrottlingError {\n    return error instanceof WhatsAppThrottlingError;\n}\n\nexport function isWhatsAppIntegrityError(error: unknown): error is WhatsAppIntegrityError {\n    return error instanceof WhatsAppIntegrityError;\n}\n\nexport function isWhatsAppSendMessageError(error: unknown): error is WhatsAppSendMessageError {\n    return error instanceof WhatsAppSendMessageError;\n}\n\nexport function isWhatsAppFlowError(error: unknown): error is WhatsAppFlowError {\n    return error instanceof WhatsAppFlowError;\n}\n\nexport function isWhatsAppBlockUserError(error: unknown): error is WhatsAppBlockUserError {\n    return error instanceof WhatsAppBlockUserError;\n}\n\nexport function isWhatsAppCallingError(error: unknown): error is WhatsAppCallingError {\n    return error instanceof WhatsAppCallingError;\n}\n\nexport function isWhatsAppGroupError(error: unknown): error is WhatsAppGroupError {\n    return error instanceof WhatsAppGroupError;\n}\n\nexport function normalizeMetaError(errorData: unknown, statusCode?: number): MetaError {\n    if (isMetaError(errorData)) return errorData;\n\n    let message = 'Unknown error occurred';\n    if (errorData && typeof errorData === 'object' && 'message' in errorData) {\n        const candidate = (errorData as { message?: unknown }).message;\n        if (typeof candidate === 'string') message = candidate;\n    }\n\n    return {\n        name: 'MetaError',\n        message,\n        error: {\n            message,\n            type: 'UnknownError',\n            code: typeof statusCode === 'number' ? statusCode : 500,\n            fbtrace_id: '',\n        },\n    };\n}\n","import { WhatsAppValidationError } from './isMetaError';\n\n/**\n * Asserts that a phone number is in valid E.164 format.\n * Accepts numbers with or without leading '+'.\n * Must be 10-15 digits (not counting the '+').\n *\n * @throws WhatsAppValidationError if the phone number is invalid\n *\n * @example\n * assertPhoneNumber('+14155552671'); // ok\n * assertPhoneNumber('14155552671');  // ok\n * assertPhoneNumber('123');          // throws\n */\nexport function assertPhoneNumber(phone: string): void {\n    if (!/^\\+?\\d{10,15}$/.test(phone)) {\n        throw new WhatsAppValidationError(\n            `Invalid phone number: \"${phone}\". Expected E.164 format (e.g. +14155552671 or 14155552671).`,\n        );\n    }\n}\n\n/**\n * Asserts that an array is non-empty.\n * Also guards against null/undefined to preserve backward compatibility\n * with callers that may pass untyped values.\n *\n * @throws WhatsAppValidationError if the array is null, undefined, or empty\n *\n * @example\n * assertNonEmpty(['user1'], 'users'); // ok\n * assertNonEmpty([], 'users');        // throws\n */\nexport function assertNonEmpty<T>(arr: T[] | null | undefined, name: string): void {\n    if (!arr || arr.length === 0) {\n        throw new WhatsAppValidationError(`\"${name}\" must contain at least one item.`);\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/block_users\n// - DELETE /{PHONE_NUMBER_ID}/block_users\n// - GET /{PHONE_NUMBER_ID}/block_users?limit&after&before\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport { assertNonEmpty } from '../../utils/validate';\nimport type * as blockUsers from './types/blockUsers';\n\n/**\n * API for blocking and unblocking WhatsApp users.\n *\n * Provides methods to block, unblock, and list blocked users for your\n * WhatsApp Business phone number.\n *\n * Limitations:\n * - Can only block users that have messaged your business in the last 24 hours\n * - 64k blocklist limit\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/block_users` - Block one or more users\n * - `DELETE /{PHONE_NUMBER_ID}/block_users` - Unblock one or more users\n * - `GET /{PHONE_NUMBER_ID}/block_users` - List blocked users with pagination\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n */\nexport default class BlockUsersApi extends BaseAPI implements blockUsers.BlockUsersClass {\n    private readonly endpoint = 'block_users';\n\n    /**\n     * Build the request body for block/unblock operations.\n     *\n     * @param users - Array of phone numbers or WhatsApp IDs.\n     * @returns The formatted request body.\n     */\n    private buildBlockUsersBody(users: string[]): blockUsers.BlockUsersRequest {\n        return {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\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/documentation/business-messaging/whatsapp/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        assertNonEmpty(users, 'users');\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/documentation/business-messaging/whatsapp/block-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        assertNonEmpty(users, 'users');\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/documentation/business-messaging/whatsapp/block-users/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/overview/\n\n// Endpoints:\n// - GET /{APPLICATION_ID}/connected_client_businesses\n// - POST /{BUSINESS_ID}/add_phone_numbers\n// - GET /{BUSINESS_ID}\n// - GET /{BUSINESS_ID}/preverified_numbers\n// - GET /{BUSINESS_ID}/client_whatsapp_business_accounts\n// - POST /{BUSINESS_ID}/onboard_partners_to_mm_lite\n// - GET /{BUSINESS_ID}/owned_whatsapp_business_accounts\n// - POST /{BUSINESS_ID}/share_preverified_numbers\n// - GET /{BUSINESS_ID}/extendedcredits\n// - GET /{USER_ID}/assigned_whatsapp_business_accounts\n// - GET /{WHATSAPP_ACCOUNT_NUMBER_ID}\n// - GET /{PRE_VERIFIED_PHONE_NUMBER_ID}\n// - DELETE /{PRE_VERIFIED_PHONE_NUMBER_ID}\n// - GET /{PRE_VERIFIED_PHONE_NUMBER_ID}/partners\n// - POST /{PRE_VERIFIED_PHONE_NUMBER_ID}/request_code\n// - POST /{PRE_VERIFIED_PHONE_NUMBER_ID}/verify_code\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as business from './types';\n\nexport default class BusinessApi extends BaseAPI implements business.BusinessClass {\n    private toQuery(params?: business.BusinessListParams): string {\n        if (!params) return '';\n\n        const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n        const filtering = Array.isArray(params.filtering) ? JSON.stringify(params.filtering) : params.filtering;\n\n        return objectToQueryString({\n            fields,\n            filtering,\n            sort: params.sort,\n            limit: params.limit,\n            after: params.after,\n            before: params.before,\n        });\n    }\n\n    private fieldsQuery(fields?: business.BusinessFieldsParam): string {\n        const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n        return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\n    }\n\n    async getConnectedClientBusinesses(\n        applicationId: string = this.config[WabaConfigEnum.AppId],\n        params?: business.BusinessListParams,\n    ): Promise<business.BusinessGraphListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${applicationId}/connected_client_businesses${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async addPhoneNumbers(businessId: string, request: business.AddPhoneNumbersRequest): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${businessId}/add_phone_numbers`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async getBusinessPortfolio(\n        businessId: string,\n        fields?: business.BusinessFieldsParam,\n    ): Promise<business.BusinessGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${businessId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getPreVerifiedPhoneNumbers(\n        businessId: string,\n        params?: business.BusinessListParams,\n    ): Promise<business.BusinessGraphListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${businessId}/preverified_numbers${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getClientWhatsAppBusinessAccounts(\n        businessId: string,\n        params?: business.BusinessListParams,\n    ): Promise<business.BusinessGraphListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${businessId}/client_whatsapp_business_accounts${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async onboardPartnersToMMLite(\n        businessId: string,\n        request: business.OnboardPartnersToMMLiteRequest,\n    ): Promise<business.BusinessGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${businessId}/onboard_partners_to_mm_lite`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async getOwnedWhatsAppBusinessAccounts(\n        businessId: string,\n        params?: business.BusinessListParams,\n    ): Promise<business.BusinessGraphListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${businessId}/owned_whatsapp_business_accounts${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async sharePreVerifiedPhoneNumber(\n        businessId: string,\n        request: business.SharePreVerifiedPhoneNumberRequest,\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${businessId}/share_preverified_numbers`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async getCreditLines(businessId: string): Promise<business.BusinessGraphListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${businessId}/extendedcredits`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getAssignedWhatsAppBusinessAccounts(\n        userId: string,\n        params?: business.BusinessListParams,\n    ): Promise<business.BusinessGraphListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${userId}/assigned_whatsapp_business_accounts${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getWhatsAppAccountNumberDetails(\n        accountNumberId: string,\n        fields?: business.BusinessFieldsParam,\n    ): Promise<business.BusinessGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${accountNumberId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getPreVerifiedPhoneNumberDetails(\n        preVerifiedPhoneNumberId: string,\n        fields?: business.BusinessFieldsParam,\n    ): Promise<business.BusinessGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${preVerifiedPhoneNumberId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async deletePreVerifiedPhoneNumber(preVerifiedPhoneNumberId: string): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Delete,\n            preVerifiedPhoneNumberId,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getPreVerifiedPhoneNumberPartners(\n        preVerifiedPhoneNumberId: string,\n        params?: business.BusinessListParams,\n    ): Promise<business.BusinessGraphListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${preVerifiedPhoneNumberId}/partners${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async requestPreVerifiedPhoneNumberCode(\n        preVerifiedPhoneNumberId: string,\n        request: business.RequestPreVerifiedPhoneNumberCodeRequest,\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${preVerifiedPhoneNumberId}/request_code`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async verifyPreVerifiedPhoneNumberCode(\n        preVerifiedPhoneNumberId: string,\n        request: business.VerifyPreVerifiedPhoneNumberCodeRequest,\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${preVerifiedPhoneNumberId}/verify_code`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/settings\n// - GET /{PHONE_NUMBER_ID}/settings?fields&include_sip_credentials\n// - GET /{PHONE_NUMBER_ID}/call_permissions?user_wa_id\n// - POST /{PHONE_NUMBER_ID}/calls\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as calling from './types';\n\n/**\n * API for WhatsApp Calling features.\n *\n * Provides methods to manage calling settings, permissions, and call lifecycle\n * (initiate, pre-accept, accept, reject, terminate).\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/settings` - Update calling settings\n * - `GET /{PHONE_NUMBER_ID}/settings` - Get calling settings\n * - `GET /{PHONE_NUMBER_ID}/call_permissions` - Get call permissions for a user\n * - `POST /{PHONE_NUMBER_ID}/calls` - Initiate, pre-accept, accept, reject, or terminate a call\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\nexport default class CallingApi extends BaseAPI implements calling.CallingClass {\n    private readonly endpoint = 'calls';\n\n    /**\n     * Update calling settings for the phone number, such as enabling/disabling calling\n     * or configuring SIP credentials.\n     *\n     * @param params - The calling settings to update.\n     * @returns A success response confirming the settings were updated.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async updateCallingSettings(params: calling.UpdateCallingSettingsRequest): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/settings`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    /**\n     * Retrieve the current calling settings for the phone number.\n     *\n     * @param params - Optional query parameters to filter the response.\n     * @param params.fields - Specific fields to include in the response.\n     * @param params.include_sip_credentials - Whether to include SIP credentials in the response.\n     * @returns The current calling settings configuration.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async getCallingSettings(params?: {\n        fields?: string[] | string;\n        include_sip_credentials?: boolean;\n    }): Promise<calling.CallingSettingsResponse> {\n        const fieldsValue = Array.isArray(params?.fields) ? params?.fields.join(',') : params?.fields;\n        const queryParams = objectToQueryString({\n            ...(fieldsValue ? { fields: fieldsValue } : {}),\n            ...(params?.include_sip_credentials !== undefined\n                ? { include_sip_credentials: params.include_sip_credentials }\n                : {}),\n        });\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/settings${queryParams}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Get calling permissions for a specific WhatsApp user.\n     *\n     * @param params - The request parameters.\n     * @param params.userWaId - The WhatsApp ID of the user to check permissions for.\n     * @returns The call permissions for the specified user.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async getCallPermissions(params: { userWaId: string }): Promise<calling.CallPermissionsResponse> {\n        const queryParams = objectToQueryString({ user_wa_id: params.userWaId });\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/call_permissions${queryParams}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Initiate an outbound call to a WhatsApp user.\n     *\n     * @param params - The call initiation parameters.\n     * @param params.to - The recipient's WhatsApp phone number.\n     * @param params.session - The call session configuration.\n     * @param params.biz_opaque_callback_data - Optional opaque data passed back in webhooks.\n     * @returns The initiated call response with call ID and status.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async initiateCall(params: calling.InitiateCallRequest): Promise<calling.InitiateCallResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            to: params.to,\n            action: 'connect',\n            session: params.session,\n        } as {\n            messaging_product: 'whatsapp';\n            to: string;\n            action: calling.CallAction;\n            session: calling.CallSession;\n            biz_opaque_callback_data?: string;\n        };\n\n        if (params.biz_opaque_callback_data) {\n            body.biz_opaque_callback_data = params.biz_opaque_callback_data;\n        }\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Pre-accept an incoming call, signaling readiness to connect before full acceptance.\n     *\n     * @param params - The pre-accept request parameters.\n     * @param params.call_id - The ID of the call to pre-accept.\n     * @param params.session - Optional session configuration for the call.\n     * @returns The call action response confirming the pre-accept.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async preAcceptCall(params: calling.PreAcceptCallRequest): Promise<calling.CallActionResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            call_id: params.call_id,\n            action: 'pre_accept',\n        } as {\n            messaging_product: 'whatsapp';\n            call_id: string;\n            action: calling.CallAction;\n            session?: calling.CallSession;\n        };\n\n        if (params.session) body.session = params.session;\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Accept an incoming call and establish the connection.\n     *\n     * @param params - The accept request parameters.\n     * @param params.call_id - The ID of the call to accept.\n     * @param params.session - Optional session configuration for the call.\n     * @param params.biz_opaque_callback_data - Optional opaque data passed back in webhooks.\n     * @returns The call action response confirming acceptance.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async acceptCall(params: calling.AcceptCallRequest): Promise<calling.CallActionResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            call_id: params.call_id,\n            action: 'accept',\n        } as {\n            messaging_product: 'whatsapp';\n            call_id: string;\n            action: calling.CallAction;\n            session?: calling.CallSession;\n            biz_opaque_callback_data?: string;\n        };\n\n        if (params.session) body.session = params.session;\n        if (params.biz_opaque_callback_data) {\n            body.biz_opaque_callback_data = params.biz_opaque_callback_data;\n        }\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Reject an incoming call.\n     *\n     * @param params - The reject request parameters.\n     * @param params.call_id - The ID of the call to reject.\n     * @returns The call action response confirming rejection.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async rejectCall(params: calling.RejectCallRequest): Promise<calling.CallActionResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            call_id: params.call_id,\n            action: 'reject',\n        };\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Terminate an active call.\n     *\n     * @param params - The terminate request parameters.\n     * @param params.call_id - The ID of the call to terminate.\n     * @returns The call action response confirming termination.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    async terminateCall(params: calling.TerminateCallRequest): Promise<calling.CallActionResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            call_id: params.call_id,\n            action: 'terminate',\n        };\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_commerce_settings\n// - POST /{PHONE_NUMBER_ID}/whatsapp_commerce_settings?is_cart_enabled&is_catalog_visible\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as commerce from './types';\n\n/**\n * API for WhatsApp Commerce Settings.\n *\n * Provides methods to retrieve and update commerce settings such as cart\n * and catalog visibility for your WhatsApp Business phone number.\n *\n * Endpoints covered:\n * - `GET /{PHONE_NUMBER_ID}/whatsapp_commerce_settings` - Get commerce settings\n * - `POST /{PHONE_NUMBER_ID}/whatsapp_commerce_settings` - Update commerce settings\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n */\nexport default class CommerceApi extends BaseAPI implements commerce.CommerceClass {\n    private readonly endpoint = 'whatsapp_commerce_settings';\n\n    /**\n     * Retrieve the current commerce settings for the phone number.\n     *\n     * @returns The current commerce settings including cart and catalog visibility state.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n     */\n    async getCommerceSettings(): Promise<commerce.CommerceSettingsResponse> {\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     * Update commerce settings for the phone number (e.g., enable/disable cart or catalog).\n     *\n     * @param params - The commerce settings to update (e.g., is_cart_enabled, is_catalog_visible).\n     * @returns A success response confirming the settings were updated.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n     */\n    async updateCommerceSettings(params: commerce.UpdateCommerceSettingsRequest): Promise<ResponseSuccess> {\n        const queryParams = objectToQueryString(params);\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${queryParams}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_business_encryption\n// - POST /{PHONE_NUMBER_ID}/whatsapp_business_encryption\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n\n/**\n * API for managing WhatsApp Business Encryption keys.\n *\n * Provides methods to get and set the public encryption key used for\n * end-to-end encrypted messaging with WhatsApp Business.\n *\n * Endpoints covered:\n * - `GET /{PHONE_NUMBER_ID}/whatsapp_business_encryption` - Get the current public encryption key\n * - `POST /{PHONE_NUMBER_ID}/whatsapp_business_encryption` - Set a new public encryption key\n *\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\nexport default class EncryptionApi extends BaseAPI implements EncryptionClass {\n    private readonly endpoint = 'whatsapp_business_encryption';\n\n    /**\n     * Retrieve the current public encryption key for the phone number.\n     *\n     * @returns The current public encryption key.\n     * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\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    /**\n     * Set a new public encryption key for the phone number.\n     *\n     * @param businessPublicKey - The PEM-encoded public key string to set.\n     * @returns A success response confirming the key was set.\n     * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n     */\n    async setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess> {\n        const formData = new FormData();\n        formData.append('business_public_key', businessPublicKey);\n\n        return this.sendFormData(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            formData,\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/\n\n// Endpoints:\n// - GET /{WABA_ID}/flows\n// - POST /{WABA_ID}/flows\n// - GET /{FLOW_ID}?fields&date_format\n// - POST /{FLOW_ID}\n// - DELETE /{FLOW_ID}\n// - GET /{FLOW_ID}/assets\n// - POST /{FLOW_ID}/assets\n// - POST /{FLOW_ID}/publish\n// - POST /{FLOW_ID}/deprecate\n// - POST /{DESTINATION_WABA_ID}/migrate_flows\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\n\nimport type * as flow from './types';\n\n/**\n * API for managing WhatsApp Flows.\n *\n * WhatsApp Flows allow businesses to build structured, interactive experiences\n * within WhatsApp conversations. Flows can be used for appointment booking,\n * lead generation, customer support, surveys, and more.\n *\n * This API allows you to:\n * - List flows for a WhatsApp Business Account (`GET /{WABA_ID}/flows`)\n * - Create new flows (`POST /{WABA_ID}/flows`)\n * - Get flow details and previews (`GET /{FLOW_ID}`)\n * - Update flow metadata (`POST /{FLOW_ID}`)\n * - Delete draft flows (`DELETE /{FLOW_ID}`)\n * - List flow assets / download Flow JSON (`GET /{FLOW_ID}/assets`)\n * - Upload or update Flow JSON (`POST /{FLOW_ID}/assets`)\n * - Publish flows (`POST /{FLOW_ID}/publish`)\n * - Deprecate flows (`POST /{FLOW_ID}/deprecate`)\n * - Migrate flows between WABAs (`POST /{DESTINATION_WABA_ID}/migrate_flows`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi | Flows API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/ | WhatsApp Flows Documentation}\n */\nexport default class FlowApi extends BaseAPI implements flow.FlowClass {\n    private appendFormValue(\n        formData: FormData,\n        key: string,\n        value?: string | boolean | string[] | flow.FlowCategoryEnum[],\n    ) {\n        if (value === undefined) return;\n        formData.append(key, Array.isArray(value) ? JSON.stringify(value) : String(value));\n    }\n\n    /**\n     * List all flows belonging to a WhatsApp Business Account.\n     *\n     * Retrieves a paginated list of all flows associated with the given WABA ID,\n     * including their IDs, names, statuses, and categories.\n     *\n     * @param wabaId - The WhatsApp Business Account ID to list flows for.\n     * @returns A promise that resolves with the list of flows and pagination info.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#list | List Flows}\n     *\n     * @example\n     * ```ts\n     * const response = await whatsappClient.flow.listFlows('WABA_ID');\n     * for (const flow of response.data) {\n     *     console.log(flow.id, flow.name, flow.status);\n     * }\n     * ```\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 a new flow for a WhatsApp Business Account.\n     *\n     * Creates a new flow in DRAFT status. You can optionally clone an existing flow,\n     * provide initial Flow JSON, and even publish the flow immediately upon creation.\n     *\n     * @param wabaId - The WhatsApp Business Account ID to create the flow under.\n     * @param data - The flow creation parameters.\n     * @param data.name - The name of the flow.\n     * @param data.categories - Optional array of flow categories (e.g., LEAD_GENERATION, APPOINTMENT_BOOKING).\n     * @param data.endpoint_uri - Optional URI for the flow endpoint that will receive flow action payloads.\n     * @param data.clone_flow_id - Optional ID of an existing flow to clone.\n     * @param data.flow_json - Optional Flow JSON definition as a string.\n     * @param data.publish - Optional flag to publish the flow immediately after creation.\n     * @returns A promise that resolves with the created flow ID and any validation errors.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#create | Create Flow}\n     *\n     * @example\n     * ```ts\n     * const result = await whatsappClient.flow.createFlow('WABA_ID', {\n     *     name: 'Appointment Booking',\n     *     categories: ['APPOINTMENT_BOOKING'],\n     *     endpoint_uri: 'https://example.com/flow-endpoint',\n     * });\n     * console.log(result.id); // New flow ID\n     * ```\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        const formData = new FormData();\n        this.appendFormValue(formData, 'name', data.name);\n        this.appendFormValue(formData, 'categories', data.categories);\n        this.appendFormValue(formData, 'endpoint_uri', data.endpoint_uri);\n        this.appendFormValue(formData, 'clone_flow_id', data.clone_flow_id);\n        this.appendFormValue(formData, 'flow_json', data.flow_json);\n        this.appendFormValue(formData, 'publish', data.publish);\n\n        return this.sendFormData(\n            HttpMethodsEnum.Post,\n            `/${wabaId}/flows`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            formData,\n        );\n    }\n\n    /**\n     * Get details of a specific flow.\n     *\n     * Retrieves flow information such as name, status, categories, JSON validation errors,\n     * and optionally a preview URL. Use the `fields` parameter to request specific fields\n     * or the preview endpoint.\n     *\n     * @param flowId - The ID of the flow to retrieve.\n     * @param fields - Optional comma-separated list of fields to return (e.g., `'name,status,preview.invalidate(false)'`).\n     * @param dateFormat - Optional date format string for date fields in the response.\n     * @returns A promise that resolves with the flow details or preview response.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#details | Get Flow Details}\n     *\n     * @example\n     * ```ts\n     * // Get all flow details\n     * const flow = await whatsappClient.flow.getFlow('FLOW_ID');\n     * console.log(flow.name, flow.status);\n     *\n     * // Get specific fields only\n     * const flow = await whatsappClient.flow.getFlow('FLOW_ID', 'name,status,categories');\n     * ```\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 a preview URL for a flow.\n     *\n     * Generates a shareable preview URL that allows viewing the flow without publishing it.\n     * The preview can optionally be invalidated to force generation of a fresh URL.\n     *\n     * @param flowId - The ID of the flow to preview.\n     * @param invalidate - If `true`, invalidates the existing preview and generates a new one. Defaults to `false`.\n     * @returns A promise that resolves with the flow preview details including the preview URL.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#details | Get Flow Preview}\n     *\n     * @example\n     * ```ts\n     * // Get existing preview URL\n     * const preview = await whatsappClient.flow.getFlowPreview('FLOW_ID');\n     * console.log(preview.preview.preview_url);\n     *\n     * // Force a new preview URL\n     * const freshPreview = await whatsappClient.flow.getFlowPreview('FLOW_ID', true);\n     * ```\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 the metadata of an existing flow.\n     *\n     * Allows updating a flow's name, categories, endpoint URI, or associated application ID.\n     * The flow must be in DRAFT status to update certain fields.\n     *\n     * @param flowId - The ID of the flow to update.\n     * @param data - The metadata fields to update.\n     * @param data.name - Optional new name for the flow.\n     * @param data.categories - Optional new categories for the flow.\n     * @param data.endpoint_uri - Optional new endpoint URI for flow action payloads.\n     * @param data.application_id - Optional application ID to associate with the flow.\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#update | Update Flow}\n     *\n     * @example\n     * ```ts\n     * await whatsappClient.flow.updateFlowMetadata('FLOW_ID', {\n     *     name: 'Updated Flow Name',\n     *     endpoint_uri: 'https://example.com/new-endpoint',\n     * });\n     * ```\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        const formData = new FormData();\n        this.appendFormValue(formData, 'name', data.name);\n        this.appendFormValue(formData, 'categories', data.categories);\n        this.appendFormValue(formData, 'endpoint_uri', data.endpoint_uri);\n        this.appendFormValue(formData, 'application_id', data.application_id);\n\n        return this.sendFormData(\n            HttpMethodsEnum.Post,\n            `/${flowId}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            formData,\n        );\n    }\n\n    /**\n     * Delete a flow.\n     *\n     * Permanently deletes a flow. Only flows in DRAFT status can be deleted.\n     * Published or deprecated flows cannot be deleted.\n     *\n     * @param flowId - The ID of the flow to delete.\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#delete | Delete Flow}\n     *\n     * @example\n     * ```ts\n     * await whatsappClient.flow.deleteFlow('FLOW_ID');\n     * ```\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 associated with a flow.\n     *\n     * Retrieves the list of assets (e.g., Flow JSON) associated with the flow.\n     * The response includes download URLs for each asset.\n     *\n     * @param flowId - The ID of the flow to list assets for.\n     * @returns A promise that resolves with the list of assets including download URLs.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-list | List Flow Assets}\n     *\n     * @example\n     * ```ts\n     * const assets = await whatsappClient.flow.listAssets('FLOW_ID');\n     * for (const asset of assets.data) {\n     *     console.log(asset.name, asset.download_url);\n     * }\n     * ```\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     * Upload or update the Flow JSON for a flow.\n     *\n     * Uploads a Flow JSON definition to the flow's assets. The JSON defines the screens,\n     * layout, and logic of the flow. Accepts a Buffer, plain JSON object, or Blob.\n     *\n     * @param flowId - The ID of the flow to update.\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 A promise that resolves with the upload status and any validation errors.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-upload | Upload Flow JSON}\n     *\n     * @example\n     * ```ts\n     * // Upload from a JSON object\n     * const result = await whatsappClient.flow.updateFlowJson('FLOW_ID', {\n     *     file: {\n     *         version: '5.0',\n     *         screens: [{ id: 'WELCOME', layout: { type: 'SingleColumnLayout', children: [] } }],\n     *     },\n     * });\n     *\n     * // Upload from a Buffer\n     * const jsonBuffer = Buffer.from(JSON.stringify(flowDefinition));\n     * await whatsappClient.flow.updateFlowJson('FLOW_ID', { file: jsonBuffer });\n     * ```\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 - convert to Uint8Array for BlobPart compatibility\n            fileContent = new globalThis.Blob([new Uint8Array(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 without publishing.\n     *\n     * This is a convenience method that uploads the Flow JSON and checks for validation\n     * errors. The API does not have a dedicated validation endpoint, so this method\n     * performs an update and inspects the response for errors.\n     *\n     * @param flowId - The ID of the flow to validate against (must exist, can be in DRAFT status).\n     * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n     * @returns A promise that resolves with validation results, including a `valid` boolean\n     *          and any `validation_errors` found.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-upload | Upload Flow JSON (validation)}\n     *\n     * @example\n     * ```ts\n     * const result = await whatsappClient.flow.validateFlowJson('FLOW_ID', {\n     *     version: '5.0',\n     *     screens: [{ id: 'WELCOME', layout: { type: 'SingleColumnLayout', children: [] } }],\n     * });\n     * if (result.valid) {\n     *     console.log('Flow JSON is valid');\n     * } else {\n     *     console.error('Validation errors:', result.validation_errors);\n     * }\n     * ```\n     */\n    async validateFlowJson(\n        flowId: string,\n        flowJsonData: Blob | Buffer | object,\n    ): Promise<flow.ValidateFlowJsonResponse> {\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    }\n\n    /**\n     * Publish a flow.\n     *\n     * Transitions a flow from DRAFT status to PUBLISHED. Once published, the flow\n     * can be sent to users in WhatsApp messages. A published flow's JSON can no longer\n     * be updated.\n     *\n     * @param flowId - The ID of the flow to publish.\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#publish | Publish Flow}\n     *\n     * @example\n     * ```ts\n     * await whatsappClient.flow.publishFlow('FLOW_ID');\n     * ```\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 a flow.\n     *\n     * Transitions a flow from PUBLISHED status to DEPRECATED. A deprecated flow\n     * can no longer be sent to users but existing sessions will continue to work.\n     * This action cannot be undone.\n     *\n     * @param flowId - The ID of the flow to deprecate.\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#deprecate | Deprecate Flow}\n     *\n     * @example\n     * ```ts\n     * await whatsappClient.flow.deprecateFlow('FLOW_ID');\n     * ```\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 WhatsApp Business Accounts.\n     *\n     * Copies flows from a source WABA to a destination WABA. You can optionally\n     * specify which flows to migrate by name. Migrated flows are created in DRAFT\n     * status in the destination WABA.\n     *\n     * @param destinationWabaId - The ID of the destination WhatsApp Business Account.\n     * @param data - The migration parameters.\n     * @param data.source_waba_id - The ID of the source WhatsApp Business Account to migrate flows from.\n     * @param data.source_flow_names - Optional array of flow names to migrate. If omitted, all flows are migrated.\n     * @returns A promise that resolves with migration results including successes and failures.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#migrate | Migrate Flows}\n     *\n     * @example\n     * ```ts\n     * // Migrate all flows from one WABA to another\n     * const result = await whatsappClient.flow.migrateFlows('DEST_WABA_ID', {\n     *     source_waba_id: 'SOURCE_WABA_ID',\n     * });\n     *\n     * // Migrate specific flows by name\n     * const result = await whatsappClient.flow.migrateFlows('DEST_WABA_ID', {\n     *     source_waba_id: 'SOURCE_WABA_ID',\n     *     source_flow_names: ['Appointment Booking', 'Lead Gen Form'],\n     * });\n     * console.log(result.migrated_flows, result.failed_flows);\n     * ```\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        const formData = new FormData();\n        this.appendFormValue(formData, 'source_waba_id', data.source_waba_id);\n        this.appendFormValue(formData, 'source_flow_names', data.source_flow_names);\n\n        return this.sendFormData(\n            HttpMethodsEnum.Post,\n            `/${destinationWabaId}/migrate_flows`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            formData,\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/\n\nimport type { IncomingHttpHeaders, IncomingMessage } from 'node:http';\nimport type { ResponseSuccess } from '../../../types';\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/groups\n// - DELETE /{GROUP_ID}\n// - GET /{GROUP_ID}?fields\n// - GET /{PHONE_NUMBER_ID}/groups?limit&after&before\n// - GET /{GROUP_ID}/invite_link\n// - POST /{GROUP_ID}/invite_link\n// - DELETE /{GROUP_ID}/invite_link\n// - GET /{GROUP_ID}/join_requests\n// - POST /{GROUP_ID}/join_requests\n// - DELETE /{GROUP_ID}/join_requests\n// - POST /{GROUP_ID}/participants\n// - DELETE /{GROUP_ID}/participants\n// - POST /{GROUP_ID}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport { assertNonEmpty } from '../../utils/validate';\n\nimport type * as groups from './types';\n\n/**\n * API for managing WhatsApp Groups.\n *\n * This API allows you to:\n * - Create and delete groups\n * - Approve/reject join requests\n * - Manage group invite links\n * - Remove participants\n * - Update group settings\n * - Fetch group metadata and active groups\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/groups` - Create a new group\n * - `DELETE /{GROUP_ID}` - Delete a group\n * - `GET /{GROUP_ID}` - Get group info\n * - `GET /{PHONE_NUMBER_ID}/groups` - List active groups\n * - `GET /{GROUP_ID}/invite_link` - Get group invite link\n * - `POST /{GROUP_ID}/invite_link` - Reset group invite link\n * - `GET /{GROUP_ID}/join_requests` - Get pending join requests\n * - `POST /{GROUP_ID}/join_requests` - Approve join requests\n * - `DELETE /{GROUP_ID}/join_requests` - Reject join requests\n * - `DELETE /{GROUP_ID}/participants` - Remove participants\n * - `POST /{GROUP_ID}` - Update group settings\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\nexport default class GroupsApi extends BaseAPI implements groups.GroupsClass {\n    /**\n     * Create a new WhatsApp group.\n     *\n     * @param params - The group creation parameters.\n     * @param params.subject - The name/subject of the group.\n     * @param params.description - Optional description for the group.\n     * @param params.join_approval_mode - Optional join approval mode setting.\n     * @returns The created group response with group ID.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async createGroup(params: groups.GroupCreateRequest): Promise<groups.GroupCreateResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            subject: params.subject,\n        } as { messaging_product: 'whatsapp'; subject: string; description?: string; join_approval_mode?: string };\n\n        if (params.description) body.description = params.description;\n        if (params.join_approval_mode) body.join_approval_mode = params.join_approval_mode;\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/groups`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Delete a WhatsApp group.\n     *\n     * @param groupId - The ID of the group to delete.\n     * @returns A success response confirming deletion.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async deleteGroup(groupId: string): Promise<ResponseSuccess> {\n        return this.sendJson(HttpMethodsEnum.Delete, groupId, this.config[WabaConfigEnum.RequestTimeout], null);\n    }\n\n    /**\n     * Retrieve metadata and information about a specific group.\n     *\n     * @param groupId - The ID of the group to retrieve.\n     * @param fields - Optional fields to include in the response (e.g., subject, description, participants).\n     * @returns The group information including metadata and requested fields.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async getGroupInfo(groupId: string, fields?: groups.GroupInfoFieldsParam): Promise<groups.GroupInfoResponse> {\n        const fieldValue = Array.isArray(fields) ? fields.join(',') : fields;\n        const queryParams = fieldValue ? objectToQueryString({ fields: fieldValue }) : '';\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${groupId}${queryParams}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * List all active groups for the phone number with optional pagination.\n     *\n     * @param params - Optional pagination parameters.\n     * @param params.limit - Maximum number of groups to return.\n     * @param params.after - Cursor for forward pagination.\n     * @param params.before - Cursor for backward pagination.\n     * @returns A paginated list of active groups.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async getActiveGroups(params?: groups.GroupListParams): Promise<groups.GroupListResponse> {\n        const queryParams = params ? objectToQueryString(params) : '';\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/groups${queryParams}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Get the current invite link for a group.\n     *\n     * @param groupId - The ID of the group.\n     * @returns The group invite link.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async getGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${groupId}/invite_link`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Create a group invite link.\n     *\n     * @param groupId - The ID of the group.\n     * @returns The group invite link.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async createGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n        };\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${groupId}/invite_link`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Reset and regenerate the invite link for a group, invalidating the previous link.\n     *\n     * @param groupId - The ID of the group.\n     * @returns The new group invite link.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async resetGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n        };\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${groupId}/invite_link`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Delete the current invite link for a group.\n     *\n     * @param groupId - The ID of the group.\n     * @returns A success response confirming deletion.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async deleteGroupInviteLink(groupId: string): Promise<ResponseSuccess> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n        };\n        return this.sendJson(\n            HttpMethodsEnum.Delete,\n            `${groupId}/invite_link`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Get pending join requests for a group.\n     *\n     * @param groupId - The ID of the group.\n     * @returns A list of pending join requests.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async getJoinRequests(groupId: string): Promise<groups.GroupJoinRequestsResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${groupId}/join_requests`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Approve one or more pending join requests for a group.\n     *\n     * @param groupId - The ID of the group.\n     * @param joinRequestIds - Array of join request IDs to approve.\n     * @returns The result of the approval action.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async approveJoinRequests(\n        groupId: string,\n        joinRequestIds: string[],\n    ): Promise<groups.GroupJoinRequestsActionResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            join_requests: joinRequestIds,\n        };\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${groupId}/join_requests`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Reject one or more pending join requests for a group.\n     *\n     * @param groupId - The ID of the group.\n     * @param joinRequestIds - Array of join request IDs to reject.\n     * @returns The result of the rejection action.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async rejectJoinRequests(\n        groupId: string,\n        joinRequestIds: string[],\n    ): Promise<groups.GroupJoinRequestsActionResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            join_requests: joinRequestIds,\n        };\n        return this.sendJson(\n            HttpMethodsEnum.Delete,\n            `${groupId}/join_requests`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Add one or more participants to a group.\n     *\n     * @param groupId - The ID of the group.\n     * @param participants - Array of user WhatsApp IDs to add to the group.\n     * @returns A success response confirming the addition.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async addParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess> {\n        assertNonEmpty(participants, 'participants');\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            participants: participants.map((user) => ({ user })),\n        };\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${groupId}/participants`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Remove one or more participants from a group.\n     *\n     * @param groupId - The ID of the group.\n     * @param participants - Array of user WhatsApp IDs to remove from the group.\n     * @returns A success response confirming removal.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async removeParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess> {\n        assertNonEmpty(participants, 'participants');\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            participants: participants.map((user) => ({ user })),\n        };\n        return this.sendJson(\n            HttpMethodsEnum.Delete,\n            `${groupId}/participants`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n\n    /**\n     * Update group settings such as subject, description, or profile picture.\n     *\n     * @param groupId - The ID of the group to update.\n     * @param params - The settings to update.\n     * @param params.subject - Optional new group subject/name.\n     * @param params.description - Optional new group description.\n     * @param params.profilePictureFile - Optional profile picture as a Buffer or Blob.\n     * @returns The updated group settings response.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    async updateGroupSettings(\n        groupId: string,\n        params: groups.UpdateGroupSettingsRequest,\n    ): Promise<groups.GroupSettingsResponse> {\n        if (params.profilePictureFile) {\n            const formData = new FormData();\n            formData.append('messaging_product', WHATSAPP_MESSAGING_PRODUCT);\n            if (params.subject) formData.append('subject', params.subject);\n            if (params.description) formData.append('description', params.description);\n\n            if (params.profilePictureFile instanceof Buffer) {\n                const fileBlob = new globalThis.Blob([new Uint8Array(params.profilePictureFile)], {\n                    type: 'image/jpeg',\n                });\n                formData.append('file', fileBlob as unknown as Blob);\n            } else if (params.profilePictureFile instanceof Blob) {\n                formData.append('file', params.profilePictureFile);\n            } else {\n                throw new Error('Invalid profile picture file type. Use a Buffer or Blob.');\n            }\n\n            return this.sendFormData(\n                HttpMethodsEnum.Post,\n                groupId,\n                this.config[WabaConfigEnum.RequestTimeout],\n                formData,\n            );\n        }\n\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n        } as { messaging_product: 'whatsapp'; subject?: string; description?: string };\n\n        if (params.subject) body.subject = params.subject;\n        if (params.description) body.description = params.description;\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            groupId,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/marketing_messages\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\n\nimport type { MessagesResponse } from '../messages/types';\nimport type * as marketing from './types';\n\n/**\n * API for WhatsApp Marketing Messages.\n *\n * Provides methods to send marketing template messages to WhatsApp users,\n * with support for message activity sharing opt-in.\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/marketing_messages` - Send a marketing template message\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n */\nexport default class MarketingMessagesApi extends BaseAPI implements marketing.MarketingMessagesClass {\n    private readonly endpoint = 'marketing_messages';\n\n    /**\n     * Send a marketing template message to a WhatsApp user.\n     *\n     * @param params - The marketing message request parameters.\n     * @param params.to - The recipient's WhatsApp phone number.\n     * @param params.template - The template configuration (name, language, components).\n     * @param params.message_activity_sharing - Optional flag to enable message activity sharing.\n     * @param params.product_policy - Optional product policy for marketing messages.\n     * @returns The messages response with message ID and status.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n     */\n    async sendTemplateMessage(params: marketing.MarketingMessageRequest): Promise<MessagesResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            recipient_type: 'individual',\n            to: params.to,\n            type: 'template',\n            template: params.template,\n        } as {\n            messaging_product: 'whatsapp';\n            recipient_type: 'individual';\n            to: string;\n            type: 'template';\n            template: marketing.MarketingMessageRequest['template'];\n            message_activity_sharing?: boolean;\n            product_policy?: marketing.MarketingMessageRequest['product_policy'];\n        };\n\n        if (params.message_activity_sharing !== undefined) {\n            body.message_activity_sharing = params.message_activity_sharing;\n        }\n\n        if (params.product_policy !== undefined) {\n            body.product_policy = params.product_policy;\n        }\n\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(body),\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media/\n\n// Endpoints:\n// - GET /{MEDIA_ID}\n// - POST /{PHONE_NUMBER_ID}/media\n// - DELETE /{MEDIA_ID}\n// - GET {MEDIA_URL}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\n\nimport type * as media from './types';\n\n/**\n * WhatsApp Media API client for uploading, retrieving, downloading, and deleting media.\n *\n * Media uploaded to the WhatsApp API can be used in messages (images, audio, video,\n * documents, stickers). Each media object is identified by a unique media ID.\n *\n * **Covered endpoints:**\n * - `GET /{MEDIA_ID}` - Retrieve media info ({@link MediaApi.getMediaById})\n * - `POST /{PHONE_NUMBER_ID}/media` - Upload media ({@link MediaApi.uploadMedia})\n * - `DELETE /{MEDIA_ID}` - Delete media ({@link MediaApi.deleteMedia})\n * - `GET {MEDIA_URL}` - Download media content ({@link MediaApi.downloadMedia})\n *\n * **Supported media types and size limits:**\n * | Type | MIME Types | Max Size |\n * |------|-----------|----------|\n * | Audio | audio/aac, audio/mp4, audio/mpeg, audio/amr, audio/ogg | 16 MB |\n * | Document | Various (PDF, DOC, DOCX, PPT, XLS, etc.) | 100 MB |\n * | Image | image/jpeg, image/png | 5 MB |\n * | Sticker | image/webp | 100 KB (animated), 500 KB (static) |\n * | Video | video/mp4, video/3gp | 16 MB |\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media | WhatsApp Media API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media/ | WhatsApp Media Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...' });\n *\n * // Upload, send, then clean up\n * const { id } = await client.media.uploadMedia(file);\n * await client.messages.image({ body: { id }, to: '1234567890' });\n * await client.media.deleteMedia(id);\n * ```\n */\nexport default class MediaApi extends BaseAPI implements media.MediaClass {\n    private readonly endpoint = 'media';\n\n    /**\n     * Retrieves media information by media ID.\n     *\n     * Returns metadata about the media object including its URL, MIME type, file size,\n     * and SHA-256 hash. The returned URL can be used with {@link MediaApi.downloadMedia}\n     * to fetch the actual media content.\n     *\n     * **Endpoint:** `GET /{MEDIA_ID}`\n     *\n     * @param mediaId - The unique identifier of the media to retrieve\n     * @returns A promise resolving to the media metadata including `url`, `mime_type`, `sha256`, and `file_size`\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#get-media-id | Get Media ID Reference}\n     *\n     * @example\n     * ```ts\n     * const mediaInfo = await client.media.getMediaById('media_id_123');\n     * console.log(mediaInfo.url);       // URL to download the media\n     * console.log(mediaInfo.mime_type);  // e.g., \"image/jpeg\"\n     * console.log(mediaInfo.file_size);  // size in bytes\n     * ```\n     */\n    async getMediaById(mediaId: string): Promise<media.MediaResponse> {\n        return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n    }\n\n    /**\n     * Uploads a media file to the WhatsApp Cloud API.\n     *\n     * The uploaded media is assigned a unique media ID that can be used to send\n     * messages containing that media. Media is automatically encrypted and stored\n     * on Meta's servers.\n     *\n     * **Endpoint:** `POST /{PHONE_NUMBER_ID}/media`\n     *\n     * @param file - The `File` object to upload. The `type` property must match a supported MIME type.\n     * @param messagingProduct - The messaging product identifier (defaults to `'whatsapp'`)\n     * @returns A promise resolving to the upload response containing the assigned `id` (media ID)\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#upload-media | Upload Media Reference}\n     *\n     * @example\n     * ```ts\n     * const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' });\n     * const { id } = await client.media.uploadMedia(file);\n     * // Use the media ID to send an image message\n     * await client.messages.image({ body: { id }, to: '1234567890' });\n     * ```\n     */\n    async uploadMedia(\n        file: File,\n        messagingProduct: string = WHATSAPP_MESSAGING_PRODUCT,\n    ): 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.sendFormData(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            formData,\n        );\n    }\n\n    /**\n     * Deletes a media file from WhatsApp servers.\n     *\n     * Once deleted, the media ID can no longer be used in messages. Any messages\n     * already sent with this media will continue to display the media.\n     *\n     * **Endpoint:** `DELETE /{MEDIA_ID}`\n     *\n     * @param mediaId - The unique identifier of the media to delete\n     * @returns A promise resolving to a success response (`{ success: true }`)\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#delete-media | Delete Media Reference}\n     *\n     * @example\n     * ```ts\n     * const result = await client.media.deleteMedia('media_id_123');\n     * console.log(result.success); // true\n     * ```\n     */\n    async deleteMedia(mediaId: string): Promise<ResponseSuccess> {\n        return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n    }\n\n    /**\n     * Downloads media content from a WhatsApp media URL.\n     *\n     * Use {@link MediaApi.getMediaById} first to obtain the media URL, then pass it\n     * to this method to download the actual file content. The returned URL from\n     * `getMediaById` is only valid for a limited time.\n     *\n     * **Endpoint:** `GET {MEDIA_URL}`\n     *\n     * @param mediaUrl - The media download URL obtained from {@link MediaApi.getMediaById}\n     * @returns A promise resolving to a `Blob` containing the raw media data\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#download-media | Download Media Reference}\n     *\n     * @example\n     * ```ts\n     * // First get the media URL, then download it\n     * const mediaInfo = await client.media.getMediaById('media_id_123');\n     * const blob = await client.media.downloadMedia(mediaInfo.url);\n     * ```\n     */\n    async downloadMedia(mediaUrl: string): Promise<Blob> {\n        return this.sendJson(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout], null);\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/overview/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/message_history\n// - GET /{MESSAGE_HISTORY_ID}/events\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as messageHistory from './types';\n\nexport default class MessageHistoryApi extends BaseAPI implements messageHistory.MessageHistoryClass {\n    private resolveFields(fields?: messageHistory.MessageHistoryFieldsParam): string | undefined {\n        return Array.isArray(fields) ? fields.join(',') : fields;\n    }\n\n    async getMessageHistory(\n        params?: messageHistory.MessageHistoryListParams,\n    ): Promise<messageHistory.MessageHistoryResponse> {\n        const query = params\n            ? objectToQueryString({\n                  fields: this.resolveFields(params.fields),\n                  message_id: params.message_id,\n                  start_time: params.start_time,\n                  end_time: params.end_time,\n                  limit: params.limit,\n                  after: params.after,\n                  before: params.before,\n              })\n            : '';\n\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/message_history${query}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getMessageHistoryEvents(\n        messageHistoryId: string,\n        params?: messageHistory.MessageHistoryEventListParams,\n    ): Promise<messageHistory.MessageHistoryResponse> {\n        const query = params\n            ? objectToQueryString({\n                  fields: this.resolveFields(params.fields),\n                  status_filter: params.status_filter,\n                  limit: params.limit,\n                  after: params.after,\n                  before: params.before,\n              })\n            : '';\n\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${messageHistoryId}/events${query}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/messages\n// - POST /{PHONE_NUMBER_ID}/messages_encrypted\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport {\n    type ComponentTypesEnum,\n    HttpMethodsEnum,\n    type InteractiveTypesEnum,\n    MessageTypesEnum,\n    WabaConfigEnum,\n} from '../../types/enums';\nimport { assertPhoneNumber } from '../../utils/validate';\nimport type * as m from './types';\n\n/**\n * Maps each message type to its appropriate payload type.\n *\n * This conditional type resolves the correct payload interface based on the {@link MessageTypesEnum} value,\n * ensuring type-safe message construction at compile time.\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\n/**\n * WhatsApp Messages API client for sending various message types.\n *\n * Provides methods to send text, media, interactive, template, location, contact,\n * reaction, and status messages through the WhatsApp Cloud API.\n *\n * **Endpoint:** `POST /{PHONE_NUMBER_ID}/messages`\n *\n * **Covered operations:**\n * - {@link MessagesApi.text | text} - Send plain text messages\n * - {@link MessagesApi.audio | audio} - Send audio messages\n * - {@link MessagesApi.image | image} - Send image messages\n * - {@link MessagesApi.video | video} - Send video messages\n * - {@link MessagesApi.document | document} - Send document messages\n * - {@link MessagesApi.sticker | sticker} - Send sticker messages\n * - {@link MessagesApi.location | location} - Send location messages\n * - {@link MessagesApi.contacts | contacts} - Send contact card(s)\n * - {@link MessagesApi.template | template} - Send template messages\n * - {@link MessagesApi.interactive | interactive} - Send interactive messages (generic)\n * - {@link MessagesApi.interactiveList | interactiveList} - Send list interactive messages\n * - {@link MessagesApi.interactiveCtaUrl | interactiveCtaUrl} - Send CTA URL interactive messages\n * - {@link MessagesApi.interactiveLocationRequest | interactiveLocationRequest} - Send location request messages\n * - {@link MessagesApi.interactiveAddressMessage | interactiveAddressMessage} - Send address message interactive messages\n * - {@link MessagesApi.interactiveReplyButtons | interactiveReplyButtons} - Send reply button interactive messages\n * - {@link MessagesApi.interactiveFlow | interactiveFlow} - Send flow interactive messages\n * - {@link MessagesApi.interactiveCarousel | interactiveCarousel} - Send carousel interactive messages\n * - {@link MessagesApi.reaction | reaction} - Send reaction emoji to a message\n * - {@link MessagesApi.status | status} - Update message status (read, typing)\n * - {@link MessagesApi.markAsRead | markAsRead} - Mark a message as read\n * - {@link MessagesApi.showTypingIndicator | showTypingIndicator} - Show typing indicator\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | WhatsApp Messages API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/ | WhatsApp Messages Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...' });\n *\n * // Send a text message\n * await client.messages.text({ body: 'Hello!', to: '1234567890' });\n *\n * // Send an image\n * await client.messages.image({ body: { link: 'https://example.com/image.jpg' }, to: '1234567890' });\n * ```\n */\nexport default class MessagesApi extends BaseAPI implements m.MessagesClass {\n    private readonly commonMethod = HttpMethodsEnum.Post;\n    private readonly commonEndpoint = 'messages';\n\n    /**\n     * Builds the request body for WhatsApp API messages.\n     *\n     * Constructs a properly formatted message payload including the messaging product,\n     * recipient type, recipient phone number, message type, and optional reply context.\n     *\n     * @param type - The type of message to send (e.g., text, image, template)\n     * @param payload - The message payload object matching the specified type\n     * @param to - The recipient's phone number in international format (e.g., \"1234567890\")\n     * @param replyMessageId - Optional message ID to reply to, setting the message context\n     * @returns The formatted request body ready to be serialized and sent\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | Messages API Reference}\n     *\n     * @example\n     * ```ts\n     * const body = messagesApi.bodyBuilder(\n     *   MessageTypesEnum.Text,\n     *   { body: 'Hello!' },\n     *   '1234567890',\n     * );\n     * ```\n     */\n    bodyBuilder<T extends MessageTypesEnum>(\n        type: T,\n        payload: MessagePayloadType<T>,\n        to: string,\n        replyMessageId?: string,\n        recipientType: m.MessageRecipientType = 'individual',\n    ) {\n        if (recipientType === 'individual') assertPhoneNumber(to);\n        const body: m.MessageRequestBody<T> = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            recipient_type: recipientType,\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 Cloud API messages endpoint.\n     *\n     * Internal method that dispatches the serialized JSON body to\n     * `POST /{PHONE_NUMBER_ID}/messages`.\n     *\n     * @param body - The serialized JSON request body to send\n     * @returns A promise resolving to the WhatsApp messages API response containing the message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | Messages API Reference}\n     */\n    private send<T = m.MessagesResponse>(body: BodyInit | null): Promise<T> {\n        return this.sendJson<T>(\n            this.commonMethod,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.commonEndpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            body,\n        );\n    }\n\n    private sendEncrypted<T = m.EncryptedMessagesResponse>(body: BodyInit | null): Promise<T> {\n        return this.sendJson<T>(\n            this.commonMethod,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/messages_encrypted`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            body,\n        );\n    }\n\n    /**\n     * Sends an audio message via the WhatsApp Cloud API.\n     *\n     * The audio can be specified by a media ID (previously uploaded) or a public URL link.\n     * Supported formats: audio/aac, audio/mp4, audio/mpeg, audio/amr, audio/ogg (with opus codec).\n     * Maximum file size: 16 MB.\n     *\n     * @param params - The audio message parameters\n     * @param params.body - Audio media object containing either `id` (media ID) or `link` (URL)\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#audio-object | Audio Object Reference}\n     *\n     * @example\n     * ```ts\n     * // Send audio by URL\n     * await client.messages.audio({\n     *   body: { link: 'https://example.com/audio.mp3' },\n     *   to: '1234567890',\n     * });\n     *\n     * // Send audio by media ID\n     * await client.messages.audio({\n     *   body: { id: 'media_id_123' },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async audio(params: m.MessageRequestParams<m.AudioMediaObject>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Audio, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends one or more contact cards via the WhatsApp Cloud API.\n     *\n     * Contact messages allow sharing structured contact information including names,\n     * phone numbers, email addresses, and more.\n     *\n     * @param params - The contact message parameters\n     * @param params.body - Array of {@link m.ContactObject} containing contact details (name, phones, emails, etc.)\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#contacts-object | Contacts Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.contacts({\n     *   body: [{\n     *     name: { formatted_name: 'John Doe', first_name: 'John', last_name: 'Doe' },\n     *     phones: [{ phone: '+1234567890', type: 'MOBILE' }],\n     *   }],\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async contacts(params: m.MessageRequestParams<m.ContactObject[]>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Contacts, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends a document message via the WhatsApp Cloud API.\n     *\n     * Documents can be specified by media ID or public URL. Supports various formats\n     * including PDF, DOC, DOCX, PPT, PPTX, XLS, XLSX, and more.\n     * Maximum file size: 100 MB.\n     *\n     * @param params - The document message parameters\n     * @param params.body - Document media object containing `id` or `link`, and optional `caption` and `filename`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#document-object | Document Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.document({\n     *   body: {\n     *     link: 'https://example.com/report.pdf',\n     *     caption: 'Monthly Report',\n     *     filename: 'report.pdf',\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async document(params: m.MessageRequestParams<m.DocumentMediaObject>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Document, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends an image message via the WhatsApp Cloud API.\n     *\n     * Images can be specified by media ID or public URL.\n     * Supported formats: image/jpeg, image/png. Maximum file size: 5 MB.\n     *\n     * @param params - The image message parameters\n     * @param params.body - Image media object containing `id` or `link`, and optional `caption`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#image-object | Image Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.image({\n     *   body: { link: 'https://example.com/photo.jpg', caption: 'Check this out!' },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async image(params: m.MessageRequestParams<m.ImageMediaObject>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Image, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends an interactive message via the WhatsApp Cloud API.\n     *\n     * Interactive messages allow rich user interactions such as lists, buttons, CTAs,\n     * flows, location requests, address messages, and carousels. For type-specific\n     * convenience methods, see {@link MessagesApi.interactiveList}, {@link MessagesApi.interactiveReplyButtons}, etc.\n     *\n     * @param params - The interactive message parameters\n     * @param params.body - Interactive object containing the `type` and type-specific action/body/header/footer\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactive({\n     *   body: {\n     *     type: 'button',\n     *     body: { text: 'Choose an option' },\n     *     action: {\n     *       buttons: [\n     *         { type: 'reply', reply: { id: 'btn1', title: 'Option 1' } },\n     *         { type: 'reply', reply: { id: 'btn2', title: 'Option 2' } },\n     *       ],\n     *     },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async interactive(params: m.MessageRequestParams<m.InteractiveObject>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends a location message via the WhatsApp Cloud API.\n     *\n     * Shares a geographic location with the recipient, displayed as a map pin.\n     *\n     * @param params - The location message parameters\n     * @param params.body - Location object containing `latitude`, `longitude`, and optional `name` and `address`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#location-object | Location Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.location({\n     *   body: {\n     *     latitude: 37.4220936,\n     *     longitude: -122.083922,\n     *     name: 'Googleplex',\n     *     address: '1600 Amphitheatre Parkway, Mountain View, CA',\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async location(params: m.MessageRequestParams<m.LocationObject>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Location, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends a sticker message via the WhatsApp Cloud API.\n     *\n     * Stickers can be specified by media ID or public URL.\n     * Supported format: image/webp. Maximum file size: 100 KB (animated), 500 KB (static).\n     *\n     * @param params - The sticker message parameters\n     * @param params.body - Sticker media object containing `id` or `link`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#sticker-object | Sticker Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.sticker({\n     *   body: { link: 'https://example.com/sticker.webp' },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async sticker(params: m.MessageRequestParams<m.StickerMediaObject>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Sticker, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends a template message via the WhatsApp Cloud API.\n     *\n     * Template messages use pre-approved message templates and can include header,\n     * body, and button components with dynamic parameters. Templates must be\n     * approved before use.\n     *\n     * @param params - The template message parameters\n     * @param params.body - Template object containing `name`, `language`, and optional `components`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#template-object | Template Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.template({\n     *   body: {\n     *     name: 'hello_world',\n     *     language: { code: 'en_US' },\n     *     components: [\n     *       { type: 'body', parameters: [{ type: 'text', text: 'John' }] },\n     *     ],\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async template(\n        params: m.MessageRequestParams<m.MessageTemplateObject<ComponentTypesEnum>>,\n    ): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Template, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends a text message via the WhatsApp Cloud API.\n     *\n     * Sends a plain text message. The `body` can be a string or a {@link m.TextObject}.\n     * URL preview is enabled by default.\n     *\n     * @param params - The text message parameters\n     * @param params.body - Message text as a string, or a {@link m.TextObject} with `body` and optional `preview_url`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @param params.previewUrl - Whether to show a URL preview (defaults to `true`)\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#text-object | Text Object Reference}\n     *\n     * @example\n     * ```ts\n     * // Simple text\n     * await client.messages.text({ body: 'Hello, World!', to: '1234567890' });\n     *\n     * // With URL preview disabled\n     * await client.messages.text({\n     *   body: { body: 'Visit https://example.com', preview_url: false },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async text(params: m.TextMessageParams): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, previewUrl, recipientType } = 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(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Text, textPayload, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Sends a video message via the WhatsApp Cloud API.\n     *\n     * Videos can be specified by media ID or public URL.\n     * Supported formats: video/mp4, video/3gp. Maximum file size: 16 MB.\n     * Only H.264 video codec and AAC audio codec are supported.\n     *\n     * @param params - The video message parameters\n     * @param params.body - Video media object containing `id` or `link`, and optional `caption`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#video-object | Video Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.video({\n     *   body: { link: 'https://example.com/video.mp4', caption: 'Watch this!' },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async video(params: m.MessageRequestParams<m.VideoMediaObject>): Promise<m.MessagesResponse> {\n        const { body, to, replyMessageId, recipientType } = params;\n        return this.send(\n            JSON.stringify(this.bodyBuilder(MessageTypesEnum.Video, body, to, replyMessageId, recipientType)),\n        );\n    }\n\n    /**\n     * Updates the status of a message (e.g., mark as read or show typing indicator).\n     *\n     * This is the low-level status method. For convenience, use {@link MessagesApi.markAsRead}\n     * or {@link MessagesApi.showTypingIndicator} instead.\n     *\n     * @param params - The status update parameters\n     * @param params.status - The status to set (e.g., `'read'`, `'typing'`)\n     * @param params.messageId - The ID of the message to update\n     * @param params.typingIndicator - Optional typing indicator configuration\n     * @returns A promise resolving to the API response\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.status({\n     *   status: 'read',\n     *   messageId: 'wamid.ABC123',\n     * });\n     * ```\n     */\n    async status(params: m.StatusParams): Promise<m.StatusResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            status: params.status,\n            message_id: params.messageId,\n            ...(params.typingIndicator && { typing_indicator: params.typingIndicator }),\n        };\n\n        return this.send<m.StatusResponse>(JSON.stringify(body));\n    }\n\n    /**\n     * Marks a message as read, sending a read receipt to the sender.\n     *\n     * This is a convenience wrapper around {@link MessagesApi.status} that sets the status to `'read'`.\n     * When a message is marked as read, all previous messages in the conversation are also marked as read.\n     *\n     * @param params - The parameters\n     * @param params.messageId - The ID of the incoming message to mark as read (the `wamid` value)\n     * @returns A promise resolving to the API response\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.markAsRead({ messageId: 'wamid.ABC123' });\n     * ```\n     */\n    async markAsRead(params: { messageId: string }): Promise<m.StatusResponse> {\n        return this.status({\n            status: 'read',\n            messageId: params.messageId,\n        });\n    }\n\n    /**\n     * Shows a typing indicator to the user, indicating that a response is being composed.\n     *\n     * The typing indicator is displayed for approximately 25 seconds or until a message\n     * is sent, whichever comes first.\n     *\n     * @param params - The parameters\n     * @param params.messageId - The ID of the incoming message to associate the typing indicator with\n     * @returns A promise resolving to the API response\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.showTypingIndicator({ messageId: 'wamid.ABC123' });\n     * ```\n     */\n    async showTypingIndicator(params: { messageId: string }): Promise<m.StatusResponse> {\n        const body = {\n            messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n            status: 'typing',\n            message_id: params.messageId,\n            typing_indicator: { type: 'text' },\n        };\n\n        return this.send<m.StatusResponse>(JSON.stringify(body));\n    }\n\n    /**\n     * Sends a list interactive message via the WhatsApp Cloud API.\n     *\n     * List messages present up to 10 selectable options in a menu-style list.\n     * Each section can have a title and multiple rows with title, description, and ID.\n     *\n     * @param params - The list interactive message parameters\n     * @param params.body - Interactive object with `type: 'list'` and action containing sections\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#list-messages | List Messages Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactiveList({\n     *   body: {\n     *     type: 'list',\n     *     body: { text: 'Choose an option' },\n     *     action: {\n     *       button: 'View Options',\n     *       sections: [{ title: 'Section 1', rows: [{ id: '1', title: 'Option 1' }] }],\n     *     },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async interactiveList(\n        params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List | 'list' }>,\n    ): Promise<m.MessagesResponse> {\n        return this.interactive(params);\n    }\n\n    /**\n     * Sends a Call-to-Action (CTA) URL button interactive message via the WhatsApp Cloud API.\n     *\n     * CTA URL messages display a button that opens a URL when tapped.\n     *\n     * @param params - The CTA URL interactive message parameters\n     * @param params.body - Interactive object with `type: 'cta_url'` and action containing the URL and display text\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactiveCtaUrl({\n     *   body: {\n     *     type: 'cta_url',\n     *     body: { text: 'Visit our website' },\n     *     action: { name: 'cta_url', parameters: { display_text: 'Open', url: 'https://example.com' } },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async interactiveCtaUrl(\n        params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl | 'cta_url' }>,\n    ): Promise<m.MessagesResponse> {\n        return this.interactive(params);\n    }\n\n    /**\n     * Sends a location request interactive message via the WhatsApp Cloud API.\n     *\n     * Prompts the recipient to share their current location.\n     *\n     * @param params - The location request interactive message parameters\n     * @param params.body - Interactive object with `type: 'location_request_message'`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactiveLocationRequest({\n     *   body: {\n     *     type: 'location_request_message',\n     *     body: { text: 'Please share your location' },\n     *     action: { name: 'send_location' },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\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 via the WhatsApp Cloud API.\n     *\n     * Prompts the recipient to provide or confirm a shipping/delivery address.\n     *\n     * @param params - The address message interactive message parameters\n     * @param params.body - Interactive object with `type: 'address_message'`\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactiveAddressMessage({\n     *   body: {\n     *     type: 'address_message',\n     *     body: { text: 'Please confirm your delivery address' },\n     *     action: { name: 'address_message', parameters: { country: 'US' } },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\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 via the WhatsApp Cloud API.\n     *\n     * Reply button messages display up to 3 quick-reply buttons. Each button has\n     * a unique ID and title (up to 20 characters).\n     *\n     * @param params - The reply buttons interactive message parameters\n     * @param params.body - Interactive object with `type: 'button'` and action containing up to 3 reply buttons\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#reply-button | Reply Button Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactiveReplyButtons({\n     *   body: {\n     *     type: 'button',\n     *     body: { text: 'Do you agree?' },\n     *     action: {\n     *       buttons: [\n     *         { type: 'reply', reply: { id: 'yes', title: 'Yes' } },\n     *         { type: 'reply', reply: { id: 'no', title: 'No' } },\n     *       ],\n     *     },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async interactiveReplyButtons(\n        params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button | 'button' }>,\n    ): Promise<m.MessagesResponse> {\n        return this.interactive(params);\n    }\n\n    /**\n     * Sends a flow interactive message via the WhatsApp Cloud API.\n     *\n     * Flow messages launch a WhatsApp Flow, which provides structured multi-step interactions\n     * (forms, surveys, appointment booking, etc.) within the chat.\n     *\n     * @param params - The flow interactive message parameters\n     * @param params.body - Interactive object with `type: 'flow'` and action containing the flow token and configuration\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n     * @see {@link https://developers.facebook.com/docs/whatsapp/flows | WhatsApp Flows Documentation}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactiveFlow({\n     *   body: {\n     *     type: 'flow',\n     *     body: { text: 'Book an appointment' },\n     *     action: {\n     *       name: 'flow',\n     *       parameters: { flow_message_version: '3', flow_id: '123456', flow_cta: 'Book Now' },\n     *     },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async interactiveFlow(\n        params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow | 'flow' }>,\n    ): Promise<m.MessagesResponse> {\n        return this.interactive(params);\n    }\n\n    /**\n     * Sends a carousel interactive message via the WhatsApp Cloud API.\n     *\n     * Carousel messages display a horizontally scrollable set of cards, each with\n     * an image, body text, and up to 2 quick-reply buttons.\n     *\n     * @param params - The carousel interactive message parameters\n     * @param params.body - Interactive object with `type: 'carousel'` and action containing carousel cards\n     * @param params.to - Recipient phone number in international format\n     * @param params.replyMessageId - Optional message ID to reply to\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n     *\n     * @example\n     * ```ts\n     * await client.messages.interactiveCarousel({\n     *   body: {\n     *     type: 'carousel',\n     *     body: { text: 'Browse our products' },\n     *     action: {\n     *       cards: [\n     *         {\n     *           header: { type: 'image', image: { link: 'https://example.com/product1.jpg' } },\n     *           body: { text: 'Product 1 - $10' },\n     *           buttons: [{ type: 'reply', reply: { id: 'buy_1', title: 'Buy' } }],\n     *         },\n     *       ],\n     *     },\n     *   },\n     *   to: '1234567890',\n     * });\n     * ```\n     */\n    async interactiveCarousel(\n        params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Carousel }>,\n    ): Promise<m.MessagesResponse> {\n        return this.interactive(params);\n    }\n\n    /**\n     * Sends a reaction emoji to an existing message via the WhatsApp Cloud API.\n     *\n     * Reactions allow users to respond to messages with a single emoji.\n     * To remove a reaction, send an empty string as the emoji.\n     *\n     * @param params - The reaction parameters\n     * @param params.messageId - The ID of the message to react to\n     * @param params.emoji - The emoji character to react with (e.g., \"\\uD83D\\uDC4D\"), or empty string to remove reaction\n     * @param params.to - Recipient phone number in international format\n     * @returns A promise resolving to the message response with the sent message ID\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#reaction-object | Reaction Object Reference}\n     *\n     * @example\n     * ```ts\n     * // Add a reaction\n     * await client.messages.reaction({\n     *   messageId: 'wamid.ABC123',\n     *   emoji: '\\uD83D\\uDC4D',\n     *   to: '1234567890',\n     * });\n     *\n     * // Remove a reaction\n     * await client.messages.reaction({\n     *   messageId: 'wamid.ABC123',\n     *   emoji: '',\n     *   to: '1234567890',\n     * });\n     * ```\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(\n            JSON.stringify(\n                this.bodyBuilder(\n                    MessageTypesEnum.Reaction,\n                    reactionPayload,\n                    params.to,\n                    undefined,\n                    params.recipientType,\n                ),\n            ),\n        );\n    }\n\n    /**\n     * Send a message through the encrypted messages endpoint.\n     *\n     * The encrypted endpoint payload varies by encryption setup, so this method accepts\n     * the Graph API payload shape directly while preserving the endpoint and response type.\n     */\n    async encrypted(params: m.EncryptedMessageRequest): Promise<m.EncryptedMessagesResponse> {\n        return this.sendEncrypted(JSON.stringify(params));\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n\n// Endpoints:\n// - GET /{WABA_ID}/payment_configurations\n// - GET /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}\n// - POST /{WABA_ID}/payment_configuration\n// - POST /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}\n// - POST /{WABA_ID}/generate_payment_configuration_oauth_link\n// - DELETE /{WABA_ID}/payment_configuration\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\n\nimport type * as payments from './types';\n\n/**\n * API for WhatsApp Payments (India payment configuration).\n *\n * Provides methods to manage payment configurations for WhatsApp Business Accounts,\n * including creating, reading, updating, and deleting payment configurations,\n * as well as generating OAuth links for payment onboarding.\n *\n * Endpoints covered:\n * - `GET /{WABA_ID}/payment_configurations` - List all payment configurations\n * - `GET /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}` - Get a specific payment configuration\n * - `POST /{WABA_ID}/payment_configuration` - Create a new payment configuration\n * - `POST /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}` - Update a payment configuration\n * - `POST /{WABA_ID}/generate_payment_configuration_oauth_link` - Generate an OAuth link\n * - `DELETE /{WABA_ID}/payment_configuration` - Delete a payment configuration\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\nexport default class PaymentsApi extends BaseAPI implements payments.PaymentsClass {\n    /**\n     * List all payment configurations for a WhatsApp Business Account.\n     *\n     * @param wabaId - The WhatsApp Business Account ID.\n     * @returns A list of all payment configurations.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n     */\n    async listPaymentConfigurations(wabaId: string): Promise<payments.PaymentConfigurationsResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `/${wabaId}/payment_configurations`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Get a specific payment configuration by name.\n     *\n     * @param wabaId - The WhatsApp Business Account ID.\n     * @param configurationName - The name of the payment configuration to retrieve.\n     * @returns The payment configuration details.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n     */\n    async getPaymentConfiguration(\n        wabaId: string,\n        configurationName: string,\n    ): Promise<payments.PaymentConfigurationsResponse> {\n        const encodedName = encodeURIComponent(configurationName);\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `/${wabaId}/payment_configuration/${encodedName}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Create a new payment configuration for a WhatsApp Business Account.\n     *\n     * @param wabaId - The WhatsApp Business Account ID.\n     * @param params - The payment configuration details to create.\n     * @returns The created payment configuration response.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n     */\n    async createPaymentConfiguration(\n        wabaId: string,\n        params: payments.PaymentConfigurationCreateRequest,\n    ): Promise<payments.PaymentConfigurationCreateResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `/${wabaId}/payment_configuration`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    /**\n     * Update an existing payment configuration.\n     *\n     * @param wabaId - The WhatsApp Business Account ID.\n     * @param configurationName - The name of the payment configuration to update.\n     * @param params - The payment configuration fields to update.\n     * @returns The updated payment configuration response.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n     */\n    async updatePaymentConfiguration(\n        wabaId: string,\n        configurationName: string,\n        params: payments.PaymentConfigurationUpdateRequest,\n    ): Promise<payments.PaymentConfigurationUpdateResponse> {\n        const encodedName = encodeURIComponent(configurationName);\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `/${wabaId}/payment_configuration/${encodedName}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    /**\n     * Generate an OAuth link for payment configuration onboarding.\n     *\n     * @param wabaId - The WhatsApp Business Account ID.\n     * @param params - The OAuth link generation parameters.\n     * @returns The generated OAuth link response.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n     */\n    async generatePaymentConfigurationOauthLink(\n        wabaId: string,\n        params: payments.PaymentConfigurationOauthLinkRequest,\n    ): Promise<payments.PaymentConfigurationOauthLinkResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `/${wabaId}/generate_payment_configuration_oauth_link`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    /**\n     * Delete a payment configuration from a WhatsApp Business Account.\n     *\n     * @param wabaId - The WhatsApp Business Account ID.\n     * @param params - The payment configuration deletion parameters (includes configuration name).\n     * @returns A success response confirming deletion.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n     */\n    async deletePaymentConfiguration(\n        wabaId: string,\n        params: payments.PaymentConfigurationDeleteRequest,\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Delete,\n            `/${wabaId}/payment_configuration`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}?fields\n// - POST /{PHONE_NUMBER_ID}\n// - GET /{WABA_ID}/phone_numbers\n// - POST /{WABA_ID}/phone_numbers\n// - POST /{PHONE_NUMBER_ID}/request_code\n// - POST /{PHONE_NUMBER_ID}/verify_code\n// - GET /{PHONE_NUMBER_ID}/settings\n// - POST /{PHONE_NUMBER_ID}/settings\n// - POST /{PHONE_NUMBER_ID}/conversational_automation\n// - GET /{PHONE_NUMBER_ID}?fields=conversational_automation\n// - GET /{PHONE_NUMBER_ID}?fields=throughput\n// - GET /{PHONE_NUMBER_ID}/official_business_account\n// - POST /{PHONE_NUMBER_ID}/official_business_account\n// - GET /{PHONE_NUMBER_ID}/business_compliance_info\n// - POST /{PHONE_NUMBER_ID}/business_compliance_info\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as phoneNumber from './types';\n\n/**\n * API for managing WhatsApp Business phone numbers.\n *\n * This API provides methods for phone number management, verification,\n * and conversational automation configuration within the WhatsApp Business Platform.\n *\n * Covered endpoints:\n * - Get phone number info by ID (`GET /{PHONE_NUMBER_ID}`)\n * - List all phone numbers for a WABA (`GET /{WABA_ID}/phone_numbers`)\n * - Request a verification code (`POST /{PHONE_NUMBER_ID}/request_code`)\n * - Verify a phone number with a code (`POST /{PHONE_NUMBER_ID}/verify_code`)\n * - Set conversational automation config (`POST /{PHONE_NUMBER_ID}/conversational_automation`)\n * - Get conversational automation config (`GET /{PHONE_NUMBER_ID}?fields=conversational_automation`)\n * - Get throughput info (`GET /{PHONE_NUMBER_ID}?fields=throughput`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers | Phone Numbers API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Phone Numbers Documentation}\n */\nexport default class PhoneNumberApi extends BaseAPI implements phoneNumber.PhoneNumberClass {\n    private readonly endpoint = 'phone_numbers';\n\n    /**\n     * Get phone number information by ID.\n     *\n     * Retrieves details about the configured phone number, including display phone number,\n     * verified name, quality rating, platform type, and more. Use the `fields` parameter\n     * to request only specific fields.\n     *\n     * @param fields - Optional fields to include in the response. Can be a comma-separated\n     *   string (e.g., `'display_phone_number,verified_name'`) or an array of field names.\n     * @returns A promise that resolves with the phone number information.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#get-single | Get Phone Number}\n     *\n     * @example\n     * ```ts\n     * // Get all available fields\n     * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById();\n     *\n     * // Get specific fields as a comma-separated string\n     * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById(\n     *     'display_phone_number,verified_name,quality_rating'\n     * );\n     *\n     * // Get specific fields as an array\n     * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById(\n     *     ['display_phone_number', 'verified_name']\n     * );\n     * ```\n     */\n    async getPhoneNumberById(fields?: phoneNumber.PhoneNumberFieldsParam): Promise<phoneNumber.PhoneNumberResponse> {\n        const fieldValue = Array.isArray(fields) ? fields.join(',') : fields;\n        const queryParams = fieldValue ? objectToQueryString({ fields: fieldValue }) : '';\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 associated with the WhatsApp Business Account.\n     *\n     * Returns a list of all phone numbers registered under the configured WABA,\n     * including their verification status, quality rating, and display information.\n     *\n     * @param params - Optional list query parameters such as fields, filtering, sort, and paging.\n     * @returns A promise that resolves with the list of phone numbers.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#get-all | List Phone Numbers}\n     *\n     * @example\n     * ```ts\n     * const response = await whatsappClient.phoneNumber.getPhoneNumbers();\n     * for (const number of response.data) {\n     *     console.log(number.display_phone_number, number.verified_name);\n     * }\n     * ```\n     */\n    async getPhoneNumbers(params?: phoneNumber.PhoneNumbersListParams): Promise<phoneNumber.PhoneNumbersResponse> {\n        const fields = Array.isArray(params?.fields) ? params.fields.join(',') : params?.fields;\n        const filtering = Array.isArray(params?.filtering) ? JSON.stringify(params.filtering) : params?.filtering;\n        const queryParams = objectToQueryString({\n            fields,\n            filtering,\n            sort: params?.sort,\n            limit: params?.limit,\n            after: params?.after,\n            before: params?.before,\n        });\n\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${queryParams}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Create a phone number under a WABA.\n     *\n     * @param request - Phone number creation payload from the Graph API.\n     * @param wabaId - Optional WABA ID. Defaults to the configured business account ID.\n     */\n    async createPhoneNumber(\n        request: phoneNumber.CreatePhoneNumberRequest,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<phoneNumber.CreatePhoneNumberResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${wabaId}/${this.endpoint}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    /**\n     * Update phone number status or configuration on the phone number node.\n     */\n    async updatePhoneNumberStatus(request: phoneNumber.UpdatePhoneNumberStatusRequest): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    /**\n     * Request a verification code for the phone number.\n     *\n     * Sends a verification code to the configured phone number via SMS or voice call.\n     * This is the first step of the phone number verification process.\n     *\n     * @param request - The verification code request parameters.\n     * @param request.code_method - The delivery method for the code: `'SMS'` or `'VOICE'`.\n     * @param request.language - The language code for the verification message (e.g., `'en_US'`).\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#request-verification-code | Request Verification Code}\n     *\n     * @example\n     * ```ts\n     * await whatsappClient.phoneNumber.requestVerificationCode({\n     *     code_method: 'SMS',\n     *     language: 'en_US',\n     * });\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 a received verification code.\n     *\n     * Completes the phone number verification process by submitting the code\n     * received via SMS or voice call from {@link requestVerificationCode}.\n     *\n     * @param request - The verification request parameters.\n     * @param request.code - The 6-digit verification code received via SMS or voice call.\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#verify-code | Verify Code}\n     *\n     * @example\n     * ```ts\n     * await whatsappClient.phoneNumber.verifyCode({\n     *     code: '123456',\n     * });\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     * Get general phone number settings.\n     *\n     * Calling-specific settings can also be accessed through `calling.getCallingSettings()`.\n     */\n    async getPhoneNumberSettings(\n        params?: phoneNumber.PhoneNumberSettingsParams,\n    ): Promise<phoneNumber.PhoneNumberSettingsResponse> {\n        const fieldsValue = Array.isArray(params?.fields) ? params.fields.join(',') : params?.fields;\n        const queryParams = objectToQueryString({\n            ...(fieldsValue ? { fields: fieldsValue } : {}),\n            ...(params?.include_sip_credentials !== undefined\n                ? { include_sip_credentials: params.include_sip_credentials }\n                : {}),\n        });\n\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/settings${queryParams}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    /**\n     * Update general phone number settings.\n     */\n    async updatePhoneNumberSettings(params: phoneNumber.UpdatePhoneNumberSettingsRequest): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/settings`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    /**\n     * Configure conversational automation features for the phone number.\n     *\n     * Sets up welcome messages, ice breakers (prompts), and commands that users\n     * see when they open a conversation with the business phone number.\n     *\n     * @param request - The conversational automation configuration.\n     * @param request.enable_welcome_message - Optional. Enable or disable the welcome message.\n     * @param request.commands - Optional. Array of command objects with `command_name` and `command_description`.\n     * @param request.prompts - Optional. Array of ice breaker prompt strings shown to users.\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Conversational Automation}\n     *\n     * @example\n     * ```ts\n     * // Enable welcome message\n     * await whatsappClient.phoneNumber.setConversationalAutomation({\n     *     enable_welcome_message: true,\n     * });\n     *\n     * // Configure commands and ice breakers\n     * await whatsappClient.phoneNumber.setConversationalAutomation({\n     *     enable_welcome_message: true,\n     *     commands: [\n     *         { command_name: 'tickets', command_description: 'Book flight tickets' },\n     *         { command_name: 'hotel', command_description: 'Book a hotel room' },\n     *     ],\n     *     prompts: ['Book a flight', 'Plan a vacation'],\n     * });\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 conversational automation configuration for the phone number.\n     *\n     * Retrieves the current settings for welcome messages, ice breakers (prompts),\n     * and commands configured on the phone number.\n     *\n     * @returns A promise that resolves with the current conversational automation settings,\n     *   including welcome message status, commands, and prompts.\n     *\n     * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Conversational Automation}\n     *\n     * @example\n     * ```ts\n     * const config = await whatsappClient.phoneNumber.getConversationalAutomation();\n     * console.log(config.enable_welcome_message); // true or false\n     * console.log(config.commands);               // Array of command objects\n     * console.log(config.prompts);                // Array of ice breaker strings\n     * ```\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\n     * sent or received on this phone number.\n     *\n     * Throughput levels:\n     * - **STANDARD**: 80 MPS (default for most numbers)\n     * - **HIGH**: 1,000 MPS (automatic upgrade for eligible numbers)\n     * - **NOT_APPLICABLE**: Fixed at 5 MPS (WhatsApp Business app coexistence numbers)\n     *\n     * @returns A promise that resolves with the current throughput information,\n     *   including the throughput level.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers | Phone Numbers - Throughput}\n     *\n     * @example\n     * ```ts\n     * const throughput = await whatsappClient.phoneNumber.getThroughput();\n     * console.log(throughput.throughput.level); // 'STANDARD' | 'HIGH' | 'NOT_APPLICABLE'\n     * ```\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    async getOfficialBusinessAccountStatus(): Promise<phoneNumber.OfficialBusinessAccountStatusResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/official_business_account`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async updateOfficialBusinessAccountStatus(\n        params: phoneNumber.UpdateOfficialBusinessAccountStatusRequest,\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/official_business_account`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    async getBusinessComplianceInfo(): Promise<phoneNumber.BusinessComplianceInfoResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/business_compliance_info`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async updateBusinessComplianceInfo(\n        params: phoneNumber.UpdateBusinessComplianceInfoRequest,\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.PhoneNumberId]}/business_compliance_info`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-profiles/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_business_profile?fields\n// - POST /{PHONE_NUMBER_ID}/whatsapp_business_profile\n// - POST /app/uploads?file_length&file_type&file_name\n// - POST /{UPLOAD_ID}\n// - GET /{UPLOAD_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 * Business profiles let customers see relevant information about your business,\n * such as a description, email, address, website, and profile picture.\n *\n * Covered endpoints:\n * - Get business profile (`GET /{PHONE_NUMBER_ID}/whatsapp_business_profile`)\n * - Update business profile (`POST /{PHONE_NUMBER_ID}/whatsapp_business_profile`)\n * - Create an upload session for profile pictures (`POST /app/uploads`)\n * - Upload file binary data (`POST /{UPLOAD_ID}`)\n * - Get upload handle (`GET /{UPLOAD_ID}`)\n *\n * Profile picture upload follows a three-step process:\n * 1. Create an upload session ({@link createUploadSession})\n * 2. Upload the image binary data ({@link uploadMedia})\n * 3. Get the upload handle ({@link getUploadHandle}) and pass it to {@link updateBusinessProfile}\n *\n * Available business profile fields: `about`, `address`, `description`, `email`,\n * `profile_picture_url`, `websites`, `vertical`, `messaging_product`.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-profiles/ | Business Profiles Documentation}\n */\nexport default class BusinessProfileApi extends BaseAPI implements bp.BusinessProfileClass {\n    private readonly endpoint = 'whatsapp_business_profile';\n\n    /**\n     * Get your WhatsApp Business profile information.\n     *\n     * Retrieves the business profile details for the configured phone number.\n     * You can request all fields or specify a subset using the `fields` parameter.\n     *\n     * @param fields - Optional fields to return. Can be a comma-separated string\n     *   (e.g., `'about,address,email'`) or an array of field names. If omitted,\n     *   all fields are returned. Available fields: `about`, `address`, `description`,\n     *   `email`, `profile_picture_url`, `websites`, `vertical`.\n     * @returns A promise that resolves with the business profile information.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles#get-business-profile | Get Business Profile}\n     *\n     * @example\n     * ```ts\n     * // Get all business profile fields\n     * const profile = await whatsappClient.businessProfile.getBusinessProfile();\n     *\n     * // Get specific fields as a string\n     * const profile = await whatsappClient.businessProfile.getBusinessProfile('about,address,email');\n     *\n     * // Get specific fields as an array\n     * const profile = await whatsappClient.businessProfile.getBusinessProfile(['about', 'address', 'email']);\n     * ```\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 WhatsApp Business profile.\n     *\n     * Updates one or more fields of the business profile for the configured phone number.\n     * Only the fields included in the request body are updated; omitted fields remain unchanged.\n     *\n     * @param updateRequest - The profile fields to update.\n     * @param updateRequest.messaging_product - Required. Must be set to `'whatsapp'`.\n     * @param updateRequest.about - Optional. Business About text (1-139 characters).\n     * @param updateRequest.address - Optional. Business address (max 256 characters).\n     * @param updateRequest.description - Optional. Business description (max 512 characters).\n     * @param updateRequest.vertical - Optional. Business industry/category.\n     * @param updateRequest.email - Optional. Contact email address (max 128 characters).\n     * @param updateRequest.websites - Optional. Up to 2 website URLs (max 256 characters each).\n     * @param updateRequest.profile_picture_handle - Optional. Handle obtained from the upload process.\n     * @returns A promise that resolves with a success indicator.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles#update-business-profile | Update Business Profile}\n     *\n     * @example\n     * ```ts\n     * await whatsappClient.businessProfile.updateBusinessProfile({\n     *     messaging_product: 'whatsapp',\n     *     about: 'We provide excellent service',\n     *     description: 'Your trusted partner for quality products',\n     *     email: 'contact@example.com',\n     *     websites: ['https://example.com'],\n     * });\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 **step 1** of the three-step profile picture upload process.\n     * It initializes a resumable upload session on the server and returns a session ID\n     * to use in subsequent upload calls.\n     *\n     * @param fileLength - The size of the file in bytes.\n     * @param fileType - The MIME type of the file (e.g., `'image/jpeg'`, `'image/png'`).\n     * @param fileName - The file name with extension (e.g., `'profile.jpg'`).\n     * @returns A promise that resolves with the upload session ID.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n     *\n     * @example\n     * ```ts\n     * const session = await whatsappClient.businessProfile.createUploadSession(\n     *     fileBuffer.length,\n     *     'image/jpeg',\n     *     'profile.jpg',\n     * );\n     * console.log(session.upload_session_id);\n     * ```\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 binary data to an upload session.\n     *\n     * This is **step 2** of the three-step profile picture upload process.\n     * Uploads the raw binary content of the image to the previously created upload session.\n     *\n     * @param uploadId - The upload session ID returned from {@link createUploadSession}.\n     * @param file - The binary data of the file as a Buffer.\n     * @returns A promise that resolves with the upload response.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n     *\n     * @example\n     * ```ts\n     * const fileBuffer = fs.readFileSync('profile.jpg');\n     * await whatsappClient.businessProfile.uploadMedia(\n     *     session.upload_session_id,\n     *     fileBuffer,\n     * );\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 for a completed upload.\n     *\n     * This is **step 3** of the three-step profile picture upload process.\n     * After uploading the file binary, retrieve the handle to use when updating\n     * the business profile's `profile_picture_handle` field.\n     *\n     * @param uploadId - The upload session ID returned from {@link createUploadSession}.\n     * @returns A promise that resolves with the upload handle information.\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n     *\n     * @example\n     * ```ts\n     * // Complete three-step profile picture upload\n     * const session = await whatsappClient.businessProfile.createUploadSession(\n     *     fileBuffer.length, 'image/jpeg', 'profile.jpg',\n     * );\n     * await whatsappClient.businessProfile.uploadMedia(session.upload_session_id, fileBuffer);\n     * const handleInfo = await whatsappClient.businessProfile.getUploadHandle(session.upload_session_id);\n     *\n     * // Use the handle to update the profile picture\n     * await whatsappClient.businessProfile.updateBusinessProfile({\n     *     messaging_product: 'whatsapp',\n     *     profile_picture_handle: handleInfo.handle,\n     * });\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/message_qrdls\n// - GET /{PHONE_NUMBER_ID}/message_qrdls\n// - GET /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}\n// - POST /{PHONE_NUMBER_ID}/message_qrdls\n// - DELETE /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/message_qrdls` - Create a new QR code\n * - `GET /{PHONE_NUMBER_ID}/message_qrdls` - Get all QR codes\n * - `GET /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Get a specific QR code\n * - `POST /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Update a QR code\n * - `DELETE /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Delete a QR code\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\n */\nexport default class QrCodeApi extends BaseAPI implements qrCode.QrCodeClass {\n    private readonly endpoint = 'message_qrdls';\n\n    /**\n     * Create a new QR code with a prefilled message.\n     *\n     * @param request - The QR code creation request containing the prefilled message and optional image format.\n     * @returns QR code information including code, deep link URL, and optional image URL.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/register\n// - POST /{PHONE_NUMBER_ID}/deregister\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { type DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/register` - Register a phone number\n * - `POST /{PHONE_NUMBER_ID}/deregister` - Deregister a phone number\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\n */\nexport default class RegistrationApi extends BaseAPI implements registration.RegistrationClass {\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 for storage compliance.\n     * @returns Response indicating success or failure.\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\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_MESSAGING_PRODUCT,\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\n// Endpoints:\n// - POST /{APPLICATION_ID}/whatsapp_business_solution\n// - GET /{APPLICATION_ID}/whatsapp_business_solutions\n// - GET /{SOLUTION_ID}/access_token\n// - POST /{SOLUTION_ID}/accept_deactivation_request\n// - POST /{SOLUTION_ID}/accept\n// - GET /{SOLUTION_ID}\n// - POST /{SOLUTION_ID}/reject_deactivation_request\n// - POST /{SOLUTION_ID}/reject\n// - POST /{SOLUTION_ID}/send_deactivation_request\n// - GET /{MIGRATION_INTENT_ID}\n// - GET /{WABA_ID}/solutions\n// - POST /{WABA_ID}/set_solution_migration_intent\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as solutions from './types';\n\nexport default class SolutionsApi extends BaseAPI implements solutions.SolutionsClass {\n    private toQuery(params?: solutions.SolutionListParams): string {\n        if (!params) return '';\n\n        const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n        return objectToQueryString({\n            fields,\n            role: params.role,\n            status: params.status,\n            limit: params.limit,\n            after: params.after,\n            before: params.before,\n        });\n    }\n\n    private fieldsQuery(fields?: solutions.SolutionFieldsParam): string {\n        const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n        return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\n    }\n\n    async createWhatsAppBusinessSolution(\n        applicationId: string,\n        request: solutions.CreateWhatsAppBusinessSolutionRequest,\n    ): Promise<solutions.SolutionGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${applicationId}/whatsapp_business_solution`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async getApplicationWhatsAppBusinessSolutions(\n        applicationId: string,\n        params?: solutions.SolutionListParams,\n    ): Promise<solutions.SolutionListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${applicationId}/whatsapp_business_solutions${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getSolutionAccessToken(\n        solutionId: string,\n        fields?: solutions.SolutionFieldsParam,\n    ): Promise<solutions.SolutionGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${solutionId}/access_token${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async acceptSolutionDeactivationRequest(\n        solutionId: string,\n        request: solutions.SolutionDeactivationRequest = {},\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${solutionId}/accept_deactivation_request`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async acceptSolution(solutionId: string, request: solutions.AcceptSolutionRequest = {}): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${solutionId}/accept`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async getSolutionDetails(\n        solutionId: string,\n        fields?: solutions.SolutionFieldsParam,\n    ): Promise<solutions.SolutionGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${solutionId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async rejectSolutionDeactivationRequest(\n        solutionId: string,\n        request: solutions.SolutionDeactivationRequest = {},\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${solutionId}/reject_deactivation_request`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async rejectSolutionRequest(\n        solutionId: string,\n        request: solutions.RejectSolutionRequest = {},\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${solutionId}/reject`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async sendSolutionDeactivationRequest(\n        solutionId: string,\n        request: solutions.SolutionDeactivationRequest = {},\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${solutionId}/send_deactivation_request`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n\n    async getMigrationIntentDetails(\n        migrationIntentId: string,\n        fields?: solutions.SolutionFieldsParam,\n    ): Promise<solutions.SolutionGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${migrationIntentId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async listWabaSolutions(\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n        params?: solutions.SolutionListParams,\n    ): Promise<solutions.SolutionListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${wabaId}/solutions${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async setSolutionMigrationIntent(\n        wabaId: string,\n        request: solutions.SetSolutionMigrationIntentRequest,\n    ): Promise<solutions.SolutionGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${wabaId}/set_solution_migration_intent`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(request),\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/\n\nimport { CategoryEnum } from '../../../types/enums';\nimport type {\n    AuthenticationTemplateOptions,\n    BodyOptions,\n    ButtonOptions,\n    CatalogTemplateOptions,\n    ComponentTypes,\n    CouponTemplateOptions,\n    FooterOptions,\n    HeaderOptions,\n    LimitedTimeOfferTemplateOptions,\n    MediaCardCarouselTemplateOptions,\n    MediaCarouselCard,\n    MPMTemplateOptions,\n    OTPTemplateOptions,\n    ProductCardCarouselTemplateOptions,\n    ProductCarouselCard,\n    SPMTemplateOptions,\n    TemplateBody,\n    TemplateButton,\n    TemplateButtons,\n    TemplateFooter,\n    TemplateHeader,\n    TemplateOptions,\n    TemplateParameter,\n    TemplateRequestBody,\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/\n\n// Endpoints:\n// - GET /{TEMPLATE_ID}\n// - POST /{TEMPLATE_ID}\n// - GET /{WABA_ID}/message_templates?...\n// - POST /{WABA_ID}/message_templates\n// - DELETE /{WABA_ID}/message_templates?...\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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\n/**\n * WhatsApp Message Templates API client for managing message templates.\n *\n * Message templates are pre-approved message formats that businesses can use to\n * send notifications and customer care messages. Templates must be approved by\n * Meta before they can be used to send messages.\n *\n * **Covered endpoints:**\n * - `GET /{TEMPLATE_ID}` - Get a single template ({@link TemplateApi.getTemplate})\n * - `POST /{TEMPLATE_ID}` - Update an existing template ({@link TemplateApi.updateTemplate})\n * - `GET /{WABA_ID}/message_templates` - List all templates ({@link TemplateApi.getTemplates})\n * - `POST /{WABA_ID}/message_templates` - Create a new template ({@link TemplateApi.createTemplate})\n * - `DELETE /{WABA_ID}/message_templates` - Delete a template ({@link TemplateApi.deleteTemplate})\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/ | WhatsApp Templates Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...', businessAcctId: '...' });\n *\n * // Create a template\n * const template = await client.template.createTemplate({\n *   name: 'hello_world',\n *   language: 'en_US',\n *   category: 'MARKETING',\n *   components: [{ type: 'BODY', text: 'Hello {{1}}!' }],\n * });\n *\n * // List all templates\n * const templates = await client.template.getTemplates();\n * ```\n */\nexport default class TemplateApi extends BaseAPI implements TemplateClass {\n    private readonly endpoint = 'message_templates';\n\n    /**\n     * Retrieves a single message template by its ID.\n     *\n     * Returns the full template definition including name, language, status,\n     * category, and components.\n     *\n     * **Endpoint:** `GET /{TEMPLATE_ID}`\n     *\n     * @param templateId - The unique identifier of the template to retrieve\n     * @returns A promise resolving to the template details\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n     *\n     * @example\n     * ```ts\n     * const template = await client.template.getTemplate('template_id_123');\n     * console.log(template.name);     // e.g., \"hello_world\"\n     * console.log(template.status);   // e.g., \"APPROVED\"\n     * ```\n     */\n    async getTemplate(templateId: string): Promise<TemplateResponse> {\n        return this.sendJson(HttpMethodsEnum.Get, `${templateId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n    }\n\n    /**\n     * Updates an existing message template.\n     *\n     * Allows modifying template components and other properties. Note that editing\n     * an approved template will resubmit it for review, changing its status back\n     * to `PENDING`.\n     *\n     * **Endpoint:** `POST /{TEMPLATE_ID}`\n     *\n     * @param templateId - The unique identifier of the template to update\n     * @param template - Partial template body containing only the fields to update\n     * @returns A promise resolving to a success response (`{ success: true }`)\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n     *\n     * @example\n     * ```ts\n     * await client.template.updateTemplate('template_id_123', {\n     *   components: [{ type: 'BODY', text: 'Updated greeting: Hello {{1}}!' }],\n     * });\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    /**\n     * Lists message templates for the WhatsApp Business Account.\n     *\n     * Returns a paginated list of templates, optionally filtered by query parameters\n     * such as category, language, name, status, or quality score.\n     *\n     * **Endpoint:** `GET /{WABA_ID}/message_templates`\n     *\n     * @param params - Optional query parameters to filter results\n     * @param params.category - Filter by template category (e.g., `'MARKETING'`, `'UTILITY'`)\n     * @param params.content - Filter by template content\n     * @param params.language - Filter by language code (e.g., `'en_US'`)\n     * @param params.name - Filter by exact template name\n     * @param params.name_or_content - Filter by name or content (search)\n     * @param params.quality_score - Filter by quality score\n     * @param params.status - Filter by template status (e.g., `'APPROVED'`, `'PENDING'`, `'REJECTED'`)\n     * @returns A promise resolving to a paginated response containing an array of templates\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n     *\n     * @example\n     * ```ts\n     * // List all templates\n     * const allTemplates = await client.template.getTemplates();\n     *\n     * // Filter by category and status\n     * const approved = await client.template.getTemplates({\n     *   category: 'MARKETING',\n     *   status: 'APPROVED',\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    /**\n     * Creates a new message template for the WhatsApp Business Account.\n     *\n     * The template will be submitted for review. Once approved, it can be used\n     * to send template messages via {@link MessagesApi.template}.\n     *\n     * **Endpoint:** `POST /{WABA_ID}/message_templates`\n     *\n     * @param template - The template definition\n     * @param template.name - Template name (lowercase alphanumeric and underscores only)\n     * @param template.language - Language code (e.g., `'en_US'`)\n     * @param template.category - Template category (`'MARKETING'`, `'UTILITY'`, or `'AUTHENTICATION'`)\n     * @param template.components - Array of template components (header, body, footer, buttons)\n     * @param template.allow_category_change - Whether Meta can auto-assign a different category\n     * @param template.parameter_format - Parameter format (`'POSITIONAL'` or `'NAMED'`)\n     * @param template.sub_category - Optional sub-category for the template\n     * @param template.message_send_ttl_seconds - Optional TTL in seconds for message delivery attempts\n     * @returns A promise resolving to the created template response with its assigned `id` and `status`\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n     *\n     * @example\n     * ```ts\n     * const template = await client.template.createTemplate({\n     *   name: 'order_confirmation',\n     *   language: 'en_US',\n     *   category: 'UTILITY',\n     *   components: [\n     *     { type: 'BODY', text: 'Your order {{1}} has been confirmed.' },\n     *   ],\n     * });\n     * console.log(template.id);     // Template ID\n     * console.log(template.status); // \"PENDING\"\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    /**\n     * Deletes a message template from the WhatsApp Business Account.\n     *\n     * Deleting a template removes all language variations of that template.\n     * To delete a specific language version, provide the `hsm_id` parameter.\n     *\n     * **Endpoint:** `DELETE /{WABA_ID}/message_templates`\n     *\n     * @param params - The delete parameters\n     * @param params.name - The name of the template to delete (required)\n     * @param params.hsm_id - Optional template ID to delete a specific language version\n     * @returns A promise resolving to a success response (`{ success: true }`)\n     *\n     * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n     *\n     * @example\n     * ```ts\n     * // Delete all language versions of a template\n     * await client.template.deleteTemplate({ name: 'old_template' });\n     *\n     * // Delete a specific language version\n     * await client.template.deleteTemplate({ name: 'old_template', hsm_id: '123456' });\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}` - Set two-step verification PIN\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\n */\nexport default class TwoStepVerificationApi extends BaseAPI implements twoStepVerification.TwoStepVerificationClass {\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\n// Endpoints:\n// - GET /{WABA_ID}?fields\n// - POST /{WABA_ID}\n// - GET /{WABA_ID}/activities\n// - GET /{WABA_ID}/subscribed_apps\n// - POST /{WABA_ID}/subscribed_apps\n// - DELETE /{WABA_ID}/subscribed_apps\n// - GET /{WABA_ID}/assigned_users\n// - POST /{WABA_ID}/assigned_users\n// - DELETE /{WABA_ID}/assigned_users\n// - GET /{WABA_ID}/in_progress_onbehalf_request\n// - GET /{OBO_MOBILITY_INTENT_ID}\n// - POST /{WABA_ID}/obo_mobility_intent\n// - POST /{WABA_ID}/set_obo_mobility_intent\n// - GET /{WABA_ID}/schedules\n// - POST /{WABA_ID}/schedules\n// - GET /{WABA_BOT_ID}\n// - GET /{WHATSAPP_BUSINESS_PROFILE_ID}\n// - POST /{WHATSAPP_BUSINESS_PROFILE_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\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 *\n * Endpoints covered:\n * - `GET /{WABA_ID}` - Get WABA account information\n * - `GET /{WABA_ID}/subscribed_apps` - Get all WABA subscriptions\n * - `POST /{WABA_ID}/subscribed_apps` - Update/create a WABA subscription\n * - `DELETE /{WABA_ID}/subscribed_apps` - Unsubscribe from WABA webhooks\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n */\nexport default class WabaApi extends BaseAPI implements waba.WABAClass {\n    private toQuery(params?: waba.WabaListParams): string {\n        if (!params) return '';\n\n        const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n        const filtering = Array.isArray(params.filtering) ? JSON.stringify(params.filtering) : params.filtering;\n\n        return objectToQueryString({\n            fields,\n            filtering,\n            sort: params.sort,\n            limit: params.limit,\n            after: params.after,\n            before: params.before,\n        });\n    }\n\n    private fieldsQuery(fields?: waba.WabaFieldsParam): string {\n        const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n        return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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     * Update WABA account fields such as name or timezone.\n     */\n    async updateWabaAccount(params: waba.UpdateWabaAccountRequest): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${this.config[WabaConfigEnum.BusinessAcctId]}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    /**\n     * Get account activity events for a WABA.\n     */\n    async getWabaActivities(params?: waba.WabaListParams): Promise<waba.WabaListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${this.config[WabaConfigEnum.BusinessAcctId]}/activities${this.toQuery(params)}`,\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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    async getAssignedUsers(\n        params: waba.AssignedUsersListParams,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<waba.WabaListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${wabaId}/assigned_users${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async addAssignedUser(\n        params: waba.AssignedUserRequest,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<ResponseSuccess> {\n        const body = {\n            user: params.user,\n            tasks: params.tasks,\n        };\n\n        return this.sendUrlEncodedForm(\n            HttpMethodsEnum.Post,\n            `${wabaId}/assigned_users`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            body,\n        );\n    }\n\n    async removeAssignedUser(\n        params: waba.RemoveAssignedUserRequest,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<ResponseSuccess> {\n        return this.sendUrlEncodedForm(\n            HttpMethodsEnum.Delete,\n            `${wabaId}/assigned_users`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            { user: params.user },\n        );\n    }\n\n    async getInProgressOnBehalfRequests(\n        params?: waba.WabaListParams,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<waba.WabaListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${wabaId}/in_progress_onbehalf_request${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getOBOMobilityIntent(\n        oboMobilityIntentId: string,\n        fields?: waba.WabaFieldsParam,\n    ): Promise<waba.WabaGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${oboMobilityIntentId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async createOBOMobilityIntent(\n        params: waba.CreateOBOMobilityIntentRequest,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<waba.WabaGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${wabaId}/obo_mobility_intent`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    async setOBOMobilityIntent(\n        params: waba.SetOBOMobilityIntentRequest,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<waba.WabaGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${wabaId}/set_obo_mobility_intent`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    async getWabaSchedules(\n        params?: waba.WabaListParams,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<waba.WabaListResponse> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${wabaId}/schedules${this.toQuery(params)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async createWabaSchedule(\n        params: waba.CreateScheduleRequest,\n        wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n    ): Promise<waba.WabaGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            `${wabaId}/schedules`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n\n    async getWhatsAppBusinessBotDetails(botId: string, fields?: waba.WabaFieldsParam): Promise<waba.WabaGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${botId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async getWhatsAppBusinessProfileDetails(\n        profileId: string,\n        fields?: waba.WabaFieldsParam,\n    ): Promise<waba.WabaGraphObject> {\n        return this.sendJson(\n            HttpMethodsEnum.Get,\n            `${profileId}${this.fieldsQuery(fields)}`,\n            this.config[WabaConfigEnum.RequestTimeout],\n            null,\n        );\n    }\n\n    async updateWhatsAppBusinessProfile(\n        profileId: string,\n        params: waba.UpdateWhatsAppBusinessProfileRequest,\n    ): Promise<ResponseSuccess> {\n        return this.sendJson(\n            HttpMethodsEnum.Post,\n            profileId,\n            this.config[WabaConfigEnum.RequestTimeout],\n            JSON.stringify(params),\n        );\n    }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\nimport type { Paging, 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    timezone_id?: string;\n    primary_business_location?: Record<string, unknown> | string;\n    currency?: string;\n    country?: string;\n    analytics?: Record<string, unknown>;\n    is_enabled_for_insights?: boolean;\n    is_shared_with_partners?: boolean;\n    marketing_messages_lite_api_status?: string;\n    marketing_messages_onboarding_status?: string;\n    on_behalf_of_business_info?: Record<string, unknown>;\n    primary_funding_id?: string;\n    purchase_order_number?: string;\n    whatsapp_business_manager_messaging_limit?: string;\n}\n\n/**\n * Available fields for WABA account queries\n */\nexport type WabaAccountFields =\n    | 'id'\n    | 'name'\n    | 'timezone_id'\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    | 'primary_business_location'\n    | 'analytics'\n    | 'is_enabled_for_insights'\n    | 'is_shared_with_partners'\n    | 'marketing_messages_lite_api_status'\n    | 'marketing_messages_onboarding_status'\n    | 'on_behalf_of_business_info'\n    | 'primary_funding_id'\n    | 'purchase_order_number'\n    | 'whatsapp_business_manager_messaging_limit';\n\n/**\n * Parameter type for specifying which WABA account fields to retrieve\n */\nexport type WabaAccountFieldsParam = WabaAccountFields[];\n\nexport type WabaGraphObject = Record<string, unknown>;\n\nexport type WabaFieldsParam = string[] | string;\n\nexport type WabaListParams = {\n    fields?: WabaFieldsParam;\n    filtering?: WabaGraphObject[] | string;\n    sort?: string;\n    limit?: number;\n    after?: string;\n    before?: string;\n};\n\nexport type WabaListResponse<T = WabaGraphObject> = {\n    data: T[];\n    paging?: Paging;\n    summary?: WabaGraphObject;\n};\n\nexport type UpdateWabaAccountRequest = {\n    name?: string;\n    timezone_id?: string;\n    [key: string]: unknown;\n};\n\nexport type AssignedUsersListParams = WabaListParams & {\n    business: string;\n};\n\nexport type AssignedUserRequest = {\n    user: string;\n    tasks: string[];\n};\n\nexport type RemoveAssignedUserRequest = {\n    user: string;\n    [key: string]: unknown;\n};\n\nexport type CreateOBOMobilityIntentRequest = {\n    intent?: string;\n    [key: string]: unknown;\n};\n\nexport type SetOBOMobilityIntentRequest = {\n    [key: string]: unknown;\n};\n\nexport type CreateScheduleRequest = {\n    name?: string;\n    schedule_type?: string;\n    [key: string]: unknown;\n};\n\nexport type UpdateWhatsAppBusinessProfileRequest = {\n    [key: string]: unknown;\n};\n\n/**\n * Interface defining all WABA API methods\n */\nexport interface WABAClass {\n    getWabaAccount(fields?: WabaAccountFieldsParam): Promise<WabaAccount>;\n    updateWabaAccount(params: UpdateWabaAccountRequest): Promise<ResponseSuccess>;\n    getWabaActivities(params?: WabaListParams): Promise<WabaListResponse>;\n    getAllWabaSubscriptions(): Promise<WabaSubscriptions>;\n    updateWabaSubscription(params: UpdateWabaSubscription): Promise<ResponseSuccess>;\n    unsubscribeFromWaba(): Promise<ResponseSuccess>;\n    getAssignedUsers(params: AssignedUsersListParams, wabaId?: string): Promise<WabaListResponse>;\n    addAssignedUser(params: AssignedUserRequest, wabaId?: string): Promise<ResponseSuccess>;\n    removeAssignedUser(params: RemoveAssignedUserRequest, wabaId?: string): Promise<ResponseSuccess>;\n    getInProgressOnBehalfRequests(params?: WabaListParams, wabaId?: string): Promise<WabaListResponse>;\n    getOBOMobilityIntent(oboMobilityIntentId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n    createOBOMobilityIntent(params: CreateOBOMobilityIntentRequest, wabaId?: string): Promise<WabaGraphObject>;\n    setOBOMobilityIntent(params: SetOBOMobilityIntentRequest, wabaId?: string): Promise<WabaGraphObject>;\n    getWabaSchedules(params?: WabaListParams, wabaId?: string): Promise<WabaListResponse>;\n    createWabaSchedule(params: CreateScheduleRequest, wabaId?: string): Promise<WabaGraphObject>;\n    getWhatsAppBusinessBotDetails(botId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n    getWhatsAppBusinessProfileDetails(profileId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n    updateWhatsAppBusinessProfile(\n        profileId: string,\n        params: UpdateWhatsAppBusinessProfileRequest,\n    ): Promise<ResponseSuccess>;\n}\n","// @ts-nocheck\nimport { inspect } from 'node: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';\nimport {\n    DEFAULT_CLOUD_API_VERSION,\n    DEFAULT_LISTENER_PORT,\n    DEFAULT_MAX_RETRIES_AFTER_WAIT,\n    DEFAULT_REQUEST_TIMEOUT,\n} from './defaults';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\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]:\n            inputConfig?.phoneNumberId || (process.env.WA_PHONE_NUMBER_ID ? Number(process.env.WA_PHONE_NUMBER_ID) : 0),\n        [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n        [WabaConfigEnum.APIVersion]:\n            inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || DEFAULT_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 || '', 10) || DEFAULT_LISTENER_PORT,\n        [WabaConfigEnum.MaxRetriesAfterWait]:\n            inputConfig?.maxRetriesAfterWait ||\n            parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '', 10) ||\n            DEFAULT_MAX_RETRIES_AFTER_WAIT,\n        [WabaConfigEnum.RequestTimeout]:\n            inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '', 10) || 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        retry: inputConfig?.retry,\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 'node:crypto';\n\nimport type { FlowEndpointRequest } from '../api/flow';\nimport type { 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?.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: crypto.KeyObject;\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 (first attempt):', {\n            error: error instanceof Error ? error.message : error,\n            hasPassphrase: !!passphrase,\n            format: isPKCS8 ? 'PKCS#8' : isPKCS1 ? 'PKCS#1' : 'Unknown',\n        });\n\n        // If PKCS#1 key failed, try to convert it to PKCS#8 format automatically\n        if (isPKCS1 && passphrase) {\n            try {\n                LOGGER.info('[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format');\n\n                // First, load the PKCS#1 key with passphrase\n                const pkcs1Key = crypto.createPrivateKey({\n                    key: privatePem,\n                    format: 'pem',\n                    passphrase,\n                });\n\n                // Export it as PKCS#8 with the same passphrase\n                const pkcs8Pem = pkcs1Key.export({\n                    type: 'pkcs8',\n                    format: 'pem',\n                    cipher: 'aes-256-cbc',\n                    passphrase,\n                });\n\n                // Now create the private key from PKCS#8 format\n                privateKey = crypto.createPrivateKey({\n                    key: pkcs8Pem as string,\n                    format: 'pem',\n                    passphrase,\n                });\n\n                LOGGER.info('[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key');\n            } catch (conversionError) {\n                LOGGER.error('[decryptFlowRequest] Failed to convert PKCS#1 to PKCS#8:', {\n                    error: conversionError instanceof Error ? conversionError.message : conversionError,\n                });\n\n                // Provide helpful error message\n                let errorMessage = `Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`;\n                errorMessage += '\\n\\nYour key is in PKCS#1 format with unsupported encryption (DES-EDE3-CBC).';\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\n                throw new Error(errorMessage);\n            }\n        } else {\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            } 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\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","import { Agent } from 'node:https';\n\nimport type { HttpMethodsEnum } from '../../types/enums';\nimport type {\n    HttpsClientClass,\n    HttpsClientResponseClass,\n    ResponseHeaders,\n    ResponseJSONBody,\n} 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            const error = new Error(`Failed to parse response body to JSON: ${(err as Error).message}`);\n            error.cause = err;\n            throw error;\n        }\n    }\n}\n","import {\n    DEFAULT_CLOUD_API_VERSION,\n    DEFAULT_RETRY_BACKOFF,\n    DEFAULT_RETRY_INITIAL_DELAY_MS,\n    DEFAULT_RETRY_MAX_ATTEMPTS,\n    GRAPH_API_HOST,\n    GRAPH_API_PROTOCOL,\n} from '../../config/defaults';\nimport type { RetryConfig } from '../../types/config';\nimport type { HttpMethodsEnum } from '../../types/enums';\nimport type { RequesterClass, UrlEncodedFormBody } from '../../types/request';\nimport {\n    createWhatsAppApiError,\n    isMetaError,\n    normalizeMetaError,\n    WhatsAppError,\n    WhatsAppNetworkError,\n    WhatsAppThrottlingError,\n} 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\nfunction sleep(ms: number): Promise<void> {\n    return new Promise((resolve) => setTimeout(resolve, ms));\n}\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> = GRAPH_API_PROTOCOL;\n    private retryConfig: RetryConfig | undefined;\n\n    constructor(\n        apiVersion: string,\n        phoneNumberId: number,\n        accessToken: string,\n        businessAcctId: string,\n        userAgent: string,\n        retryConfig?: RetryConfig,\n    ) {\n        this.client = new HttpsClient();\n        this.host = GRAPH_API_HOST;\n        this.apiVersion = this.normalizeApiVersion(apiVersion);\n        this.phoneNumberId = phoneNumberId;\n        this.accessToken = accessToken;\n        this.businessAcctId = businessAcctId;\n        this.userAgent = userAgent;\n        this.retryConfig = retryConfig;\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 `${this.apiVersion}/${endpoint}`;\n    }\n\n    private normalizeApiVersion(apiVersion?: string): string {\n        if (!apiVersion) return DEFAULT_CLOUD_API_VERSION;\n\n        const trimmed = apiVersion.trim();\n        if (/^v\\d+\\.\\d+$/.test(trimmed)) return trimmed;\n        if (/^\\d+\\.\\d+$/.test(trimmed)) return `v${trimmed}`;\n        if (/^v\\d+$/.test(trimmed)) return `${trimmed}.0`;\n        if (/^\\d+$/.test(trimmed)) return `v${trimmed}.0`;\n\n        return trimmed;\n    }\n\n    private buildRequestTarget(endpoint: string): { host: string; path: string; displayUrl: string } {\n        if (/^https?:\\/\\//.test(endpoint)) {\n            const url = new URL(endpoint);\n            const path = `${url.pathname}${url.search}`.replace(/^\\//, '');\n            return {\n                host: url.host,\n                path,\n                displayUrl: url.toString(),\n            };\n        }\n\n        const path = this.buildCAPIPath(endpoint.replace(/^\\//, ''));\n        return {\n            host: this.host,\n            path,\n            displayUrl: `${this.protocol.toLowerCase()}//${this.host}/${path}`,\n        };\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        const maxAttempts = this.retryConfig?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;\n        const initialDelayMs = this.retryConfig?.initialDelayMs ?? DEFAULT_RETRY_INITIAL_DELAY_MS;\n        const backoff = this.retryConfig?.backoff ?? DEFAULT_RETRY_BACKOFF;\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 requestTarget = this.buildRequestTarget(endpoint);\n        LOGGER.log(`${method} : ${requestTarget.displayUrl} (${effectiveContentType})`);\n\n        for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n            try {\n                const shouldSendBody = method === 'POST' || method === 'PUT' || method === 'DELETE';\n\n                const response = await this.client.sendRequest(\n                    requestTarget.host,\n                    requestTarget.path,\n                    method,\n                    this.buildHeader(effectiveContentType, additionalHeaders),\n                    timeout,\n                    shouldSendBody ? body : undefined,\n                );\n\n                if (!response.rawResponse().ok) {\n                    let errorData: unknown = null;\n                    try {\n                        errorData = await response.json();\n                    } catch {\n                        errorData = null;\n                    }\n\n                    const metaError = normalizeMetaError(errorData, response.statusCode());\n                    throw createWhatsAppApiError(metaError.error, response.statusCode());\n                }\n\n                return response;\n            } catch (error) {\n                if (error instanceof WhatsAppThrottlingError && attempt < maxAttempts) {\n                    const delay = backoff === 'exponential' ? initialDelayMs * 2 ** (attempt - 1) : initialDelayMs;\n                    LOGGER.log(`Throttled (attempt ${attempt}/${maxAttempts}). Retrying in ${delay}ms...`);\n                    await sleep(delay);\n                    continue;\n                }\n\n                if (error instanceof WhatsAppError) {\n                    throw error;\n                }\n                if (isMetaError(error)) {\n                    throw createWhatsAppApiError(error.error);\n                }\n\n                const message = error instanceof Error ? error.message : 'Network error occurred';\n                throw new WhatsAppNetworkError(message, error);\n            }\n        }\n\n        // Unreachable in practice — loop always returns or throws.\n        // Required for TypeScript return type inference.\n        throw new WhatsAppThrottlingError(\n            'Max retry attempts exceeded',\n            { message: 'Max retry attempts exceeded', type: 'ThrottlingError', code: 130429, fbtrace_id: '' },\n            429,\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    updateTimeout(timeout: number): void {\n        LOGGER.log(`Timeout updated to ${timeout}ms`);\n    }\n\n    updateAccessToken(accessToken: string): void {\n        (this as { accessToken: string }).accessToken = accessToken;\n        LOGGER.log('Access token updated');\n    }\n\n    async sendUrlEncodedForm<T>(\n        method: HttpMethodsEnum,\n        endpoint: string,\n        timeout: number,\n        formData: UrlEncodedFormBody,\n        additionalHeaders?: Record<string, string>,\n    ): Promise<T> {\n        const urlParams = new URLSearchParams();\n        for (const [key, value] of Object.entries(formData)) {\n            if (Array.isArray(value)) {\n                for (const item of value) {\n                    urlParams.append(key, item);\n                }\n            } else {\n                urlParams.append(key, value);\n            }\n        }\n\n        const urlEncodedBody = urlParams.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","export function printLogo() {\n    // Skip logo output in test environment\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 { readFileSync } from 'node:fs';\nimport { join } from 'node: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 {\n    BlockUsersApi,\n    BusinessApi,\n    BusinessProfileApi,\n    CallingApi,\n    CommerceApi,\n    EncryptionApi,\n    FlowApi,\n    GroupsApi,\n    MarketingMessagesApi,\n    MediaApi,\n    MessageApi,\n    MessageHistoryApi,\n    PaymentsApi,\n    PhoneNumberApi,\n    QrCodeApi,\n    RegistrationApi,\n    SolutionsApi,\n    TemplateApi,\n    TwoStepVerificationApi,\n    WabaApi,\n} from '../../api';\nimport { importConfig } from '../../config/importConfig';\nimport type { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport { type EncryptionKeyPair, generateEncryption } from '../../utils/flowEncryptionUtils';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { printLogo } from '../../utils/logoConsole';\nimport { getUserAgent, getVersion } from '../../utils/version';\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    business: BusinessApi;\n    calling: CallingApi;\n    commerce: CommerceApi;\n    groups: GroupsApi;\n    marketingMessages: MarketingMessagesApi;\n    messageHistory: MessageHistoryApi;\n    messages: MessageApi;\n    media: MediaApi;\n    payments: PaymentsApi;\n    phoneNumbers: PhoneNumberApi;\n    solutions: SolutionsApi;\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            this.config.retry,\n        );\n\n        this.blockUsers = new BlockUsersApi(this.config, this.requester);\n        this.business = new BusinessApi(this.config, this.requester);\n        this.calling = new CallingApi(this.config, this.requester);\n        this.commerce = new CommerceApi(this.config, this.requester);\n        this.groups = new GroupsApi(this.config, this.requester);\n        this.marketingMessages = new MarketingMessagesApi(this.config, this.requester);\n        this.messageHistory = new MessageHistoryApi(this.config, this.requester);\n        this.messages = new MessageApi(this.config, this.requester);\n        this.media = new MediaApi(this.config, this.requester);\n        this.payments = new PaymentsApi(this.config, this.requester);\n        this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n        this.solutions = new SolutionsApi(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        this.requester.updateTimeout(timeout);\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        this.requester.updateAccessToken(accessToken);\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    type FlowDataExchangeRequest,\n    type FlowEndpointRequest,\n    type FlowErrorNotificationRequest,\n    type 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 'node:crypto';\n\nimport type { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport type { 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 type WhatsApp from '../../whatsapp/WhatsApp';\nimport type {\n    AccountAlertsWebhookValue,\n    AccountReviewUpdateWebhookValue,\n    AccountSettingsUpdateWebhookValue,\n    AccountUpdateWebhookValue,\n    AutomaticEventsWebhookValue,\n    BusinessCapabilityUpdateWebhookValue,\n    BusinessStatusUpdateWebhookValue,\n    CallsWebhookValue,\n    FlowsWebhookValue,\n    GroupLifecycleUpdateWebhookValue,\n    GroupParticipantsUpdateWebhookValue,\n    GroupSettingsUpdateWebhookValue,\n    GroupStatusUpdateWebhookValue,\n    HistoryWebhookValue,\n    MessageEchoesWebhookValue,\n    MessageTemplateComponentsUpdateWebhookValue,\n    MessageTemplateQualityUpdateWebhookValue,\n    MessageTemplateStatusUpdateWebhookValue,\n    MessageWebhookValue,\n    MessagingHandoversWebhookValue,\n    PartnerSolutionsWebhookValue,\n    PaymentConfigurationUpdateWebhookValue,\n    PhoneNumberNameUpdateWebhookValue,\n    PhoneNumberQualityUpdateWebhookValue,\n    SecurityWebhookValue,\n    SmbAppStateSyncWebhookValue,\n    SmbMessageEchoesWebhookValue,\n    StandbyWebhookValue,\n    StatusWebhook,\n    StatusWebhookValue,\n    TemplateCategoryUpdateWebhookValue,\n    TemplateCorrectCategoryDetectionWebhookValue,\n    TrackingEventsWebhookValue,\n    UserPreferencesWebhookValue,\n    WebhookFieldType,\n    WebhookPayload,\n    WebhookValue,\n    WhatsAppMessage,\n} 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/**\n * Processed webhook field types for specialized handlers\n */\nexport type ProcessedAccountUpdate = {\n    wabaId: string;\n    value: AccountUpdateWebhookValue['value'];\n};\n\nexport type ProcessedAccountReviewUpdate = {\n    wabaId: string;\n    value: AccountReviewUpdateWebhookValue['value'];\n};\n\nexport type ProcessedAccountAlerts = {\n    wabaId: string;\n    value: AccountAlertsWebhookValue['value'];\n};\n\nexport type ProcessedBusinessCapabilityUpdate = {\n    wabaId: string;\n    value: BusinessCapabilityUpdateWebhookValue['value'];\n};\n\nexport type ProcessedPhoneNumberNameUpdate = {\n    wabaId: string;\n    value: PhoneNumberNameUpdateWebhookValue['value'];\n};\n\nexport type ProcessedPhoneNumberQualityUpdate = {\n    wabaId: string;\n    value: PhoneNumberQualityUpdateWebhookValue['value'];\n};\n\nexport type ProcessedMessageTemplateStatusUpdate = {\n    wabaId: string;\n    value: MessageTemplateStatusUpdateWebhookValue['value'];\n};\n\nexport type ProcessedTemplateCategoryUpdate = {\n    wabaId: string;\n    value: TemplateCategoryUpdateWebhookValue['value'];\n};\n\nexport type ProcessedMessageTemplateQualityUpdate = {\n    wabaId: string;\n    value: MessageTemplateQualityUpdateWebhookValue['value'];\n};\n\nexport type ProcessedFlows = {\n    wabaId: string;\n    value: FlowsWebhookValue['value'];\n};\n\nexport type ProcessedSecurity = {\n    wabaId: string;\n    value: SecurityWebhookValue['value'];\n};\n\nexport type ProcessedHistory = {\n    wabaId: string;\n    value: HistoryWebhookValue['value'];\n};\n\nexport type ProcessedSmbMessageEchoes = {\n    wabaId: string;\n    value: SmbMessageEchoesWebhookValue['value'];\n};\n\nexport type ProcessedSmbAppStateSync = {\n    wabaId: string;\n    value: SmbAppStateSyncWebhookValue['value'];\n};\n\nexport type ProcessedAccountSettingsUpdate = {\n    wabaId: string;\n    value: AccountSettingsUpdateWebhookValue['value'];\n};\n\nexport type ProcessedAutomaticEvents = {\n    wabaId: string;\n    value: AutomaticEventsWebhookValue['value'];\n};\n\nexport type ProcessedBusinessStatusUpdate = {\n    wabaId: string;\n    value: BusinessStatusUpdateWebhookValue['value'];\n};\n\nexport type ProcessedCalls = {\n    wabaId: string;\n    value: CallsWebhookValue['value'];\n};\n\nexport type ProcessedGroupLifecycleUpdate = {\n    wabaId: string;\n    value: GroupLifecycleUpdateWebhookValue['value'];\n};\n\nexport type ProcessedGroupParticipantsUpdate = {\n    wabaId: string;\n    value: GroupParticipantsUpdateWebhookValue['value'];\n};\n\nexport type ProcessedGroupSettingsUpdate = {\n    wabaId: string;\n    value: GroupSettingsUpdateWebhookValue['value'];\n};\n\nexport type ProcessedGroupStatusUpdate = {\n    wabaId: string;\n    value: GroupStatusUpdateWebhookValue['value'];\n};\n\nexport type ProcessedMessageEchoes = {\n    wabaId: string;\n    value: MessageEchoesWebhookValue['value'];\n};\n\nexport type ProcessedMessageTemplateComponentsUpdate = {\n    wabaId: string;\n    value: MessageTemplateComponentsUpdateWebhookValue['value'];\n};\n\nexport type ProcessedMessagingHandovers = {\n    wabaId: string;\n    value: MessagingHandoversWebhookValue['value'];\n};\n\nexport type ProcessedPartnerSolutions = {\n    wabaId: string;\n    value: PartnerSolutionsWebhookValue['value'];\n};\n\nexport type ProcessedPaymentConfigurationUpdate = {\n    wabaId: string;\n    value: PaymentConfigurationUpdateWebhookValue['value'];\n};\n\nexport type ProcessedStandby = {\n    wabaId: string;\n    value: StandbyWebhookValue['value'];\n};\n\nexport type ProcessedTemplateCorrectCategoryDetection = {\n    wabaId: string;\n    value: TemplateCorrectCategoryDetectionWebhookValue['value'];\n};\n\nexport type ProcessedTrackingEvents = {\n    wabaId: string;\n    value: TrackingEventsWebhookValue['value'];\n};\n\nexport type ProcessedUserPreferences = {\n    wabaId: string;\n    value: UserPreferencesWebhookValue['value'];\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\n/**\n * Original HTTP request context for WhatsApp webhook handlers.\n *\n * The `rawBody` and `headers` values preserve the incoming webhook request so\n * callers can forward or verify the request according to Meta's request syntax.\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint/#request-syntax-1\n */\nexport type WebhookHandlerContext = {\n    /** Original request headers from the incoming webhook request. */\n    headers: Headers;\n    /** Original request body string before JSON parsing or field filtering. */\n    rawBody: string;\n    /** Original request method. */\n    method: string;\n    /** Original request URL. */\n    url: string;\n};\n\ntype WebhookHandler<TProcessed, TReturn = void> = (\n    whatsapp: WhatsApp,\n    processed: TProcessed,\n    context: WebhookHandlerContext,\n) => TReturn | Promise<TReturn>;\n\nexport type MessageHandler = WebhookHandler<ProcessedMessage>;\nexport type StatusHandler = WebhookHandler<ProcessedStatus>;\nexport type FlowHandler = WebhookHandler<FlowEndpointRequest, any>;\nexport type RawWebhookHandler = WebhookHandler<WebhookPayload>;\n\n// Webhook field handlers\nexport type AccountUpdateHandler = WebhookHandler<ProcessedAccountUpdate>;\nexport type AccountReviewUpdateHandler = WebhookHandler<ProcessedAccountReviewUpdate>;\nexport type AccountAlertsHandler = WebhookHandler<ProcessedAccountAlerts>;\nexport type BusinessCapabilityUpdateHandler = WebhookHandler<ProcessedBusinessCapabilityUpdate>;\nexport type PhoneNumberNameUpdateHandler = WebhookHandler<ProcessedPhoneNumberNameUpdate>;\nexport type PhoneNumberQualityUpdateHandler = WebhookHandler<ProcessedPhoneNumberQualityUpdate>;\nexport type MessageTemplateStatusUpdateHandler = WebhookHandler<ProcessedMessageTemplateStatusUpdate>;\nexport type TemplateCategoryUpdateHandler = WebhookHandler<ProcessedTemplateCategoryUpdate>;\nexport type MessageTemplateQualityUpdateHandler = WebhookHandler<ProcessedMessageTemplateQualityUpdate>;\nexport type FlowsHandler = WebhookHandler<ProcessedFlows>;\nexport type SecurityHandler = WebhookHandler<ProcessedSecurity>;\nexport type HistoryHandler = WebhookHandler<ProcessedHistory>;\nexport type SmbMessageEchoesHandler = WebhookHandler<ProcessedSmbMessageEchoes>;\nexport type SmbAppStateSyncHandler = WebhookHandler<ProcessedSmbAppStateSync>;\nexport type AccountSettingsUpdateHandler = WebhookHandler<ProcessedAccountSettingsUpdate>;\nexport type AutomaticEventsHandler = WebhookHandler<ProcessedAutomaticEvents>;\nexport type BusinessStatusUpdateHandler = WebhookHandler<ProcessedBusinessStatusUpdate>;\nexport type CallsHandler = WebhookHandler<ProcessedCalls>;\nexport type GroupLifecycleUpdateHandler = WebhookHandler<ProcessedGroupLifecycleUpdate>;\nexport type GroupParticipantsUpdateHandler = WebhookHandler<ProcessedGroupParticipantsUpdate>;\nexport type GroupSettingsUpdateHandler = WebhookHandler<ProcessedGroupSettingsUpdate>;\nexport type GroupStatusUpdateHandler = WebhookHandler<ProcessedGroupStatusUpdate>;\nexport type MessageEchoesHandler = WebhookHandler<ProcessedMessageEchoes>;\nexport type MessageTemplateComponentsUpdateHandler = WebhookHandler<ProcessedMessageTemplateComponentsUpdate>;\nexport type MessagingHandoversHandler = WebhookHandler<ProcessedMessagingHandovers>;\nexport type PartnerSolutionsHandler = WebhookHandler<ProcessedPartnerSolutions>;\nexport type PaymentConfigurationUpdateHandler = WebhookHandler<ProcessedPaymentConfigurationUpdate>;\nexport type StandbyHandler = WebhookHandler<ProcessedStandby>;\nexport type TemplateCorrectCategoryDetectionHandler = WebhookHandler<ProcessedTemplateCorrectCategoryDetection>;\nexport type TrackingEventsHandler = WebhookHandler<ProcessedTrackingEvents>;\nexport type UserPreferencesHandler = WebhookHandler<ProcessedUserPreferences>;\n\n// Type-specific handlers for specialized methods\nexport type TextMessageHandler = WebhookHandler<TextProcessedMessage>;\nexport type ImageMessageHandler = WebhookHandler<ImageProcessedMessage>;\nexport type VideoMessageHandler = WebhookHandler<VideoProcessedMessage>;\nexport type AudioMessageHandler = WebhookHandler<AudioProcessedMessage>;\nexport type DocumentMessageHandler = WebhookHandler<DocumentProcessedMessage>;\nexport type StickerMessageHandler = WebhookHandler<StickerProcessedMessage>;\nexport type InteractiveMessageHandler = WebhookHandler<InteractiveProcessedMessage>;\nexport type ButtonMessageHandler = WebhookHandler<ButtonProcessedMessage>;\nexport type LocationMessageHandler = WebhookHandler<LocationProcessedMessage>;\nexport type ContactsMessageHandler = WebhookHandler<ContactsProcessedMessage>;\nexport type ReactionMessageHandler = WebhookHandler<ReactionProcessedMessage>;\nexport type OrderMessageHandler = WebhookHandler<OrderProcessedMessage>;\nexport type SystemMessageHandler = WebhookHandler<SystemProcessedMessage>;\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        rawHandler?: RawWebhookHandler;\n        rawHandlerFields?: WebhookFieldType[];\n        // Webhook field handlers\n        accountUpdateHandler?: AccountUpdateHandler;\n        accountReviewUpdateHandler?: AccountReviewUpdateHandler;\n        accountAlertsHandler?: AccountAlertsHandler;\n        businessCapabilityUpdateHandler?: BusinessCapabilityUpdateHandler;\n        phoneNumberNameUpdateHandler?: PhoneNumberNameUpdateHandler;\n        phoneNumberQualityUpdateHandler?: PhoneNumberQualityUpdateHandler;\n        messageTemplateStatusUpdateHandler?: MessageTemplateStatusUpdateHandler;\n        templateCategoryUpdateHandler?: TemplateCategoryUpdateHandler;\n        messageTemplateQualityUpdateHandler?: MessageTemplateQualityUpdateHandler;\n        flowsHandler?: FlowsHandler;\n        securityHandler?: SecurityHandler;\n        historyHandler?: HistoryHandler;\n        smbMessageEchoesHandler?: SmbMessageEchoesHandler;\n        smbAppStateSyncHandler?: SmbAppStateSyncHandler;\n        accountSettingsUpdateHandler?: AccountSettingsUpdateHandler;\n        automaticEventsHandler?: AutomaticEventsHandler;\n        businessStatusUpdateHandler?: BusinessStatusUpdateHandler;\n        callsHandler?: CallsHandler;\n        groupLifecycleUpdateHandler?: GroupLifecycleUpdateHandler;\n        groupParticipantsUpdateHandler?: GroupParticipantsUpdateHandler;\n        groupSettingsUpdateHandler?: GroupSettingsUpdateHandler;\n        groupStatusUpdateHandler?: GroupStatusUpdateHandler;\n        messageEchoesHandler?: MessageEchoesHandler;\n        messageTemplateComponentsUpdateHandler?: MessageTemplateComponentsUpdateHandler;\n        messagingHandoversHandler?: MessagingHandoversHandler;\n        partnerSolutionsHandler?: PartnerSolutionsHandler;\n        paymentConfigurationUpdateHandler?: PaymentConfigurationUpdateHandler;\n        standbyHandler?: StandbyHandler;\n        templateCorrectCategoryDetectionHandler?: TemplateCorrectCategoryDetectionHandler;\n        trackingEventsHandler?: TrackingEventsHandler;\n        userPreferencesHandler?: UserPreferencesHandler;\n    },\n): Promise<Response> {\n    try {\n        const rawBody = await request.text();\n        const body = JSON.parse(rawBody);\n        const context: WebhookHandlerContext = {\n            headers: request.headers,\n            rawBody,\n            method: request.method,\n            url: request.url,\n        };\n\n        if (handlers.rawHandler) {\n            const { rawHandler, rawHandlerFields } = handlers;\n            let payload = body as WebhookPayload;\n            if (rawHandlerFields && rawHandlerFields.length > 0) {\n                const filtered: WebhookPayload = {\n                    ...payload,\n                    entry: payload.entry\n                        .map((entry) => ({\n                            ...entry,\n                            changes: entry.changes.filter((change) =>\n                                rawHandlerFields.includes(change.field as WebhookFieldType),\n                            ),\n                        }))\n                        .filter((entry) => entry.changes.length > 0),\n                };\n                if (filtered.entry.length === 0) {\n                    payload = null as any;\n                } else {\n                    payload = filtered;\n                }\n            }\n            if (payload) {\n                await rawHandler(whatsapp, payload, context);\n            }\n        }\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, context);\n                    } else if (change.field === 'account_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as AccountUpdateWebhookValue,\n                            handlers.accountUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'account_review_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as AccountReviewUpdateWebhookValue,\n                            handlers.accountReviewUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'account_alerts') {\n                        await processWebhookField(\n                            entry.id,\n                            change as AccountAlertsWebhookValue,\n                            handlers.accountAlertsHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'business_capability_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as BusinessCapabilityUpdateWebhookValue,\n                            handlers.businessCapabilityUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'phone_number_name_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as PhoneNumberNameUpdateWebhookValue,\n                            handlers.phoneNumberNameUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'phone_number_quality_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as PhoneNumberQualityUpdateWebhookValue,\n                            handlers.phoneNumberQualityUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'message_template_status_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as MessageTemplateStatusUpdateWebhookValue,\n                            handlers.messageTemplateStatusUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'template_category_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as TemplateCategoryUpdateWebhookValue,\n                            handlers.templateCategoryUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'message_template_quality_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as MessageTemplateQualityUpdateWebhookValue,\n                            handlers.messageTemplateQualityUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'flows') {\n                        await processWebhookField(\n                            entry.id,\n                            change as FlowsWebhookValue,\n                            handlers.flowsHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'security') {\n                        await processWebhookField(\n                            entry.id,\n                            change as SecurityWebhookValue,\n                            handlers.securityHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'history') {\n                        await processWebhookField(\n                            entry.id,\n                            change as HistoryWebhookValue,\n                            handlers.historyHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'smb_message_echoes') {\n                        await processWebhookField(\n                            entry.id,\n                            change as SmbMessageEchoesWebhookValue,\n                            handlers.smbMessageEchoesHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'smb_app_state_sync') {\n                        await processWebhookField(\n                            entry.id,\n                            change as SmbAppStateSyncWebhookValue,\n                            handlers.smbAppStateSyncHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'account_settings_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as AccountSettingsUpdateWebhookValue,\n                            handlers.accountSettingsUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'automatic_events') {\n                        await processWebhookField(\n                            entry.id,\n                            change as AutomaticEventsWebhookValue,\n                            handlers.automaticEventsHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'business_status_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as BusinessStatusUpdateWebhookValue,\n                            handlers.businessStatusUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'calls') {\n                        await processWebhookField(\n                            entry.id,\n                            change as CallsWebhookValue,\n                            handlers.callsHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'group_lifecycle_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as GroupLifecycleUpdateWebhookValue,\n                            handlers.groupLifecycleUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'group_participants_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as GroupParticipantsUpdateWebhookValue,\n                            handlers.groupParticipantsUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'group_settings_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as GroupSettingsUpdateWebhookValue,\n                            handlers.groupSettingsUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'group_status_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as GroupStatusUpdateWebhookValue,\n                            handlers.groupStatusUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'message_echoes') {\n                        await processWebhookField(\n                            entry.id,\n                            change as MessageEchoesWebhookValue,\n                            handlers.messageEchoesHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'message_template_components_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as MessageTemplateComponentsUpdateWebhookValue,\n                            handlers.messageTemplateComponentsUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'messaging_handovers') {\n                        await processWebhookField(\n                            entry.id,\n                            change as MessagingHandoversWebhookValue,\n                            handlers.messagingHandoversHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'partner_solutions') {\n                        await processWebhookField(\n                            entry.id,\n                            change as PartnerSolutionsWebhookValue,\n                            handlers.partnerSolutionsHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'payment_configuration_update') {\n                        await processWebhookField(\n                            entry.id,\n                            change as PaymentConfigurationUpdateWebhookValue,\n                            handlers.paymentConfigurationUpdateHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'standby') {\n                        await processWebhookField(\n                            entry.id,\n                            change as StandbyWebhookValue,\n                            handlers.standbyHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'template_correct_category_detection') {\n                        await processWebhookField(\n                            entry.id,\n                            change as TemplateCorrectCategoryDetectionWebhookValue,\n                            handlers.templateCorrectCategoryDetectionHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'tracking_events') {\n                        await processWebhookField(\n                            entry.id,\n                            change as TrackingEventsWebhookValue,\n                            handlers.trackingEventsHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else if (change.field === 'user_preferences') {\n                        await processWebhookField(\n                            entry.id,\n                            change as UserPreferencesWebhookValue,\n                            handlers.userPreferencesHandler,\n                            whatsapp,\n                            context,\n                        );\n                    } else {\n                        LOGGER.warn(`Unhandled webhook field: ${change.field}`);\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 context: WebhookHandlerContext = {\n            headers: request.headers,\n            rawBody: body,\n            method: request.method,\n            url: request.url,\n        };\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, context);\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        if ('context' in message && message.context?.id) {\n            return message.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    context: WebhookHandlerContext,\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, context);\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, context, 'pre-process');\n            await executeMessageHandler(\n                handlers.messageHandlers.get(messageType),\n                whatsapp,\n                processed,\n                context,\n                messageType,\n            );\n            await executeMessageHandler(handlers.postProcessHandler, whatsapp, processed, context, 'post-process');\n        }\n    }\n}\n\nasync function executeMessageHandler(\n    handler: MessageHandler | undefined,\n    whatsapp: WhatsApp,\n    processed: ProcessedMessage,\n    context: WebhookHandlerContext,\n    handlerType: string,\n): Promise<void> {\n    if (handler) {\n        try {\n            await handler(whatsapp, processed, context);\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    context: WebhookHandlerContext,\n): Promise<void> {\n    if (handler) {\n        try {\n            await handler(whatsapp, processed, context);\n        } catch (error) {\n            LOGGER.error('Error in status handler:', { error, statusId: processed.status.id });\n        }\n    }\n}\n\n/**\n * Generic webhook field processor\n * Processes webhook fields other than 'messages'\n */\nasync function processWebhookField<T extends { field: string; value: any }>(\n    wabaId: string,\n    webhookValue: T,\n    handler:\n        | ((\n              whatsapp: WhatsApp,\n              processed: { wabaId: string; value: T['value'] },\n              context: WebhookHandlerContext,\n          ) => void | Promise<void>)\n        | undefined,\n    whatsapp: WhatsApp,\n    context: WebhookHandlerContext,\n): Promise<void> {\n    if (handler) {\n        try {\n            await handler(\n                whatsapp,\n                {\n                    wabaId,\n                    value: webhookValue.value,\n                },\n                context,\n            );\n        } catch (error) {\n            LOGGER.error(`Error in ${webhookValue.field} handler:`, { error, wabaId });\n        }\n    }\n}\n","import type { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport type { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport type { WebhookFieldType } from './types';\nimport {\n    type AccountAlertsHandler,\n    type AccountReviewUpdateHandler,\n    type AccountSettingsUpdateHandler,\n    type AccountUpdateHandler,\n    type AudioMessageHandler,\n    type AutomaticEventsHandler,\n    type BusinessCapabilityUpdateHandler,\n    type BusinessStatusUpdateHandler,\n    type ButtonMessageHandler,\n    type CallsHandler,\n    type ContactsMessageHandler,\n    type DocumentMessageHandler,\n    type FlowHandler,\n    type FlowsHandler,\n    type GroupLifecycleUpdateHandler,\n    type GroupParticipantsUpdateHandler,\n    type GroupSettingsUpdateHandler,\n    type GroupStatusUpdateHandler,\n    type HistoryHandler,\n    type ImageMessageHandler,\n    type InteractiveMessageHandler,\n    type LocationMessageHandler,\n    type MessageEchoesHandler,\n    type MessageHandler,\n    type MessageTemplateComponentsUpdateHandler,\n    type MessageTemplateQualityUpdateHandler,\n    type MessageTemplateStatusUpdateHandler,\n    type MessagingHandoversHandler,\n    type OrderMessageHandler,\n    type PartnerSolutionsHandler,\n    type PaymentConfigurationUpdateHandler,\n    type PhoneNumberNameUpdateHandler,\n    type PhoneNumberQualityUpdateHandler,\n    processFlowRequest,\n    processWebhookMessages,\n    type RawWebhookHandler,\n    type ReactionMessageHandler,\n    type SecurityHandler,\n    type SmbAppStateSyncHandler,\n    type SmbMessageEchoesHandler,\n    type StandbyHandler,\n    type StatusHandler,\n    type StickerMessageHandler,\n    type SystemMessageHandler,\n    type TemplateCategoryUpdateHandler,\n    type TemplateCorrectCategoryDetectionHandler,\n    type TextMessageHandler,\n    type TrackingEventsHandler,\n    type UserPreferencesHandler,\n    type VideoMessageHandler,\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 rawHandler: { handler: RawWebhookHandler; fields?: WebhookFieldType[] } | undefined = undefined;\n    private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n    // Webhook field handlers\n    private accountUpdateHandler: AccountUpdateHandler | undefined = undefined;\n    private accountReviewUpdateHandler: AccountReviewUpdateHandler | undefined = undefined;\n    private accountAlertsHandler: AccountAlertsHandler | undefined = undefined;\n    private businessCapabilityUpdateHandler: BusinessCapabilityUpdateHandler | undefined = undefined;\n    private phoneNumberNameUpdateHandler: PhoneNumberNameUpdateHandler | undefined = undefined;\n    private phoneNumberQualityUpdateHandler: PhoneNumberQualityUpdateHandler | undefined = undefined;\n    private messageTemplateStatusUpdateHandler: MessageTemplateStatusUpdateHandler | undefined = undefined;\n    private templateCategoryUpdateHandler: TemplateCategoryUpdateHandler | undefined = undefined;\n    private messageTemplateQualityUpdateHandler: MessageTemplateQualityUpdateHandler | undefined = undefined;\n    private flowsHandler: FlowsHandler | undefined = undefined;\n    private securityHandler: SecurityHandler | undefined = undefined;\n    private historyHandler: HistoryHandler | undefined = undefined;\n    private smbMessageEchoesHandler: SmbMessageEchoesHandler | undefined = undefined;\n    private smbAppStateSyncHandler: SmbAppStateSyncHandler | undefined = undefined;\n    private accountSettingsUpdateHandler: AccountSettingsUpdateHandler | undefined = undefined;\n    private automaticEventsHandler: AutomaticEventsHandler | undefined = undefined;\n    private businessStatusUpdateHandler: BusinessStatusUpdateHandler | undefined = undefined;\n    private callsHandler: CallsHandler | undefined = undefined;\n    private groupLifecycleUpdateHandler: GroupLifecycleUpdateHandler | undefined = undefined;\n    private groupParticipantsUpdateHandler: GroupParticipantsUpdateHandler | undefined = undefined;\n    private groupSettingsUpdateHandler: GroupSettingsUpdateHandler | undefined = undefined;\n    private groupStatusUpdateHandler: GroupStatusUpdateHandler | undefined = undefined;\n    private messageEchoesHandler: MessageEchoesHandler | undefined = undefined;\n    private messageTemplateComponentsUpdateHandler: MessageTemplateComponentsUpdateHandler | undefined = undefined;\n    private messagingHandoversHandler: MessagingHandoversHandler | undefined = undefined;\n    private partnerSolutionsHandler: PartnerSolutionsHandler | undefined = undefined;\n    private paymentConfigurationUpdateHandler: PaymentConfigurationUpdateHandler | undefined = undefined;\n    private standbyHandler: StandbyHandler | undefined = undefined;\n    private templateCorrectCategoryDetectionHandler: TemplateCorrectCategoryDetectionHandler | undefined = undefined;\n    private trackingEventsHandler: TrackingEventsHandler | undefined = undefined;\n    private userPreferencesHandler: UserPreferencesHandler | undefined = undefined;\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                rawHandler: this.rawHandler?.handler,\n                rawHandlerFields: this.rawHandler?.fields,\n                // Webhook field handlers\n                accountUpdateHandler: this.accountUpdateHandler,\n                accountReviewUpdateHandler: this.accountReviewUpdateHandler,\n                accountAlertsHandler: this.accountAlertsHandler,\n                businessCapabilityUpdateHandler: this.businessCapabilityUpdateHandler,\n                phoneNumberNameUpdateHandler: this.phoneNumberNameUpdateHandler,\n                phoneNumberQualityUpdateHandler: this.phoneNumberQualityUpdateHandler,\n                messageTemplateStatusUpdateHandler: this.messageTemplateStatusUpdateHandler,\n                templateCategoryUpdateHandler: this.templateCategoryUpdateHandler,\n                messageTemplateQualityUpdateHandler: this.messageTemplateQualityUpdateHandler,\n                flowsHandler: this.flowsHandler,\n                securityHandler: this.securityHandler,\n                historyHandler: this.historyHandler,\n                smbMessageEchoesHandler: this.smbMessageEchoesHandler,\n                smbAppStateSyncHandler: this.smbAppStateSyncHandler,\n                accountSettingsUpdateHandler: this.accountSettingsUpdateHandler,\n                automaticEventsHandler: this.automaticEventsHandler,\n                businessStatusUpdateHandler: this.businessStatusUpdateHandler,\n                callsHandler: this.callsHandler,\n                groupLifecycleUpdateHandler: this.groupLifecycleUpdateHandler,\n                groupParticipantsUpdateHandler: this.groupParticipantsUpdateHandler,\n                groupSettingsUpdateHandler: this.groupSettingsUpdateHandler,\n                groupStatusUpdateHandler: this.groupStatusUpdateHandler,\n                messageEchoesHandler: this.messageEchoesHandler,\n                messageTemplateComponentsUpdateHandler: this.messageTemplateComponentsUpdateHandler,\n                messagingHandoversHandler: this.messagingHandoversHandler,\n                partnerSolutionsHandler: this.partnerSolutionsHandler,\n                paymentConfigurationUpdateHandler: this.paymentConfigurationUpdateHandler,\n                standbyHandler: this.standbyHandler,\n                templateCorrectCategoryDetectionHandler: this.templateCorrectCategoryDetectionHandler,\n                trackingEventsHandler: this.trackingEventsHandler,\n                userPreferencesHandler: this.userPreferencesHandler,\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 | string, 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 as MessageTypesEnum, 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    onRaw(handler: RawWebhookHandler, fields?: WebhookFieldType[]): void {\n        this.rawHandler = { handler, fields };\n        LOGGER.log(`Registered raw webhook handler${fields ? ` for fields: ${fields.join(', ')}` : ''}`);\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    // ============================================================================\n    // Webhook field handlers\n    // @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account\n    // ============================================================================\n\n    /**\n     * Register a handler for account_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_update\n     */\n    onAccountUpdate(handler: AccountUpdateHandler): void {\n        this.accountUpdateHandler = handler;\n        LOGGER.log('Registered account_update handler');\n    }\n\n    /**\n     * Register a handler for account_review_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_review_update\n     */\n    onAccountReviewUpdate(handler: AccountReviewUpdateHandler): void {\n        this.accountReviewUpdateHandler = handler;\n        LOGGER.log('Registered account_review_update handler');\n    }\n\n    /**\n     * Register a handler for account_alerts webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_alerts\n     */\n    onAccountAlerts(handler: AccountAlertsHandler): void {\n        this.accountAlertsHandler = handler;\n        LOGGER.log('Registered account_alerts handler');\n    }\n\n    /**\n     * Register a handler for business_capability_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#business_capability_update\n     */\n    onBusinessCapabilityUpdate(handler: BusinessCapabilityUpdateHandler): void {\n        this.businessCapabilityUpdateHandler = handler;\n        LOGGER.log('Registered business_capability_update handler');\n    }\n\n    /**\n     * Register a handler for phone_number_name_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#phone_number_name_update\n     */\n    onPhoneNumberNameUpdate(handler: PhoneNumberNameUpdateHandler): void {\n        this.phoneNumberNameUpdateHandler = handler;\n        LOGGER.log('Registered phone_number_name_update handler');\n    }\n\n    /**\n     * Register a handler for phone_number_quality_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#phone_number_quality_update\n     */\n    onPhoneNumberQualityUpdate(handler: PhoneNumberQualityUpdateHandler): void {\n        this.phoneNumberQualityUpdateHandler = handler;\n        LOGGER.log('Registered phone_number_quality_update handler');\n    }\n\n    /**\n     * Register a handler for message_template_status_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#message_template_status_update\n     */\n    onMessageTemplateStatusUpdate(handler: MessageTemplateStatusUpdateHandler): void {\n        this.messageTemplateStatusUpdateHandler = handler;\n        LOGGER.log('Registered message_template_status_update handler');\n    }\n\n    /**\n     * Register a handler for template_category_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#template_category_update\n     */\n    onTemplateCategoryUpdate(handler: TemplateCategoryUpdateHandler): void {\n        this.templateCategoryUpdateHandler = handler;\n        LOGGER.log('Registered template_category_update handler');\n    }\n\n    /**\n     * Register a handler for message_template_quality_update webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#message_template_quality_update\n     */\n    onMessageTemplateQualityUpdate(handler: MessageTemplateQualityUpdateHandler): void {\n        this.messageTemplateQualityUpdateHandler = handler;\n        LOGGER.log('Registered message_template_quality_update handler');\n    }\n\n    /**\n     * Register a handler for flows webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/flows/guides/implementingyourflowendpoint#webhooks\n     */\n    onFlows(handler: FlowsHandler): void {\n        this.flowsHandler = handler;\n        LOGGER.log('Registered flows handler');\n    }\n\n    /**\n     * Register a handler for security webhook field\n     * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#security\n     */\n    onSecurity(handler: SecurityHandler): void {\n        this.securityHandler = handler;\n        LOGGER.log('Registered security handler');\n    }\n\n    /**\n     * Register a handler for history webhook field\n     * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#history\n     */\n    onHistory(handler: HistoryHandler): void {\n        this.historyHandler = handler;\n        LOGGER.log('Registered history handler');\n    }\n\n    /**\n     * Register a handler for smb_message_echoes webhook field\n     * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#smb_message_echoes\n     */\n    onSmbMessageEchoes(handler: SmbMessageEchoesHandler): void {\n        this.smbMessageEchoesHandler = handler;\n        LOGGER.log('Registered smb_message_echoes handler');\n    }\n\n    /**\n     * Register a handler for smb_app_state_sync webhook field\n     * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#smb_app_state_sync\n     */\n    onSmbAppStateSync(handler: SmbAppStateSyncHandler): void {\n        this.smbAppStateSyncHandler = handler;\n        LOGGER.log('Registered smb_app_state_sync handler');\n    }\n\n    /**\n     * Register a handler for account_settings_update webhook field\n     */\n    onAccountSettingsUpdate(handler: AccountSettingsUpdateHandler): void {\n        this.accountSettingsUpdateHandler = handler;\n        LOGGER.log('Registered account_settings_update handler');\n    }\n\n    /**\n     * Register a handler for automatic_events webhook field\n     */\n    onAutomaticEvents(handler: AutomaticEventsHandler): void {\n        this.automaticEventsHandler = handler;\n        LOGGER.log('Registered automatic_events handler');\n    }\n\n    /**\n     * Register a handler for business_status_update webhook field\n     */\n    onBusinessStatusUpdate(handler: BusinessStatusUpdateHandler): void {\n        this.businessStatusUpdateHandler = handler;\n        LOGGER.log('Registered business_status_update handler');\n    }\n\n    /**\n     * Register a handler for calls webhook field\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n     */\n    onCalls(handler: CallsHandler): void {\n        this.callsHandler = handler;\n        LOGGER.log('Registered calls handler');\n    }\n\n    /**\n     * Register a handler for group_lifecycle_update webhook field\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    onGroupLifecycleUpdate(handler: GroupLifecycleUpdateHandler): void {\n        this.groupLifecycleUpdateHandler = handler;\n        LOGGER.log('Registered group_lifecycle_update handler');\n    }\n\n    /**\n     * Register a handler for group_participants_update webhook field\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    onGroupParticipantsUpdate(handler: GroupParticipantsUpdateHandler): void {\n        this.groupParticipantsUpdateHandler = handler;\n        LOGGER.log('Registered group_participants_update handler');\n    }\n\n    /**\n     * Register a handler for group_settings_update webhook field\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    onGroupSettingsUpdate(handler: GroupSettingsUpdateHandler): void {\n        this.groupSettingsUpdateHandler = handler;\n        LOGGER.log('Registered group_settings_update handler');\n    }\n\n    /**\n     * Register a handler for group_status_update webhook field\n     * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n     */\n    onGroupStatusUpdate(handler: GroupStatusUpdateHandler): void {\n        this.groupStatusUpdateHandler = handler;\n        LOGGER.log('Registered group_status_update handler');\n    }\n\n    /**\n     * Register a handler for message_echoes webhook field\n     * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#message_echoes\n     */\n    onMessageEchoes(handler: MessageEchoesHandler): void {\n        this.messageEchoesHandler = handler;\n        LOGGER.log('Registered message_echoes handler');\n    }\n\n    /**\n     * Register a handler for message_template_components_update webhook field\n     */\n    onMessageTemplateComponentsUpdate(handler: MessageTemplateComponentsUpdateHandler): void {\n        this.messageTemplateComponentsUpdateHandler = handler;\n        LOGGER.log('Registered message_template_components_update handler');\n    }\n\n    /**\n     * Register a handler for messaging_handovers webhook field\n     */\n    onMessagingHandovers(handler: MessagingHandoversHandler): void {\n        this.messagingHandoversHandler = handler;\n        LOGGER.log('Registered messaging_handovers handler');\n    }\n\n    /**\n     * Register a handler for partner_solutions webhook field\n     */\n    onPartnerSolutions(handler: PartnerSolutionsHandler): void {\n        this.partnerSolutionsHandler = handler;\n        LOGGER.log('Registered partner_solutions handler');\n    }\n\n    /**\n     * Register a handler for payment_configuration_update webhook field\n     */\n    onPaymentConfigurationUpdate(handler: PaymentConfigurationUpdateHandler): void {\n        this.paymentConfigurationUpdateHandler = handler;\n        LOGGER.log('Registered payment_configuration_update handler');\n    }\n\n    /**\n     * Register a handler for standby webhook field\n     */\n    onStandby(handler: StandbyHandler): void {\n        this.standbyHandler = handler;\n        LOGGER.log('Registered standby handler');\n    }\n\n    /**\n     * Register a handler for template_correct_category_detection webhook field\n     */\n    onTemplateCorrectCategoryDetection(handler: TemplateCorrectCategoryDetectionHandler): void {\n        this.templateCorrectCategoryDetectionHandler = handler;\n        LOGGER.log('Registered template_correct_category_detection handler');\n    }\n\n    /**\n     * Register a handler for tracking_events webhook field\n     */\n    onTrackingEvents(handler: TrackingEventsHandler): void {\n        this.trackingEventsHandler = handler;\n        LOGGER.log('Registered tracking_events handler');\n    }\n\n    /**\n     * Register a handler for user_preferences webhook field\n     */\n    onUserPreferences(handler: UserPreferencesHandler): void {\n        this.userPreferencesHandler = handler;\n        LOGGER.log('Registered user_preferences handler');\n    }\n\n    // ============================================================================\n    // Handler removal methods\n    // ============================================================================\n\n    /**\n     * Remove a registered message handler by type\n     */\n    offMessage(type: MessageTypesEnum | string): void {\n        this.messageHandlers.delete(type as MessageTypesEnum);\n        LOGGER.log(`Removed message handler for ${type}`);\n    }\n\n    /**\n     * Remove the pre-process handler\n     */\n    offMessagePreProcess(): void {\n        this.preProcessHandler = undefined;\n        LOGGER.log('Removed pre-process handler');\n    }\n\n    /**\n     * Remove the post-process handler\n     */\n    offMessagePostProcess(): void {\n        this.postProcessHandler = undefined;\n        LOGGER.log('Removed post-process handler');\n    }\n\n    /**\n     * Remove the status handler\n     */\n    offStatus(): void {\n        this.statusHandler = undefined;\n        LOGGER.log('Removed status handler');\n    }\n\n    /**\n     * Remove the raw webhook handler\n     */\n    offRaw(): void {\n        this.rawHandler = undefined;\n        LOGGER.log('Removed raw webhook handler');\n    }\n\n    /**\n     * Remove a registered flow handler by type\n     */\n    offFlow(type: FlowTypeEnum): void {\n        this.flowHandlers.delete(type);\n        LOGGER.log(`Removed flow handler for ${type}`);\n    }\n\n    /**\n     * Remove all registered handlers\n     */\n    removeAllHandlers(): void {\n        this.messageHandlers.clear();\n        this.statusHandler = undefined;\n        this.preProcessHandler = undefined;\n        this.postProcessHandler = undefined;\n        this.rawHandler = undefined;\n        this.flowHandlers.clear();\n\n        // Webhook field handlers\n        this.accountUpdateHandler = undefined;\n        this.accountReviewUpdateHandler = undefined;\n        this.accountAlertsHandler = undefined;\n        this.businessCapabilityUpdateHandler = undefined;\n        this.phoneNumberNameUpdateHandler = undefined;\n        this.phoneNumberQualityUpdateHandler = undefined;\n        this.messageTemplateStatusUpdateHandler = undefined;\n        this.templateCategoryUpdateHandler = undefined;\n        this.messageTemplateQualityUpdateHandler = undefined;\n        this.flowsHandler = undefined;\n        this.securityHandler = undefined;\n        this.historyHandler = undefined;\n        this.smbMessageEchoesHandler = undefined;\n        this.smbAppStateSyncHandler = undefined;\n        this.accountSettingsUpdateHandler = undefined;\n        this.automaticEventsHandler = undefined;\n        this.businessStatusUpdateHandler = undefined;\n        this.callsHandler = undefined;\n        this.groupLifecycleUpdateHandler = undefined;\n        this.groupParticipantsUpdateHandler = undefined;\n        this.groupSettingsUpdateHandler = undefined;\n        this.groupStatusUpdateHandler = undefined;\n        this.messageEchoesHandler = undefined;\n        this.messageTemplateComponentsUpdateHandler = undefined;\n        this.messagingHandoversHandler = undefined;\n        this.partnerSolutionsHandler = undefined;\n        this.paymentConfigurationUpdateHandler = undefined;\n        this.standbyHandler = undefined;\n        this.templateCorrectCategoryDetectionHandler = undefined;\n        this.trackingEventsHandler = undefined;\n        this.userPreferencesHandler = undefined;\n\n        LOGGER.log('Removed all handlers');\n    }\n\n    getClient(): WhatsApp {\n        return this.client;\n    }\n\n    getConfig(): WabaConfigType {\n        return this.config;\n    }\n}\n","import type { WhatsAppConfig } from '../../../types/config';\nimport { constructFullUrl } from '../utils/webhookUtils';\nimport { WebhookProcessor } from '../WebhookProcessor';\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 | undefined;\n    send?(data?: any): T | undefined;\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 type { WebhookResponse } from '../../WebhookProcessor';\nimport { type BaseRequest, type BaseResponse, type BaseWebhookConfig, BaseWebhookHandler } from '../handler';\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 type NextFunction = (error?: any) => void;\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    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            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\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 bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\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.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            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\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            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\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\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, ReturnType<ExpressWebhookHandler['getHandlers']> & { destroy: () => void }>();\n\nfunction getCacheKey(config: ExpressWebhookConfig): string {\n    return `express:${config.phoneNumberId ?? 'default'}`;\n}\n\nexport function expressWebhookHandler(config: ExpressWebhookConfig) {\n    const key = getCacheKey(config);\n    const cached = handlerCache.get(key);\n    if (cached) return cached;\n\n    const handler = new ExpressWebhookHandler(config);\n    const handlers = {\n        ...handler.getHandlers(),\n        /**\n         * Destroy this handler instance: removes all registered handlers\n         * and clears it from the singleton cache so the next call creates a fresh instance.\n         */\n        destroy: () => {\n            handler.webhookProcessor.removeAllHandlers();\n            handlerCache.delete(key);\n        },\n    };\n\n    handlerCache.set(key, handlers);\n    return handlers;\n}\n","import type { 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// Singleton cache keyed by phoneNumberId\n// biome-ignore lint/suspicious/noExplicitAny: cache stores the handler return type which is complex and self-referential\nconst handlerCache = new Map<string, any>();\n\nfunction getCacheKey(config: NextJsAppWebhookConfig): string {\n    return `nextjs-app:${config.phoneNumberId ?? 'default'}`;\n}\n\n// Next.js App Router webhook handler\nexport function nextjsAppWebhookHandler(config: NextJsAppWebhookConfig) {\n    const key = getCacheKey(config);\n    const cached = handlerCache.get(key);\n    if (cached) return cached;\n\n    const processor = new WebhookProcessor(config);\n\n    const handlers = {\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         * Destroy this handler instance: removes all registered handlers\n         * and clears it from the singleton cache so the next call creates a fresh instance.\n         */\n        destroy: () => {\n            processor.removeAllHandlers();\n            handlerCache.delete(key);\n        },\n    };\n\n    handlerCache.set(key, handlers);\n    return handlers;\n}\n","import type { WebhookResponse } from '../../WebhookProcessor';\nimport { type BaseRequest, type BaseResponse, type BaseWebhookConfig, BaseWebhookHandler } from '../handler';\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): undefined | any;\n    send(data?: any): undefined | 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    // 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            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\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, true);\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                return {\n                    status: 400,\n                    body: JSON.stringify({ error: 'Invalid JSON' }),\n                    headers: { 'Content-Type': 'application/json' },\n                };\n            }\n\n            res.status(500).json({ error: 'Internal Server Error' });\n            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\n        }\n\n        try {\n            const fullUrl = this.constructFullUrl(req.headers, req.url);\n            const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n            const webRequest = new Request(fullUrl, {\n                method: 'POST',\n                headers: req.headers as HeadersInit,\n                body: bodyContent,\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            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\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                return {\n                    status: 400,\n                    body: JSON.stringify({ error: 'Invalid JSON' }),\n                    headers: { 'Content-Type': 'application/json' },\n                };\n            }\n\n            res.status(500).json({ error: 'Internal Server Error' });\n            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\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            return {\n                status: 500,\n                body: JSON.stringify({ error: 'Internal Server Error' }),\n                headers: { 'Content-Type': 'application/json' },\n            };\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// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<\n    string,\n    ReturnType<NextJsWebhookHandler<any, any>['getHandlers']> & { destroy: () => void }\n>();\n\nfunction getCacheKey(config: NextJsWebhookConfig): string {\n    return `nextjs-page:${config.phoneNumberId ?? 'default'}`;\n}\n\n// Next.js Pages Router webhook handler\nexport function nextjsPagesWebhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n    config: NextJsWebhookConfig,\n) {\n    const key = getCacheKey(config);\n    const cached = handlerCache.get(key);\n    if (cached) return cached;\n\n    const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n    const handlers = {\n        ...handler.getHandlers(),\n        /**\n         * Destroy this handler instance: removes all registered handlers\n         * and clears it from the singleton cache so the next call creates a fresh instance.\n         */\n        destroy: () => {\n            handler.webhookProcessor.removeAllHandlers();\n            handlerCache.delete(key);\n        },\n    };\n\n    handlerCache.set(key, handlers);\n    return handlers;\n}\n","import { MessageTypesEnum } from '../../../types/enums';\nimport type { WhatsAppMessage } from '../types/message';\n\n/**\n * Extracts a human-readable display text from any incoming WhatsApp message.\n *\n * Useful for logging, notifications, chat previews, and storing message summaries.\n *\n * @param message - The incoming WhatsApp message from a webhook handler\n * @returns A display-friendly string representing the message content\n *\n * @example\n * ```ts\n * handler.processor.onText(async (whatsapp, processed) => {\n *   const text = extractMessageText(processed.message);\n *   console.log(`Message from ${processed.message.from}: ${text}`);\n * });\n * ```\n */\nexport function extractMessageText(message: WhatsAppMessage): string {\n    switch (message.type) {\n        case MessageTypesEnum.Text:\n            return message.text.body;\n\n        case MessageTypesEnum.Image:\n            return message.image.caption || '[Image]';\n\n        case MessageTypesEnum.Video:\n            return message.video.caption || '[Video]';\n\n        case MessageTypesEnum.Audio:\n            return message.audio.voice ? '[Voice Message]' : '[Audio]';\n\n        case MessageTypesEnum.Document:\n            return message.document.caption || message.document.filename || '[Document]';\n\n        case MessageTypesEnum.Sticker:\n            return message.sticker.animated ? '[Animated Sticker]' : '[Sticker]';\n\n        case MessageTypesEnum.Interactive: {\n            const interactive = message.interactive;\n            if (interactive.type === 'button_reply') {\n                return interactive.button_reply.title;\n            }\n            if (interactive.type === 'list_reply') {\n                return interactive.list_reply.title;\n            }\n            if (interactive.type === 'nfm_reply') {\n                return interactive.nfm_reply.body || interactive.nfm_reply.name || '[Form Reply]';\n            }\n            return '[Interactive]';\n        }\n\n        case MessageTypesEnum.Button:\n            return message.button.text;\n\n        case MessageTypesEnum.Location:\n            return (\n                message.location.name ||\n                message.location.address ||\n                `📍 ${message.location.latitude}, ${message.location.longitude}`\n            );\n\n        case MessageTypesEnum.Contacts: {\n            const names = message.contacts.map((c) => c.name.formatted_name);\n            return names.length === 1 ? `👤 ${names[0]}` : `👤 ${names.length} contacts`;\n        }\n\n        case MessageTypesEnum.Reaction:\n            return message.reaction.emoji || '[Reaction removed]';\n\n        case MessageTypesEnum.Order: {\n            const count = message.order.product_items.length;\n            return `🛒 Order: ${count} item${count > 1 ? 's' : ''}`;\n        }\n\n        case MessageTypesEnum.System:\n            return message.system.body;\n\n        case MessageTypesEnum.Unsupported:\n            return '[Unsupported message]';\n\n        default:\n            return `[${(message as any).type}]`;\n    }\n}\n","import * as crypto from 'node:crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n    return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","import { MessageTypesEnum } from '../../../types/enums';\nimport type {\n    AudioMessage,\n    ButtonMessage,\n    ContactsMessage,\n    DocumentMessage,\n    ImageMessage,\n    InteractiveButtonReplyMessage,\n    InteractiveListReplyMessage,\n    InteractiveMessage,\n    InteractiveNfmReplyMessage,\n    LocationMessage,\n    OrderMessage,\n    ReactionMessage,\n    StickerMessage,\n    SystemMessage,\n    TextMessage,\n    VideoMessage,\n    WhatsAppMessage,\n} from '../types/message';\n\n// ============================================================================\n// Type Guards — narrow WhatsAppMessage to specific types\n// ============================================================================\n\nexport function isTextMessage(msg: WhatsAppMessage): msg is TextMessage {\n    return msg.type === MessageTypesEnum.Text;\n}\n\nexport function isImageMessage(msg: WhatsAppMessage): msg is ImageMessage {\n    return msg.type === MessageTypesEnum.Image;\n}\n\nexport function isVideoMessage(msg: WhatsAppMessage): msg is VideoMessage {\n    return msg.type === MessageTypesEnum.Video;\n}\n\nexport function isAudioMessage(msg: WhatsAppMessage): msg is AudioMessage {\n    return msg.type === MessageTypesEnum.Audio;\n}\n\nexport function isDocumentMessage(msg: WhatsAppMessage): msg is DocumentMessage {\n    return msg.type === MessageTypesEnum.Document;\n}\n\nexport function isStickerMessage(msg: WhatsAppMessage): msg is StickerMessage {\n    return msg.type === MessageTypesEnum.Sticker;\n}\n\nexport function isInteractiveMessage(msg: WhatsAppMessage): msg is InteractiveMessage {\n    return msg.type === MessageTypesEnum.Interactive;\n}\n\nexport function isButtonMessage(msg: WhatsAppMessage): msg is ButtonMessage {\n    return msg.type === MessageTypesEnum.Button;\n}\n\nexport function isLocationMessage(msg: WhatsAppMessage): msg is LocationMessage {\n    return msg.type === MessageTypesEnum.Location;\n}\n\nexport function isContactsMessage(msg: WhatsAppMessage): msg is ContactsMessage {\n    return msg.type === MessageTypesEnum.Contacts;\n}\n\nexport function isReactionMessage(msg: WhatsAppMessage): msg is ReactionMessage {\n    return msg.type === MessageTypesEnum.Reaction;\n}\n\nexport function isOrderMessage(msg: WhatsAppMessage): msg is OrderMessage {\n    return msg.type === MessageTypesEnum.Order;\n}\n\nexport function isSystemMessage(msg: WhatsAppMessage): msg is SystemMessage {\n    return msg.type === MessageTypesEnum.System;\n}\n\n// Interactive sub-type guards\nexport function isButtonReply(msg: WhatsAppMessage): msg is InteractiveButtonReplyMessage {\n    return isInteractiveMessage(msg) && msg.interactive.type === 'button_reply';\n}\n\nexport function isListReply(msg: WhatsAppMessage): msg is InteractiveListReplyMessage {\n    return isInteractiveMessage(msg) && msg.interactive.type === 'list_reply';\n}\n\nexport function isNfmReply(msg: WhatsAppMessage): msg is InteractiveNfmReplyMessage {\n    return isInteractiveMessage(msg) && msg.interactive.type === 'nfm_reply';\n}\n\n// ============================================================================\n// Structured data extractors — type-safe parsed data from messages\n// ============================================================================\n\nexport type MediaInfo = {\n    id: string;\n    mimeType: string;\n    sha256: string;\n    caption?: string;\n    filename?: string;\n    animated?: boolean;\n    voice?: boolean;\n};\n\n/**\n * Extract media info from image/video/audio/document/sticker messages.\n * Returns null if the message is not a media message.\n *\n * @example\n * ```ts\n * const media = getMediaInfo(message);\n * if (media) {\n *   const url = await sdk.media.get(media.id);\n * }\n * ```\n */\nexport function getMediaInfo(msg: WhatsAppMessage): MediaInfo | null {\n    if (isImageMessage(msg)) {\n        return {\n            id: msg.image.id,\n            mimeType: msg.image.mime_type,\n            sha256: msg.image.sha256,\n            caption: msg.image.caption,\n        };\n    }\n    if (isVideoMessage(msg)) {\n        return {\n            id: msg.video.id,\n            mimeType: msg.video.mime_type,\n            sha256: msg.video.sha256,\n            caption: msg.video.caption,\n        };\n    }\n    if (isAudioMessage(msg)) {\n        return { id: msg.audio.id, mimeType: msg.audio.mime_type, sha256: msg.audio.sha256, voice: msg.audio.voice };\n    }\n    if (isDocumentMessage(msg)) {\n        return {\n            id: msg.document.id,\n            mimeType: msg.document.mime_type,\n            sha256: msg.document.sha256,\n            caption: msg.document.caption,\n            filename: msg.document.filename,\n        };\n    }\n    if (isStickerMessage(msg)) {\n        return {\n            id: msg.sticker.id,\n            mimeType: msg.sticker.mime_type,\n            sha256: msg.sticker.sha256,\n            animated: msg.sticker.animated,\n        };\n    }\n    return null;\n}\n\nexport type InteractiveReply = {\n    type: 'button_reply' | 'list_reply' | 'nfm_reply';\n    id: string;\n    title: string;\n    description?: string;\n    responseJson?: string;\n};\n\n/**\n * Extract the user's selection from interactive messages (button reply, list reply, nfm reply).\n * Returns null if not an interactive message.\n *\n * @example\n * ```ts\n * const reply = getInteractiveReply(message);\n * if (reply) {\n *   console.log(`User selected: ${reply.title} (id: ${reply.id})`);\n * }\n * ```\n */\nexport function getInteractiveReply(msg: WhatsAppMessage): InteractiveReply | null {\n    if (!isInteractiveMessage(msg)) return null;\n\n    if (msg.interactive.type === 'button_reply') {\n        return {\n            type: 'button_reply',\n            id: msg.interactive.button_reply.id,\n            title: msg.interactive.button_reply.title,\n        };\n    }\n    if (msg.interactive.type === 'list_reply') {\n        return {\n            type: 'list_reply',\n            id: msg.interactive.list_reply.id,\n            title: msg.interactive.list_reply.title,\n            description: msg.interactive.list_reply.description,\n        };\n    }\n    if (msg.interactive.type === 'nfm_reply') {\n        return {\n            type: 'nfm_reply',\n            id: msg.interactive.nfm_reply.name,\n            title: msg.interactive.nfm_reply.body,\n            responseJson: msg.interactive.nfm_reply.response_json,\n        };\n    }\n    return null;\n}\n\nexport type LocationInfo = {\n    latitude: number;\n    longitude: number;\n    name?: string;\n    address?: string;\n    url?: string;\n};\n\n/**\n * Extract location data from a location message.\n * Returns null if not a location message.\n */\nexport function getLocationInfo(msg: WhatsAppMessage): LocationInfo | null {\n    if (!isLocationMessage(msg)) return null;\n    return {\n        latitude: msg.location.latitude,\n        longitude: msg.location.longitude,\n        name: msg.location.name,\n        address: msg.location.address,\n        url: msg.location.url,\n    };\n}\n\nexport type ContactInfo = {\n    formattedName: string;\n    firstName?: string;\n    lastName?: string;\n    phones: string[];\n    emails: string[];\n};\n\n/**\n * Extract contact info from a contacts message.\n * Returns empty array if not a contacts message.\n */\nexport function getContactsInfo(msg: WhatsAppMessage): ContactInfo[] {\n    if (!isContactsMessage(msg)) return [];\n    return msg.contacts.map((c) => ({\n        formattedName: c.name.formatted_name,\n        firstName: c.name.first_name,\n        lastName: c.name.last_name,\n        phones: c.phones?.map((p) => p.phone) || [],\n        emails: c.emails?.map((e) => e.email) || [],\n    }));\n}\n\nexport type ReactionInfo = {\n    messageId: string;\n    emoji: string | null; // null = reaction removed\n};\n\n/**\n * Extract reaction data from a reaction message.\n * Returns null if not a reaction message.\n */\nexport function getReactionInfo(msg: WhatsAppMessage): ReactionInfo | null {\n    if (!isReactionMessage(msg)) return null;\n    return {\n        messageId: msg.reaction.message_id,\n        emoji: msg.reaction.emoji || null,\n    };\n}\n\nexport type OrderInfo = {\n    catalogId: string;\n    text?: string;\n    items: Array<{\n        productId: string;\n        quantity: number;\n        price: number;\n        currency: string;\n    }>;\n};\n\n/**\n * Extract order data from an order message.\n * Returns null if not an order message.\n */\nexport function getOrderInfo(msg: WhatsAppMessage): OrderInfo | null {\n    if (!isOrderMessage(msg)) return null;\n    return {\n        catalogId: msg.order.catalog_id,\n        text: msg.order.text,\n        items: msg.order.product_items.map((item) => ({\n            productId: item.product_retailer_id,\n            quantity: item.quantity,\n            price: item.item_price,\n            currency: item.currency,\n        })),\n    };\n}\n","/**\n * As-const alternatives to enums.\n *\n * Every enum in enums.ts gets a matching `as const` object and a union type here.\n * Use whichever style you prefer:\n *   - Enum:  CategoryEnum.Marketing\n *   - Const: Category.Marketing  (value: 'MARKETING')\n *   - Type:  CategoryType        (union: 'AUTHENTICATION' | 'MARKETING' | 'UTILITY')\n */\n\n// ---- Category ----\nexport const Category = {\n    Authentication: 'AUTHENTICATION',\n    Marketing: 'MARKETING',\n    Utility: 'UTILITY',\n} as const;\nexport type CategoryType = (typeof Category)[keyof typeof Category];\n\n// ---- TemplateStatus ----\nexport const TemplateStatus = {\n    Approved: 'APPROVED',\n    Pending: 'PENDING',\n    Rejected: 'REJECTED',\n} as const;\nexport type TemplateStatusType = (typeof TemplateStatus)[keyof typeof TemplateStatus];\n\n// ---- HttpMethods ----\nexport const HttpMethods = {\n    Get: 'GET',\n    Post: 'POST',\n    Put: 'PUT',\n    Delete: 'DELETE',\n} as const;\nexport type HttpMethodsType = (typeof HttpMethods)[keyof typeof HttpMethods];\n\n// ---- MessageTypes ----\nexport const MessageTypes = {\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    /** @deprecated Use WebhookProcessor.onStatus() instead */\n    Statuses: 'statuses',\n    All: '*',\n} as const;\nexport type MessageTypesType = (typeof MessageTypes)[keyof typeof MessageTypes];\n\n// ---- ParametersTypes ----\nexport const ParametersTypes = {\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} as const;\nexport type ParametersTypesType = (typeof ParametersTypes)[keyof typeof ParametersTypes];\n\n// ---- InteractiveTypes ----\nexport const InteractiveTypes = {\n    Button: 'button',\n    List: 'list',\n    Product: 'product',\n    ProductList: 'product_list',\n    CtaUrl: 'cta_url',\n    Carousel: 'carousel',\n    LocationRequest: 'location_request_message',\n    AddressMessage: 'address_message',\n    Flow: 'flow',\n} as const;\nexport type InteractiveTypesType = (typeof InteractiveTypes)[keyof typeof InteractiveTypes];\n\n// ---- ButtonPosition ----\nexport const ButtonPosition = {\n    First: 1,\n    Second: 2,\n    Third: 3,\n    Fourth: 4,\n    Fifth: 5,\n} as const;\nexport type ButtonPositionType = (typeof ButtonPosition)[keyof typeof ButtonPosition];\n\n// ---- SubType ----\nexport const SubType = {\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} as const;\nexport type SubTypeType = (typeof SubType)[keyof typeof SubType];\n\n// ---- ComponentTypes (template) ----\nexport const ComponentType = {\n    Header: 'HEADER',\n    Body: 'BODY',\n    Button: 'BUTTON',\n    Footer: 'FOOTER',\n} as const;\nexport type ComponentTypeType = (typeof ComponentType)[keyof typeof ComponentType];\n\n// ---- ConversationTypes ----\nexport const ConversationTypes = {\n    BusinessInitiated: 'business_initiated',\n    CustomerInitiated: 'customer_initiated',\n    ReferralConversion: 'referral_conversion',\n} as const;\nexport type ConversationTypesType = (typeof ConversationTypes)[keyof typeof ConversationTypes];\n\n// ---- Status ----\nexport const Status = {\n    Delivered: 'delivered',\n    Read: 'read',\n    Sent: 'sent',\n} as const;\nexport type StatusType = (typeof Status)[keyof typeof Status];\n\n// ---- VideoMediaTypes ----\nexport const VideoMediaTypes = {\n    Mp4: 'video/mp4',\n    Threegp: 'video/3gp',\n} as const;\nexport type VideoMediaTypesType = (typeof VideoMediaTypes)[keyof typeof VideoMediaTypes];\n\n// ---- StickerMediaTypes ----\nexport const StickerMediaTypes = {\n    Webp: 'image/webp',\n} as const;\nexport type StickerMediaTypesType = (typeof StickerMediaTypes)[keyof typeof StickerMediaTypes];\n\n// ---- ImageMediaTypes ----\nexport const ImageMediaTypes = {\n    Jpeg: 'image/jpeg',\n    Png: 'image/png',\n} as const;\nexport type ImageMediaTypesType = (typeof ImageMediaTypes)[keyof typeof ImageMediaTypes];\n\n// ---- DocumentMediaTypes ----\nexport const DocumentMediaTypes = {\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} as const;\nexport type DocumentMediaTypesType = (typeof DocumentMediaTypes)[keyof typeof DocumentMediaTypes];\n\n// ---- AudioMediaTypes ----\nexport const AudioMediaTypes = {\n    Aac: 'audio/aac',\n    Mp4: 'audio/mp4',\n    Mpeg: 'audio/mpeg',\n    Amr: 'audio/amr',\n    Ogg: 'audio/ogg',\n} as const;\nexport type AudioMediaTypesType = (typeof AudioMediaTypes)[keyof typeof AudioMediaTypes];\n\n// ---- WebhookTypes ----\nexport const WebhookTypes = {\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} as const;\nexport type WebhookTypesType = (typeof WebhookTypes)[keyof typeof WebhookTypes];\n\n// ---- SystemChangeTypes ----\nexport const SystemChangeTypes = {\n    CustomerChangedNumber: 'customer_changed_number',\n    CustomerIdentityChanged: 'customer_identity_changed',\n} as const;\nexport type SystemChangeTypesType = (typeof SystemChangeTypes)[keyof typeof SystemChangeTypes];\n\n// ---- ReferralSourceTypes ----\nexport const ReferralSourceTypes = {\n    Ad: 'ad',\n    Post: 'post',\n} as const;\nexport type ReferralSourceTypesType = (typeof ReferralSourceTypes)[keyof typeof ReferralSourceTypes];\n\n// ---- RequestCodeMethods ----\nexport const RequestCodeMethods = {\n    Sms: 'SMS',\n    Voice: 'VOICE',\n} as const;\nexport type RequestCodeMethodsType = (typeof RequestCodeMethods)[keyof typeof RequestCodeMethods];\n\n// ---- Languages ----\nexport const Languages = {\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} as const;\nexport type LanguagesType = (typeof Languages)[keyof typeof Languages];\n\n// ---- DataLocalizationRegion ----\nexport const DataLocalizationRegion = {\n    AU: 'AU',\n    ID: 'ID',\n    IN: 'IN',\n    JP: 'JP',\n    SG: 'SG',\n    KR: 'KR',\n    DE: 'DE',\n    CH: 'CH',\n    GB: 'GB',\n    BR: 'BR',\n    BH: 'BH',\n    ZA: 'ZA',\n    AE: 'AE',\n    CA: 'CA',\n} as const;\nexport type DataLocalizationRegionType = (typeof DataLocalizationRegion)[keyof typeof DataLocalizationRegion];\n"],"mappings":"wOAAA,MAYa,EAA6B,WCH1C,IAAa,EAAb,KAA0C,CACtC,OACA,OAEA,YAAY,EAAwB,EAAwB,CACxD,KAAK,OAAS,EACd,KAAK,OAAS,EAGlB,SAAsB,EAAyB,EAAkB,EAAiB,EAAwB,CACtG,OAAO,KAAK,OAAO,QAAW,EAAQ,EAAU,EAAS,EAAK,CAGlE,aAA0B,EAAyB,EAAkB,EAAiB,EAAwB,CAC1G,OAAO,KAAK,OAAO,aAAgB,EAAQ,EAAU,EAAS,EAAK,CAGvE,mBACI,EACA,EACA,EACA,EACU,CACV,OAAO,KAAK,OAAO,mBAAsB,EAAQ,EAAU,EAAS,EAAK,4oBChCjF,IAAY,EAAL,SAAA,EAAA,OACH,GAAA,eAAA,iBACA,EAAA,UAAA,YACA,EAAA,QAAA,gBACH,CAEW,EAAL,SAAA,EAAA,OACH,GAAA,SAAA,WACA,EAAA,QAAA,UACA,EAAA,SAAA,iBACH,C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AU,iBACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,qBACT,EACA,EACH,CACM,EAAO,QAAU,6BACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,gCACT,EACA,EACH,CACM,EAAO,QAAU,2BACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,6BACT,EACA,EACH,CACM,EAAO,QAAU,8BACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,gCACT,EACA,EACH,CACM,EAAO,QAAU,iCACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,mCACT,EACA,EACH,CACM,EAAO,QAAU,2BACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,8BACT,EACA,EACH,CACM,EAAO,QAAU,kCACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,oCACT,EACA,EACH,CACM,EAAO,QAAU,QACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,aACT,EACA,EACH,CACM,EAAO,QAAU,WACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,gBACT,EACA,EACH,CACM,EAAO,QAAU,UACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,eACT,EACA,EACH,CACM,EAAO,QAAU,qBACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,wBACT,EACA,EACH,CACM,EAAO,QAAU,qBACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,uBACT,EACA,EACH,CACM,EAAO,QAAU,0BACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,6BACT,EACA,EACH,CACM,EAAO,QAAU,mBACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,uBACT,EACA,EACH,CACM,EAAO,QAAU,yBACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,4BACT,EACA,EACH,CACM,EAAO,QAAU,QACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,aACT,EACA,EACH,CACM,EAAO,QAAU,yBACxB,MAAM,EACF,EAAM,GACN,EACA,EAAS,4BACT,EACA,EACH,CACM,EAAO,QAAU,4BACxB,MA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