meta-cloud-api 0.2.14 → 0.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/{index.d.mts → index.d.ts} +1 -1
- package/dist/api/{index.mjs → index.js} +2 -2
- package/dist/{types/index.mjs.map → api/index.js.map} +1 -1
- package/dist/{chunk-XVYL7ZTG.mjs → chunk-IE2YYEC7.js} +2 -2
- package/dist/{chunk-XVYL7ZTG.mjs.map → chunk-IE2YYEC7.js.map} +1 -1
- package/dist/chunk-IMPHLXRA.js +2 -0
- package/dist/chunk-IMPHLXRA.js.map +1 -0
- package/dist/{chunk-KZQQJAPX.mjs → chunk-KW56EPP7.js} +2 -2
- package/dist/chunk-KW56EPP7.js.map +1 -0
- package/dist/chunk-SLDCD6XR.js +2 -0
- package/dist/chunk-SLDCD6XR.js.map +1 -0
- package/dist/{chunk-QE4PKOSW.mjs → chunk-UVPYV4PL.js} +2 -2
- package/dist/chunk-UVPYV4PL.js.map +1 -0
- package/dist/{index.d.mts → index.d.ts} +7 -7
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/types/{index.d.mts → index.d.ts} +3 -3
- package/dist/types/index.js +2 -0
- package/dist/{utils/index.mjs.map → types/index.js.map} +1 -1
- package/dist/utils/{index.d.mts → index.d.ts} +2 -2
- package/dist/utils/index.js +2 -0
- package/dist/{api/index.mjs.map → utils/index.js.map} +1 -1
- package/dist/{whatsapp-BNHXjrds.d.mts → whatsapp-DmeO83A8.d.ts} +1 -1
- package/package.json +2 -1
- package/dist/chunk-KZQQJAPX.mjs.map +0 -1
- package/dist/chunk-N7A7DQDX.mjs +0 -2
- package/dist/chunk-N7A7DQDX.mjs.map +0 -1
- package/dist/chunk-QE4PKOSW.mjs.map +0 -1
- package/dist/chunk-R4CFE2XP.mjs +0 -2
- package/dist/chunk-R4CFE2XP.mjs.map +0 -1
- package/dist/index.mjs +0 -3
- package/dist/index.mjs.map +0 -1
- package/dist/types/index.mjs +0 -2
- package/dist/utils/index.mjs +0 -2
- /package/dist/{waba-RRlZTQUG.d.mts → waba-RRlZTQUG.d.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/generateXHub256Sig.ts","../src/utils/importConfig.ts","../src/utils/isMetaError.ts","../src/utils/flowTypeGuards.ts"],"names":["generateXHub256Sig","body","appSecret","LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","isMetaError","error","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest"],"mappings":"6DAEaA,IAAAA,CAAAA,CAAqB,CAACC,CAAcC,CAAAA,CAAAA,GAC/B,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUA,CAAS,CAAA,CAAE,OAAOD,CAAM,CAAA,OAAO,CAAE,CAAA,MAAA,CAAO,KAAK,MCE9EE,CAAW,CAAA,OAAA,CACXC,CAAY,CAAA,KAAA,CACZC,CAAS,CAAA,IAAIC,EAAOH,CAAU,CAAA,OAAA,CAAQ,IAAI,KAAU,GAAA,MAAA,EAAUC,CAAS,CACvEG,CAAAA,CAAAA,CAAwB,GACxBC,CAAAA,CAAAA,CAAiC,EACjCC,CAAAA,CAAAA,CAA0B,IAE1BC,CAAsBC,CAAAA,CAAAA,EAAuC,CAC/D,GAAI,CAAC,OAAA,CAAQ,IAAI,sBAA+B,EAAA,CAACA,CAAQ,EAAA,WAAA,CACrD,MAAAN,CAAAA,CAAO,IAAI,2FAA2F,CAAA,CAChG,IAAI,KAAM,CAAA,gCAAgC,CAExD,CAEaO,CAAAA,CAAAA,CAAgBC,CAAiC,EAAA,CAC1DH,CAAmBG,CAAAA,C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CAAA,CAGhCK,CACFd,CAAAA,CAAAA,CAASU,CAAI,CAAA,EACb,cAAeA,CACfR,EAAAA,CAAAA,CAASQ,CAAK,CAAA,KAAK,CACnB,EAAA,eAAA,GAAmBA,GACnBR,CAASQ,CAAAA,CAAAA,CAAK,aAAa,CAAA,CAG/B,OAAOE,CAAAA,EAAkBC,GAAkBC,CAC/C,CASO,SAASE,CAAAA,CAAkBV,CAAiE,CAAA,CAE/F,OAAO,QAAYA,GAAAA,CAAAA,EAAWA,CAAQ,CAAA,MAAA,GAAW,MACrD","file":"chunk-SLDCD6XR.js","sourcesContent":["import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","import { WhatsAppConfig } from 'src/types/whatsapp';\nimport type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from './logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\n};\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from 'src/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"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var o=class{name;debug;constructor(n,e=false){this.name=n,this.debug=e;}log(...n){if(this.debug){let e=`[ ${Date.now()} ]`;this.name&&(e+=` - ${this.name}`),console.log.apply(console,[e,": ",...n]);}}error(...n){let e=`[ ${Date.now()} ] - ERROR`;this.name&&(e+=` - ${this.name}`),console.error.apply(console,[e,": ",...n]);}warn(...n){let e=`[ ${Date.now()} ] - WARN`;this.name&&(e+=` - ${this.name}`),console.warn.apply(console,[e,": ",...n]);}info(...n){let e=`[ ${Date.now()} ] - INFO`;this.name&&(e+=` - ${this.name}`),console.info.apply(console,[e,": ",...n]);}};var s=t=>{if(!t||Object.keys(t).length===0)return "";let n=new URLSearchParams;for(let[a,r]of Object.entries(t))r!==void 0&&n.append(a,String(r));let e=n.toString();return e?`?${e}`:""};export{o as a,s as b};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var o=class{name;debug;constructor(n,e=false){this.name=n,this.debug=e;}log(...n){if(this.debug){let e=`[ ${Date.now()} ]`;this.name&&(e+=` - ${this.name}`),console.log.apply(console,[e,": ",...n]);}}error(...n){let e=`[ ${Date.now()} ] - ERROR`;this.name&&(e+=` - ${this.name}`),console.error.apply(console,[e,": ",...n]);}warn(...n){let e=`[ ${Date.now()} ] - WARN`;this.name&&(e+=` - ${this.name}`),console.warn.apply(console,[e,": ",...n]);}info(...n){let e=`[ ${Date.now()} ] - INFO`;this.name&&(e+=` - ${this.name}`),console.info.apply(console,[e,": ",...n]);}};var s=t=>{if(!t||Object.keys(t).length===0)return "";let n=new URLSearchParams;for(let[a,r]of Object.entries(t))r!==void 0&&n.append(a,String(r));let e=n.toString();return e?`?${e}`:""};export{o as a,s as b};//# sourceMappingURL=chunk-UVPYV4PL.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-UVPYV4PL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/logger.ts","../src/utils/objectToQueryString.ts"],"names":["Logger","name","debug","data","prefix","objectToQueryString","params","searchParams","key","value","queryString"],"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M,IAAK,CAAA,IAAI,IAE7B,OAAQ,CAAA,IAAA,CAAK,MAAM,OAAS,CAAA,CAACA,EAAQ,IAAM,CAAA,GAAGD,CAAI,CAAC,EACvD,CACJ,EC7CO,IAAME,EAAuBC,CAAwC,EAAA,CACxE,GAAI,CAACA,CAAAA,EAAU,OAAO,IAAKA,CAAAA,CAAM,EAAE,MAAW,GAAA,CAAA,CAC1C,OAAO,EAGX,CAAA,IAAMC,EAAe,IAAI,eAAA,CAEzB,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAK,GAAA,MAAA,CAAO,QAAQH,CAAM,CAAA,CACxCG,IAAU,MACVF,EAAAA,CAAAA,CAAa,OAAOC,CAAK,CAAA,MAAA,CAAOC,CAAK,CAAC,CAAA,CAI9C,IAAMC,CAAcH,CAAAA,CAAAA,CAAa,UACjC,CAAA,OAAOG,EAAc,CAAIA,CAAAA,EAAAA,CAAW,GAAK,EAC7C","file":"chunk-UVPYV4PL.js","sourcesContent":["// @ts-nocheck\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 log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...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.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n searchParams.append(key, String(value));\n }\n }\n\n const queryString = searchParams.toString();\n return queryString ? `?${queryString}` : '';\n};\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { IncomingMessage } from 'http';
|
|
2
|
-
import { H as HttpMethodsEnum, c as RequesterClass, d as WabaConfigType, S as SDKEnums, e as MessageTypesEnum, f as FlowEndpointRequest, g as FlowTypeEnum } from './waba-RRlZTQUG.
|
|
3
|
-
export { a$ as AccountMode, aA as AudioMediaObject, G as AudioMediaTypesEnum, aB as AudioMessageRequestBody, h as BaseClass, B as BusinessProfileClass, k as BusinessProfileData, i as BusinessProfileField, j as BusinessProfileFieldsParam, l as BusinessProfileResponse, Z as BusinessVerticalEnum, u as ButtonPositionEnum, t as ButtonTypesEnum, C as CategoryEnum, b0 as CodeVerificationStatus, bE as ComponentTypes, v as ComponentTypesEnum, aC as ContactObject, aD as ContactsMessageRequestBody, x as ConversationTypesEnum, bu as CopyCodeButton, ad as CreateFlowResponse, bg as CreateQrCodeRequest, X as CurrencyCodesEnum, b9 as Cursors, Y as DataLocalizationRegionEnum, aE as DocumentMediaObject, D as DocumentMediaTypesEnum, aF as DocumentMessageRequestBody, E as EncryptionClass, q as EncryptionPublicKeyResponse, a3 as Flow, a0 as FlowActionEnum, a7 as FlowAsset, a8 as FlowAssetsResponse, bv as FlowButton, $ as FlowCategoryEnum, F as FlowClass, am as FlowDataExchangeRequest, an as FlowDataExchangeResponse, ai as FlowDecryptedRequestResponse, ah as FlowEncryptedRequestPayload, ar as FlowEndpointResponse, ap as FlowErrorNotificationRequest, aq as FlowErrorNotificationResponse, ak as FlowHealthCheckRequest, al as FlowHealthCheckResponse, aj as FlowHttpRequest, ac as FlowMigrationFailure, af as FlowMigrationResponse, ab as FlowMigrationResult, a9 as FlowPreview, aa as FlowPreviewResponse, _ as FlowStatusEnum, ao as FlowSuccessScreenResponse, a2 as FlowValidationError, a1 as FlowValidationErrorPointer, a6 as FlowsListResponse, bk as GeneralHeaderInterface, av as GeneralMessageBody, bj as GeneralRequestBody, b5 as HealthStatus, b4 as HealthStatusEntity, aG as ImageMediaObject, A as ImageMediaTypesEnum, aH as ImageMessageRequestBody, aJ as InteractiveMessageRequestBody, aI as InteractiveObject, I as InteractiveTypesEnum, O as LanguagesEnum, aU as LocationMessageRequestBody, aT as LocationObject, bw as MPMButton, b as MediaClass, as as MediaResponse, at as MediasResponse, az as MessageRequestBody, aW as MessageRequestParams, aR as MessageTemplateObject, aS as MessageTemplateRequestBody, M as MessagesClass, aV as MessagesResponse, b1 as MessagingLimitTier, bx as OTPButton, a5 as Pagination, a4 as PaginationCursors, bp as Paging, s as ParametersTypesEnum, br as PhoneNumberButton, P as PhoneNumberClass, b8 as PhoneNumberResponse, ba as PhoneNumbersResponse, b2 as PlatformType, Q as QrCodeClass, be as QrCodeResponse, bf as QrCodesResponse, a_ as QualityRating, b6 as QualityScore, bt as QuickReplyButton, aM as ReactionMessageRequestBody, aY as ReactionParams, L as ReferralSourceTypesEnum, R as RegistrationClass, bi as RegistrationRequest, N as RequestCodeMethodsEnum, bb as RequestVerificationCodeRequest, bl as RequesterResponseInterface, bn as ResponseData, bo as ResponsePagination, bm as ResponseSuccess, by as SPMButton, y as StatusEnum, aw as StatusObject, aZ as StatusParams, ay as StatusRequestBody, aK as StickerMediaObject, z as StickerMediaTypesEnum, aL as StickerMessageRequestBody, K as SystemChangeTypesEnum, bC as TemplateBody, bz as TemplateButton, T as TemplateClass, bI as TemplateDeleteParams, bD as TemplateFooter, bq as TemplateFormat, bH as TemplateGetParams, bB as TemplateHeader, bA as TemplateHeaderExample, bF as TemplateRequestBody, bG as TemplateResponse, r as TemplateStatusEnum, aX as TextMessageParams, aO as TextMessageRequestBody, aN as TextObject, b7 as Throughput, b3 as ThroughputLevel, a as TwoStepVerificationClass, bd as TwoStepVerificationParams, bJ as TwoStepVerificationRequest, ax as TypingIndicatorObject, bs as URLButton, U as UpdateBusinessProfileRequest, ae as UpdateFlowResponse, bh as UpdateQrCodeRequest, bL as UpdateWabaSubscription, o as UploadBusinessProfileResponse, p as UploadHandle, au as UploadMediaResponse, m as UploadSession, n as UploadSessionResponse, ag as ValidateFlowJsonResponse, bc as VerifyCodeRequest, aP as VideoMediaObject, V as VideoMediaTypesEnum, aQ as VideoMessageRequestBody, W as WABAClass, bU as WabaAccount, bV as WabaAccountFields, bW as WabaAccountFieldsParam, bN as WabaAccountReviewStatus, bP as WabaAccountStatus, bQ as WabaBusinessVerificationStatus, w as WabaConfigEnum, bT as WabaHealthStatus, bO as WabaHealthStatusCanSendMessage, bS as WabaHealthStatusEntity, bR as WabaHealthStatusError, bK as WabaSubscription, bM as WabaSubscriptions, J as WebhookTypesEnum } from './waba-RRlZTQUG.
|
|
4
|
-
import { HttpsClientClass, HttpsClientResponseClass, WebhookMessage, WebhookEvent } from './types/index.
|
|
5
|
-
export { EventField, EventHandler, LoggerInterface, MessageHandler, MessageStatus, ResponseHeaderValue, ResponseHeaders, ResponseJSONBody, WebhookContact } from './types/index.
|
|
6
|
-
import { W as WhatsAppClass, a as WhatsAppConfig } from './whatsapp-
|
|
7
|
-
import { MessagesAPI as MessagesApi, TemplateAPI as TemplateApi, PhoneNumberAPI as PhoneNumberApi, QrCodeAPI, EncryptionAPI, TwoStepVerificationAPI, RegistrationAPI, MediaAPI, WabaAPI, FlowAPI, BusinessProfileAPI } from './api/index.
|
|
2
|
+
import { H as HttpMethodsEnum, c as RequesterClass, d as WabaConfigType, S as SDKEnums, e as MessageTypesEnum, f as FlowEndpointRequest, g as FlowTypeEnum } from './waba-RRlZTQUG.js';
|
|
3
|
+
export { a$ as AccountMode, aA as AudioMediaObject, G as AudioMediaTypesEnum, aB as AudioMessageRequestBody, h as BaseClass, B as BusinessProfileClass, k as BusinessProfileData, i as BusinessProfileField, j as BusinessProfileFieldsParam, l as BusinessProfileResponse, Z as BusinessVerticalEnum, u as ButtonPositionEnum, t as ButtonTypesEnum, C as CategoryEnum, b0 as CodeVerificationStatus, bE as ComponentTypes, v as ComponentTypesEnum, aC as ContactObject, aD as ContactsMessageRequestBody, x as ConversationTypesEnum, bu as CopyCodeButton, ad as CreateFlowResponse, bg as CreateQrCodeRequest, X as CurrencyCodesEnum, b9 as Cursors, Y as DataLocalizationRegionEnum, aE as DocumentMediaObject, D as DocumentMediaTypesEnum, aF as DocumentMessageRequestBody, E as EncryptionClass, q as EncryptionPublicKeyResponse, a3 as Flow, a0 as FlowActionEnum, a7 as FlowAsset, a8 as FlowAssetsResponse, bv as FlowButton, $ as FlowCategoryEnum, F as FlowClass, am as FlowDataExchangeRequest, an as FlowDataExchangeResponse, ai as FlowDecryptedRequestResponse, ah as FlowEncryptedRequestPayload, ar as FlowEndpointResponse, ap as FlowErrorNotificationRequest, aq as FlowErrorNotificationResponse, ak as FlowHealthCheckRequest, al as FlowHealthCheckResponse, aj as FlowHttpRequest, ac as FlowMigrationFailure, af as FlowMigrationResponse, ab as FlowMigrationResult, a9 as FlowPreview, aa as FlowPreviewResponse, _ as FlowStatusEnum, ao as FlowSuccessScreenResponse, a2 as FlowValidationError, a1 as FlowValidationErrorPointer, a6 as FlowsListResponse, bk as GeneralHeaderInterface, av as GeneralMessageBody, bj as GeneralRequestBody, b5 as HealthStatus, b4 as HealthStatusEntity, aG as ImageMediaObject, A as ImageMediaTypesEnum, aH as ImageMessageRequestBody, aJ as InteractiveMessageRequestBody, aI as InteractiveObject, I as InteractiveTypesEnum, O as LanguagesEnum, aU as LocationMessageRequestBody, aT as LocationObject, bw as MPMButton, b as MediaClass, as as MediaResponse, at as MediasResponse, az as MessageRequestBody, aW as MessageRequestParams, aR as MessageTemplateObject, aS as MessageTemplateRequestBody, M as MessagesClass, aV as MessagesResponse, b1 as MessagingLimitTier, bx as OTPButton, a5 as Pagination, a4 as PaginationCursors, bp as Paging, s as ParametersTypesEnum, br as PhoneNumberButton, P as PhoneNumberClass, b8 as PhoneNumberResponse, ba as PhoneNumbersResponse, b2 as PlatformType, Q as QrCodeClass, be as QrCodeResponse, bf as QrCodesResponse, a_ as QualityRating, b6 as QualityScore, bt as QuickReplyButton, aM as ReactionMessageRequestBody, aY as ReactionParams, L as ReferralSourceTypesEnum, R as RegistrationClass, bi as RegistrationRequest, N as RequestCodeMethodsEnum, bb as RequestVerificationCodeRequest, bl as RequesterResponseInterface, bn as ResponseData, bo as ResponsePagination, bm as ResponseSuccess, by as SPMButton, y as StatusEnum, aw as StatusObject, aZ as StatusParams, ay as StatusRequestBody, aK as StickerMediaObject, z as StickerMediaTypesEnum, aL as StickerMessageRequestBody, K as SystemChangeTypesEnum, bC as TemplateBody, bz as TemplateButton, T as TemplateClass, bI as TemplateDeleteParams, bD as TemplateFooter, bq as TemplateFormat, bH as TemplateGetParams, bB as TemplateHeader, bA as TemplateHeaderExample, bF as TemplateRequestBody, bG as TemplateResponse, r as TemplateStatusEnum, aX as TextMessageParams, aO as TextMessageRequestBody, aN as TextObject, b7 as Throughput, b3 as ThroughputLevel, a as TwoStepVerificationClass, bd as TwoStepVerificationParams, bJ as TwoStepVerificationRequest, ax as TypingIndicatorObject, bs as URLButton, U as UpdateBusinessProfileRequest, ae as UpdateFlowResponse, bh as UpdateQrCodeRequest, bL as UpdateWabaSubscription, o as UploadBusinessProfileResponse, p as UploadHandle, au as UploadMediaResponse, m as UploadSession, n as UploadSessionResponse, ag as ValidateFlowJsonResponse, bc as VerifyCodeRequest, aP as VideoMediaObject, V as VideoMediaTypesEnum, aQ as VideoMessageRequestBody, W as WABAClass, bU as WabaAccount, bV as WabaAccountFields, bW as WabaAccountFieldsParam, bN as WabaAccountReviewStatus, bP as WabaAccountStatus, bQ as WabaBusinessVerificationStatus, w as WabaConfigEnum, bT as WabaHealthStatus, bO as WabaHealthStatusCanSendMessage, bS as WabaHealthStatusEntity, bR as WabaHealthStatusError, bK as WabaSubscription, bM as WabaSubscriptions, J as WebhookTypesEnum } from './waba-RRlZTQUG.js';
|
|
4
|
+
import { HttpsClientClass, HttpsClientResponseClass, WebhookMessage, WebhookEvent } from './types/index.js';
|
|
5
|
+
export { EventField, EventHandler, LoggerInterface, MessageHandler, MessageStatus, ResponseHeaderValue, ResponseHeaders, ResponseJSONBody, WebhookContact } from './types/index.js';
|
|
6
|
+
import { W as WhatsAppClass, a as WhatsAppConfig } from './whatsapp-DmeO83A8.js';
|
|
7
|
+
import { MessagesAPI as MessagesApi, TemplateAPI as TemplateApi, PhoneNumberAPI as PhoneNumberApi, QrCodeAPI, EncryptionAPI, TwoStepVerificationAPI, RegistrationAPI, MediaAPI, WabaAPI, FlowAPI, BusinessProfileAPI } from './api/index.js';
|
|
8
8
|
import { Agent } from 'https';
|
|
9
|
-
export { MetaError, generateXHub256Sig, importConfig, isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest, isMetaError, objectToQueryString } from './utils/index.
|
|
9
|
+
export { MetaError, generateXHub256Sig, importConfig, isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest, isMetaError, objectToQueryString } from './utils/index.js';
|
|
10
10
|
|
|
11
11
|
declare class HttpsClient implements HttpsClientClass {
|
|
12
12
|
agent: Agent;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {f,j,g as g$1,h,c,k,i,e,l as l$1,d,b as b$1}from'./chunk-IMPHLXRA.js';import {b,f as f$1,d as d$1,e as e$1,c as c$1}from'./chunk-SLDCD6XR.js';export{a as generateXHub256Sig,b as importConfig,d as isFlowDataExchangeRequest,e as isFlowErrorRequest,f as isFlowPingRequest,c as isMetaError}from'./chunk-SLDCD6XR.js';import {a}from'./chunk-UVPYV4PL.js';export{b as objectToQueryString}from'./chunk-UVPYV4PL.js';export{j as EventField,c as FlowActionEnum,b as FlowCategoryEnum,a as FlowStatusEnum,d as FlowTypeEnum,i as MessageStatus,e as WabaAccountReviewStatus,g as WabaAccountStatus,h as WabaBusinessVerificationStatus,f as WabaHealthStatusCanSendMessage}from'./chunk-KW56EPP7.js';import {z as z$1}from'./chunk-IE2YYEC7.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,h as ButtonPositionEnum,g as ButtonTypesEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-IE2YYEC7.js';import h$1 from'crypto';import {Agent}from'https';var J="HttpsClient",Q=false,z=new a(J,process.env.DEBUG==="true"||Q),g=class{agent;constructor(){this.agent=new Agent({keepAlive:true});}clearSockets(){return this.agent.destroy(),true}async sendRequest(e,s,n,o,i,a){let r=`https://${e}/${s}`,d=new AbortController,t=setTimeout(()=>d.abort(),i);try{let c=await fetch(r,{method:n,headers:o,body:a,signal:d.signal});return z.log(`${n} : ${r} - ${JSON.stringify(c)}`),clearTimeout(t),new A(c)}catch(c){throw c}}},A=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries());}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};var X="REQUESTER",Y=false,Z=new a(X,process.env.DEBUG==="true"||Y),m=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,s,n,o,i){this.client=new g,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=s,this.accessToken=n,this.businessAcctId=o,this.userAgent=i;}buildHeader(e,s){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(n["Content-Type"]=e),s&&Object.assign(n,s),n}buildCAPIPath(e){return `v${this.apiVersion}.0/${e}`}async sendRequest(e,s,n,o,i="application/json",a){let r=i;o instanceof FormData?r="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(r="application/xml");let d=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;Z.log(`${e} : ${d} (${r})`);try{let t=await this.client.sendRequest(this.host,this.buildCAPIPath(s),e,this.buildHeader(r,a),n,e==="POST"||e==="PUT"?o:void 0);if(!t.rawResponse().ok){let c=await t.json();throw c$1(c)?c:{name:"MetaError",message:"Unknown error occurred",error:{message:c.message||"Unknown error occurred",type:"UnknownError",code:t.statusCode(),fbtrace_id:""}}}return t}catch(t){throw c$1(t)?t:{name:"MetaError",message:t instanceof Error?t.message:"Network error occurred",error:{message:t instanceof Error?t.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,s,n,o,i){return await(await this.sendRequest(e,s,n,o,"application/json",i)).json()}async sendFormData(e,s,n,o,i){return await(await this.sendRequest(e,s,n,o,"multipart/form-data",i)).json()}async sendUrlEncodedForm(e,s,n,o,i){let a=new URLSearchParams(o).toString();return await(await this.sendRequest(e,s,n,a,"application/x-www-form-urlencoded",i)).json()}};var ee="WHATSAPP",se=false,y=new a(ee,process.env.DEBUG==="true"||se),te="WA_SDK",l=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=z$1;constructor(e$1){this.config=b(e$1),this.requester=new m(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new f(this.config,this.requester),this.templates=new j(this.config,this.requester),this.phoneNumber=new g$1(this.config,this.requester),this.qrCode=new h(this.config,this.requester),this.encryption=new c(this.config,this.requester),this.twoStepVerification=new k(this.config,this.requester),this.registration=new i(this.config,this.requester),this.media=new e(this.config,this.requester),this.waba=new l$1(this.config,this.requester),this.flow=new d(this.config,this.requester),this.businessProfile=new b$1(this.config,this.requester),y.log("WhatsApp Node.js SDK instantiated!");}userAgent(){return `${te}/0.0.1 (Node.js ${process.version})`}updateTimeout(e){return this.config.REQUEST_TIMEOUT=e,y.log(`Updated request timeout to ${e}ms`),true}updatePhoneNumberId(e){return this.config.WA_PHONE_NUMBER_ID=e,y.log(`Updated sender phone number id to ${e}`),true}updateAccessToken(e){return this.config.CLOUD_API_ACCESS_TOKEN=e,y.log("Updated access token"),true}updateWabaId(e){return this.config.WA_BUSINESS_ACCOUNT_ID=e,y.log(`Updated business account id to ${e}`),true}};var re="WEBHOOK",oe=false,p=new a(re,process.env.DEBUG==="true"||oe),R=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(e){let s=b(e);this.config=s,this.client=new l(e),p.log("WebhookHandler instantiated!");}handleVerificationRequest(e,s){let n=e.query["hub.mode"],o=e.query["hub.verify_token"],i=e.query["hub.challenge"];n==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(p.log("Webhook verified successfully"),s.status(200).send(i)):(p.log("Webhook verification failed"),s.status(403).end());}async handleWebhookRequest(e,s){let n=e.body;if(n.object!=="whatsapp_business_account"){p.log("Received webhook for non-WhatsApp event"),s.status(404).end();return}for(let o of n.entry)try{let i=o.changes;for(let a of i)a.field==="messages"?await this.processMessages(a.value):await this.processEvent(a.field,a.value);}catch(i){p.log(`Error processing webhook: ${i}`);}s.status(200).end();}handleRequest(e,s){if(e.method==="GET")return this.handleVerificationRequest(e,s);if(e.method==="POST")return this.handleWebhookRequest(e,s);s.status(405).end();}async processMessages(e){let s=e.metadata,n=s.display_phone_number,o=s.phone_number_id,i=e.contacts[0].profile.name,a=e.messages;if(a&&a.length>0)for(let r of a){let d=r.type,t={id:r.id,from:r.from,timestamp:r.timestamp,type:r.type,phoneNumberId:o,displayPhoneNumber:n,profileName:i,originalData:r};switch(r.type){case "text":t.text=r.text;break;case "image":t.image=r.image;break;case "video":t.video=r.video;break;case "audio":t.audio=r.audio;break;case "document":t.document=r.document;break;case "sticker":t.sticker=r.sticker;break;case "location":t.location=r.location;break;case "contacts":t.contacts=r.contacts;break;case "interactive":t.interactive=r.interactive;break;case "button":t.button=r.button;break;case "order":t.order=r.order;break;case "system":t.system=r.system;break;}if(r.context&&(t.context=r.context),r.errors&&(t.errors=r.errors),this.preProcessHandler&&await Promise.resolve(this.preProcessHandler(this.client,t)),this.messageHandlers.has(d)){let c=this.messageHandlers.get(d);c&&await Promise.resolve(c(this.client,t));}if(this.messageHandlers.has("*")){let c=this.messageHandlers.get("*");c&&await Promise.resolve(c(this.client,t));}this.postProcessHandler&&await Promise.resolve(this.postProcessHandler(this.client,t));}e.statuses&&e.statuses.length>0&&await this.processEvent("statuses",e);}async processEvent(e,s){let n={field:e,value:s};if(this.eventHandlers.has(e)){let o=this.eventHandlers.get(e);o&&await Promise.resolve(o(n));}if(this.eventHandlers.has("*")){let o=this.eventHandlers.get("*");o&&await Promise.resolve(o(n));}}onMessage(e,s){this.messageHandlers.set(e,s),p.log(`Registered handler for message type: ${e}`);}onEvent(e,s){this.eventHandlers.set(e,s),p.log(`Registered handler for event field: ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,p.log("Registered pre-processing handler for all messages");}onMessagePostProcess(e){this.postProcessHandler=e,p.log("Registered post-processing handler for all messages");}async handleFlowRequest(e,s){if(!this.isRequestSignatureValid(e)){s.status(403).end();return}let n;try{n=this.decryptRequest(e.body);}catch(t){if(p.error(t),t instanceof Error){s.status(421).send(t.message);return}s.status(500).send("internal server error, please check with logs");return}let{decryptedBody:o,aesKeyBuffer:i,initialVectorBuffer:a}=n,r;if(f$1(o)?r="ping":d$1(o)?r="data_exchange":e$1(o)&&(r="error"),r&&this.flowHandlers.has(r)){let t=this.flowHandlers.get(r);if(t){let c=await Promise.resolve(t(this.client,o)),f=this.encryptResponse(c,i,a);s.status(200).send(f);return}}if(this.flowHandlers.has("*")){let t=this.flowHandlers.get("*");if(t){let c=await Promise.resolve(t(this.client,o)),f=this.encryptResponse(c,i,a);s.status(200).send(f);return}}p.log("No handler found, sending an empty response body: ",o);let d=this.encryptResponse({},i,a);s.status(200).send(d);}isRequestSignatureValid(e){let s=this.config.M4D_APP_SECRET;if(!s)return p.warn("App Secret is not set up. Please Add M4D_APP_SECRET or configuration"),false;let n=e.headers["x-hub-signature-256"];if(!n||typeof n!="string")return p.warn("x-hub-signature-256 header is missing"),false;let o=Buffer.from(n.replace("sha256=",""),"utf-8"),a=h$1.createHmac("sha256",s).update(e.rawBody).digest("hex"),r=Buffer.from(a,"utf-8");return h$1.timingSafeEqual(r,o)?true:(p.error("Error: Request Signature did not match"),false)}decryptRequest(e){p.log("Received body for decryption:",JSON.stringify(e,null,2));let{encrypted_aes_key:s,encrypted_flow_data:n,initial_vector:o}=e;if(!s)throw new Error("Missing required property: encrypted_aes_key");if(!n)throw new Error("Missing required property: encrypted_flow_data");if(!o)throw new Error("Missing required property: initial_vector");p.log("Received body for privatePem:",JSON.stringify(this.config.FLOW_API_PRIVATE_PEM,null,2)),p.log("Received body for passphrase:",JSON.stringify(this.config.FLOW_API_PASSPHRASE,null,2));let i=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
|
|
2
|
+
`),a=this.config.FLOW_API_PASSPHRASE,r=h$1.createPrivateKey({key:i,passphrase:a}),d=null;try{d=h$1.privateDecrypt({key:r,padding:h$1.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(s,"base64"));}catch($){throw p.error($),new Error("Failed to decrypt the request. Please verify your private key.")}let t=Buffer.from(n,"base64"),c=Buffer.from(o,"base64"),L=t.subarray(0,-16),D=t.subarray(-16),P=h$1.createDecipheriv("aes-128-gcm",d,c);P.setAuthTag(D);let F=Buffer.concat([P.update(L),P.final()]).toString("utf-8");return {decryptedBody:JSON.parse(F),aesKeyBuffer:d,initialVectorBuffer:c}}encryptResponse(e,s,n){let o=[];for(let i of Array.from(n.entries()))o.push(~i[1]);try{let i=h$1.createCipheriv("aes-128-gcm",s,Buffer.from(o));return Buffer.concat([i.update(JSON.stringify(e||{}),"utf-8"),i.final(),i.getAuthTag()]).toString("base64")}catch(i){throw p.error("Response encryption error:",i),new Error("Failed to encrypt response. Internal server error.")}}onFlow(e,s){this.flowHandlers.set(e,s),p.log(`Registered handler for Flow type: ${e}`);}};var hs=l;export{R as WebhookHandler,hs as default};//# sourceMappingURL=index.js.map
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/httpsClient.ts","../src/request.ts","../src/whatsapp.ts","../src/webhook.ts","../src/index.ts"],"names":["LIB_NAME","LOG_LOCAL","LOGGER","Logger","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","contentType","additionalHeaders","endpoint","effectiveContentType","errorData","isMetaError","formData","urlEncodedBody","headerPrefix","WhatsApp","enums_exports","config","importConfig","MessagesApi","TemplateApi","PhoneNumberApi","QrCodeAPI","EncryptionAPI","TwoStepVerificationAPI","RegistrationAPI","MediaAPI","WabaAPI","FlowAPI","BusinessProfileAPI","ms","wabaId","WebhookHandler","configuration","req","res","mode","token","challenge","entry","changes","change","value","metadata","displayPhoneNumber","profileName","messages","message","messageType","processedMessage","handler","field","event","type","flowRequestData","decryptedBody","aesKeyBuffer","initialVectorBuffer","flowType","isFlowPingRequest","isFlowDataExchangeRequest","isFlowErrorRequest","encryptedResponse","appSecret","signatureHeader","signatureBuffer","digestString","crypto","digestBuffer","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","flipped_iv","pair","cipher","src_default"],"mappings":"u4CAMA,IAAMA,CAAW,CAAA,aAAA,CACXC,CAAY,CAAA,KAAA,CACZC,EAAS,IAAIC,CAAAA,CAAOH,EAAU,OAAQ,CAAA,GAAA,CAAI,QAAU,MAAUC,EAAAA,CAAS,CAExDG,CAAAA,CAAAA,CAArB,KAA6D,CACzD,MAEA,WAAc,EAAA,CACV,KAAK,KAAQ,CAAA,IAAIC,MAAM,CAAE,SAAA,CAAW,IAAK,CAAC,EAC9C,CAEA,cAAwB,CACpB,OAAA,IAAA,CAAK,MAAM,OAAQ,EAAA,CACZ,IACX,CAEA,MAAM,WACFC,CAAAA,CAAAA,CACAC,CACAC,CAAAA,CAAAA,CACAC,EACAC,CACAC,CAAAA,CAAAA,CACiC,CACjC,IAAMC,CAAAA,CAAM,WAAWN,CAAQ,CAAA,CAAA,EAAIC,CAAI,CAAA,CAAA,CACjCM,CAAa,CAAA,IAAI,gBACjBC,CAAY,CAAA,UAAA,CAAW,IAAMD,CAAW,CAAA,KAAA,GAASH,CAAO,CAAA,CAE9D,GAAI,CACA,IAAMK,CAAAA,CAAW,MAAM,KAAMH,CAAAA,CAAAA,CAAK,CAC9B,MAAAJ,CAAAA,CAAAA,CACA,QAAAC,CACA,CAAA,IAAA,CAAAE,CACA,CAAA,MAAA,CAAQE,CAAW,CAAA,MACvB,CAAC,CACD,CAAA,OAAAX,EAAO,GAAI,CAAA,CAAA,EAAGM,CAAM,CAAMI,GAAAA,EAAAA,CAAG,CAAM,GAAA,EAAA,IAAA,CAAK,SAAUG,CAAAA,CAAQ,CAAC,CAAE,CAAA,CAAA,CAE7D,aAAaD,CAAS,CAAA,CACf,IAAIE,CAAoBD,CAAAA,CAAQ,CAC3C,CAAA,MAASE,CAAO,CAAA,CACZ,MAAMA,CACV,CACJ,CACJ,CAEaD,CAAAA,CAAAA,CAAN,KAA8D,CACjE,GAAA,CACA,cACA,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,CAAAA,CAAAA,CAAW,IAAK,CAAA,CAACC,CAAK,CAAA,CAAC,CAAC,CAG5B,CAAA,GAAI,CAEA,IAAMC,CAAShB,CAAAA,GAAAA,CAAO,eAAe,aAAeX,CAAAA,CAAAA,CAAc,MAAO,CAAA,IAAA,CAAKyB,CAAU,CAAC,EACzF,OAAO,MAAA,CAAO,MAAO,CAAA,CACjBE,CAAO,CAAA,MAAA,CAAO,KAAK,SAAUxF,CAAAA,CAAAA,EAAY,EAAE,CAAA,CAAG,OAAO,CACrDwF,CAAAA,CAAAA,CAAO,KAAM,EAAA,CACbA,CAAO,CAAA,UAAA,EACX,CAAC,CAAA,CAAE,QAAS,CAAA,QAAQ,CACxB,CAAA,MAAStF,EAAO,CACZ,MAAAf,CAAO,CAAA,KAAA,CAAM,4BAA8Be,CAAAA,CAAK,EAC1C,IAAI,KAAA,CAAM,oDAAoD,CACxE,CACJ,CAOO,OACHwD,CACAH,CAAAA,CAAAA,CACI,CACJ,IAAA,CAAK,YAAa,CAAA,GAAA,CAAIG,EAAMH,CAAO,CAAA,CACnCpE,CAAO,CAAA,GAAA,CAAI,CAAqCuE,kCAAAA,EAAAA,CAAI,EAAE,EAC1D,CACJ,ECzeA,IAAO+B,EAAQrE,CAAAA","file":"index.js","sourcesContent":["import { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { WabaConfigType } from './types/config';\nimport * as SDKEnums from './types/enums';\nimport Logger from './utils/logger';\n\nimport {\n BusinessProfileAPI,\n EncryptionAPI,\n FlowAPI,\n MediaAPI,\n MessagesAPI,\n PhoneNumberAPI,\n QrCodeAPI,\n RegistrationAPI,\n TemplateAPI,\n TwoStepVerificationAPI,\n WabaAPI,\n} from './api';\nimport Requester from './request';\nimport { WhatsAppClass, WhatsAppConfig } from './types/whatsapp';\nimport { importConfig } from './utils/importConfig';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nconst headerPrefix = 'WA_SDK';\n\nexport default class WhatsApp implements WhatsAppClass {\n config: WabaConfigType;\n\n requester: Readonly<Requester>;\n\n readonly messages: MessagesAPI;\n readonly templates: TemplateAPI;\n readonly phoneNumber: PhoneNumberAPI;\n readonly qrCode: QrCodeAPI;\n readonly encryption: EncryptionAPI;\n readonly twoStepVerification: TwoStepVerificationAPI;\n readonly registration: RegistrationAPI;\n readonly media: MediaAPI;\n readonly waba: WabaAPI;\n readonly flow: FlowAPI;\n readonly businessProfile: BusinessProfileAPI;\n static readonly Enums = SDKEnums;\n\n constructor(config?: WhatsAppConfig) {\n this.config = importConfig(config);\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.userAgent(),\n );\n\n this.messages = new MessagesAPI(this.config, this.requester);\n this.templates = new TemplateAPI(this.config, this.requester);\n this.phoneNumber = new PhoneNumberAPI(this.config, this.requester);\n this.qrCode = new QrCodeAPI(this.config, this.requester);\n this.encryption = new EncryptionAPI(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationAPI(this.config, this.requester);\n this.registration = new RegistrationAPI(this.config, this.requester);\n this.media = new MediaAPI(this.config, this.requester);\n this.waba = new WabaAPI(this.config, this.requester);\n this.flow = new FlowAPI(this.config, this.requester);\n this.businessProfile = new BusinessProfileAPI(this.config, this.requester);\n LOGGER.log('WhatsApp Node.js SDK instantiated!');\n }\n\n private userAgent(): string {\n const userAgentString = `${headerPrefix}/${'0.0.1'} (Node.js ${process.version})`;\n return userAgentString;\n }\n\n updateTimeout(ms: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = ms;\n LOGGER.log(`Updated request timeout to ${ms}ms`);\n return true;\n }\n\n updatePhoneNumberId(phoneNumberId: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Updated sender phone number id to ${phoneNumberId}`);\n return true;\n }\n\n updateAccessToken(accessToken: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n LOGGER.log(`Updated access token`);\n return true;\n }\n\n updateWabaId(wabaId: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId] = wabaId;\n LOGGER.log(`Updated business account id to ${wabaId}`);\n return true;\n }\n}\n","import { IncomingMessage } from 'http';\nimport { FlowEndpointRequest, FlowTypeEnum, MessageTypesEnum, WhatsAppConfig } from './types';\nimport { WabaConfigType } from './types/config';\n\nimport crypto from 'crypto';\nimport { EventField, WebhookEvent, WebhookMessage } from './types/webhook';\nimport { importConfig } from './utils';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from './utils/flowTypeGuards';\nimport Logger from './utils/logger';\nimport WhatsApp from './whatsapp';\nconst LIB_NAME = 'WEBHOOK';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport interface IRequest extends IncomingMessage {\n body: any;\n query: Record<string, any>;\n method?: string;\n}\nexport interface IResponse {\n status: (code: number) => IResponse;\n send: (body: any) => IResponse | void;\n json: (body: any) => IResponse | void;\n end: () => void;\n}\n\n/**\n * Webhook handler for WhatsApp Cloud API\n */\nexport default class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<\n MessageTypesEnum,\n (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>\n > = new Map();\n private eventHandlers: Map<string, (event: WebhookEvent) => void | Promise<void>> = new Map();\n private preProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private postProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private flowHandlers: Map<FlowTypeEnum, (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>> =\n new Map();\n\n /**\n * Create a new WebhookHandler\n * @param config The WhatsApp configuration\n */\n constructor(config: WhatsAppConfig) {\n const configuration = importConfig(config);\n this.config = configuration;\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle a GET request for webhook verification\n */\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void {\n const mode = req.query['hub.mode'];\n const token = req.query['hub.verify_token'];\n const challenge = req.query['hub.challenge'];\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n LOGGER.log('Webhook verified successfully');\n res.status(200).send(challenge);\n } else {\n LOGGER.log('Webhook verification failed');\n res.status(403).end();\n }\n }\n\n /**\n * Handle a POST request for webhook events\n */\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void> {\n const body = req.body;\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n LOGGER.log('Received webhook for non-WhatsApp event');\n res.status(404).end();\n return;\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === EventField.MESSAGES) {\n await this.processMessages(change.value);\n } else {\n // Handle other event types\n await this.processEvent(change.field, change.value);\n }\n }\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n }\n }\n\n // Always respond with 200 to acknowledge receipt\n res.status(200).end();\n }\n\n /**\n * Handle webhook requests (both verification and events)\n */\n public handleRequest(req: IRequest, res: IResponse): void | Promise<void> {\n if (req.method === 'GET') {\n return this.handleVerificationRequest(req, res);\n } else if (req.method === 'POST') {\n return this.handleWebhookRequest(req, res);\n } else {\n res.status(405).end(); // Method not allowed\n }\n }\n\n /**\n * Process incoming messages\n */\n private async processMessages(value: any): Promise<void> {\n // Extract metadata\n const metadata = value.metadata;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n const profileName = value.contacts[0].profile.name;\n const messages = value.messages as WebhookMessage[];\n\n // Process messages if present\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n // Create the base message object\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n // Add type-specific data based on the message type\n switch (message.type) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n default:\n // Unknown message type\n break;\n }\n\n // Add context if available\n if (message.context) {\n processedMessage.context = message.context;\n }\n\n // Add errors if available\n if (message.errors) {\n processedMessage.errors = message.errors;\n }\n\n // 1. Execute pre-processing handler if exists\n if (this.preProcessHandler) {\n await Promise.resolve(this.preProcessHandler(this.client, processedMessage));\n }\n\n // 2. Dispatch to appropriate message handler\n if (this.messageHandlers.has(messageType)) {\n const handler = this.messageHandlers.get(messageType);\n if (handler) {\n await Promise.resolve(handler(this.client, processedMessage));\n }\n }\n\n // Also dispatch to general message handler if exists\n if (this.messageHandlers.has(MessageTypesEnum['*'])) {\n const handler = this.messageHandlers.get(MessageTypesEnum['*']);\n if (handler) {\n await Promise.resolve(handler(this.client, processedMessage));\n }\n }\n\n // 3. Execute post-processing handler if exists\n if (this.postProcessHandler) {\n await Promise.resolve(this.postProcessHandler(this.client, processedMessage));\n }\n }\n }\n\n if (value.statuses && value.statuses.length > 0) {\n await this.processEvent(EventField.STATUSES, value);\n }\n }\n\n private async processEvent(field: string, value: any): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n };\n\n if (this.eventHandlers.has(field)) {\n const handler = this.eventHandlers.get(field);\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n\n if (this.eventHandlers.has('*')) {\n const handler = this.eventHandlers.get('*');\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n }\n\n /**\n * Register a message handler for a specific message type\n * @param type Message type to handle, or '*' for all types\n * @param handler The handler function\n */\n public onMessage(\n type: MessageTypesEnum,\n handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>,\n ): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered handler for message type: ${type}`);\n }\n\n /**\n * Register a general event handler\n * @param field Event field to handle, or '*' for all fields\n * @param handler The handler function\n */\n public onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered handler for event field: ${field}`);\n }\n\n /**\n * Register a pre-processing handler for all messages\n * @param handler The handler function\n */\n public onMessagePreProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-processing handler for all messages');\n }\n\n /**\n * Register a post-processing handler for all messages\n * @param handler The handler function\n */\n public onMessagePostProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-processing handler for all messages');\n }\n\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }, Res extends IResponse>(\n req: Req,\n res: Res,\n ): Promise<void> {\n if (!this.isRequestSignatureValid(req)) {\n res.status(403).end();\n return;\n }\n\n let flowRequestData: {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n };\n\n try {\n flowRequestData = this.decryptRequest(req.body);\n } catch (error) {\n LOGGER.error(error);\n if (error instanceof Error) {\n res.status(421).send(error.message);\n return;\n }\n\n res.status(500).send('internal server error, please check with logs');\n return;\n }\n\n const { decryptedBody, aesKeyBuffer, initialVectorBuffer } = flowRequestData;\n\n // Determine flow type\n let flowType: FlowTypeEnum | undefined = undefined;\n\n if (isFlowPingRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Ping;\n } else if (isFlowDataExchangeRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Change;\n } else if (isFlowErrorRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Error;\n }\n\n // If we have a registered handler for this flow type, use it\n if (flowType && this.flowHandlers.has(flowType)) {\n const handler = this.flowHandlers.get(flowType);\n if (handler) {\n const response = await Promise.resolve(handler(this.client, decryptedBody));\n const encryptedResponse = this.encryptResponse(response, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n return;\n }\n }\n\n // If we have a catch-all handler, use it\n if (this.flowHandlers.has(FlowTypeEnum.All)) {\n const handler = this.flowHandlers.get(FlowTypeEnum.All);\n if (handler) {\n const response = await Promise.resolve(handler(this.client, decryptedBody));\n const encryptedResponse = this.encryptResponse(response, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n return;\n }\n }\n\n // No handler found, send an empty response\n // Add an empty response here for consistency\n LOGGER.log('No handler found, sending an empty response body: ', decryptedBody);\n const encryptedResponse = this.encryptResponse({}, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n }\n\n public isRequestSignatureValid(req: IRequest & { rawBody: string }): boolean {\n const appSecret = this.config.M4D_APP_SECRET;\n\n if (!appSecret) {\n LOGGER.warn('App Secret is not set up. Please Add M4D_APP_SECRET or configuration');\n return false;\n }\n\n const signatureHeader = req.headers['x-hub-signature-256'];\n\n if (!signatureHeader || typeof signatureHeader !== 'string') {\n LOGGER.warn('x-hub-signature-256 header is missing');\n return false;\n }\n\n const signatureBuffer = Buffer.from(signatureHeader.replace('sha256=', ''), 'utf-8');\n const hmac = crypto.createHmac('sha256', appSecret);\n\n const digestString = hmac.update(req.rawBody).digest('hex');\n const digestBuffer = Buffer.from(digestString, 'utf-8');\n\n // Note: This is corrected from the original code which had inverted logic\n if (!crypto.timingSafeEqual(digestBuffer, signatureBuffer)) {\n LOGGER.error('Error: Request Signature did not match');\n return false;\n }\n return true;\n }\n\n public decryptRequest(body: any): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n } {\n LOGGER.log('Received body for decryption:', JSON.stringify(body, null, 2));\n\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key) {\n throw new Error('Missing required property: encrypted_aes_key');\n }\n if (!encrypted_flow_data) {\n throw new Error('Missing required property: encrypted_flow_data');\n }\n if (!initial_vector) {\n throw new Error('Missing required property: initial_vector');\n }\n\n LOGGER.log('Received body for privatePem:', JSON.stringify(this.config.FLOW_API_PRIVATE_PEM, null, 2));\n LOGGER.log('Received body for passphrase:', JSON.stringify(this.config.FLOW_API_PASSPHRASE, null, 2));\n\n const privatePem = this.config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = this.config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey = null;\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n LOGGER.error(error);\n /*\n Failed to decrypt. Please verify your private key.\n If you change your public key. You need to return HTTP status code 421 to refresh the public key on the client\n */\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n // decrypt flow data\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([\n decipher.update(encrypted_flow_data_body),\n decipher.final(),\n ]).toString('utf-8');\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n }\n\n private encryptResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer) {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n // encrypt response data\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n }\n\n /**\n * Register a Flow action handler for a specific flow type\n * @param type The flow type to handle (ping, change, error), or '*' for all types\n * @param handler The handler function that receives the WhatsApp client and the Flow request\n */\n public onFlow(\n type: FlowTypeEnum,\n handler: (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>,\n ): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered handler for Flow type: ${type}`);\n }\n}\n","import WebhookHandler, { IRequest, IResponse } from './webhook';\nimport WhatsApp from './whatsapp';\n\nexport default WhatsApp;\nexport * from './types';\nexport * from './utils';\nexport { WebhookHandler, type IRequest, type IResponse };\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { H as HttpMethodsEnum, e as MessageTypesEnum } from '../waba-RRlZTQUG.
|
|
2
|
-
export { a$ as AccountMode, aA as AudioMediaObject, G as AudioMediaTypesEnum, aB as AudioMessageRequestBody, h as BaseClass, B as BusinessProfileClass, k as BusinessProfileData, i as BusinessProfileField, j as BusinessProfileFieldsParam, l as BusinessProfileResponse, Z as BusinessVerticalEnum, u as ButtonPositionEnum, t as ButtonTypesEnum, C as CategoryEnum, b0 as CodeVerificationStatus, bE as ComponentTypes, v as ComponentTypesEnum, aC as ContactObject, aD as ContactsMessageRequestBody, x as ConversationTypesEnum, bu as CopyCodeButton, ad as CreateFlowResponse, bg as CreateQrCodeRequest, X as CurrencyCodesEnum, b9 as Cursors, Y as DataLocalizationRegionEnum, aE as DocumentMediaObject, D as DocumentMediaTypesEnum, aF as DocumentMessageRequestBody, E as EncryptionClass, q as EncryptionPublicKeyResponse, a3 as Flow, a0 as FlowActionEnum, a7 as FlowAsset, a8 as FlowAssetsResponse, bv as FlowButton, $ as FlowCategoryEnum, F as FlowClass, am as FlowDataExchangeRequest, an as FlowDataExchangeResponse, ai as FlowDecryptedRequestResponse, ah as FlowEncryptedRequestPayload, f as FlowEndpointRequest, ar as FlowEndpointResponse, ap as FlowErrorNotificationRequest, aq as FlowErrorNotificationResponse, ak as FlowHealthCheckRequest, al as FlowHealthCheckResponse, aj as FlowHttpRequest, ac as FlowMigrationFailure, af as FlowMigrationResponse, ab as FlowMigrationResult, a9 as FlowPreview, aa as FlowPreviewResponse, _ as FlowStatusEnum, ao as FlowSuccessScreenResponse, g as FlowTypeEnum, a2 as FlowValidationError, a1 as FlowValidationErrorPointer, a6 as FlowsListResponse, bk as GeneralHeaderInterface, av as GeneralMessageBody, bj as GeneralRequestBody, b5 as HealthStatus, b4 as HealthStatusEntity, aG as ImageMediaObject, A as ImageMediaTypesEnum, aH as ImageMessageRequestBody, aJ as InteractiveMessageRequestBody, aI as InteractiveObject, I as InteractiveTypesEnum, O as LanguagesEnum, aU as LocationMessageRequestBody, aT as LocationObject, bw as MPMButton, b as MediaClass, as as MediaResponse, at as MediasResponse, az as MessageRequestBody, aW as MessageRequestParams, aR as MessageTemplateObject, aS as MessageTemplateRequestBody, M as MessagesClass, aV as MessagesResponse, b1 as MessagingLimitTier, bx as OTPButton, a5 as Pagination, a4 as PaginationCursors, bp as Paging, s as ParametersTypesEnum, br as PhoneNumberButton, P as PhoneNumberClass, b8 as PhoneNumberResponse, ba as PhoneNumbersResponse, b2 as PlatformType, Q as QrCodeClass, be as QrCodeResponse, bf as QrCodesResponse, a_ as QualityRating, b6 as QualityScore, bt as QuickReplyButton, aM as ReactionMessageRequestBody, aY as ReactionParams, L as ReferralSourceTypesEnum, R as RegistrationClass, bi as RegistrationRequest, N as RequestCodeMethodsEnum, bb as RequestVerificationCodeRequest, c as RequesterClass, bl as RequesterResponseInterface, bn as ResponseData, bo as ResponsePagination, bm as ResponseSuccess, by as SPMButton, y as StatusEnum, aw as StatusObject, aZ as StatusParams, ay as StatusRequestBody, aK as StickerMediaObject, z as StickerMediaTypesEnum, aL as StickerMessageRequestBody, K as SystemChangeTypesEnum, bC as TemplateBody, bz as TemplateButton, T as TemplateClass, bI as TemplateDeleteParams, bD as TemplateFooter, bq as TemplateFormat, bH as TemplateGetParams, bB as TemplateHeader, bA as TemplateHeaderExample, bF as TemplateRequestBody, bG as TemplateResponse, r as TemplateStatusEnum, aX as TextMessageParams, aO as TextMessageRequestBody, aN as TextObject, b7 as Throughput, b3 as ThroughputLevel, a as TwoStepVerificationClass, bd as TwoStepVerificationParams, bJ as TwoStepVerificationRequest, ax as TypingIndicatorObject, bs as URLButton, U as UpdateBusinessProfileRequest, ae as UpdateFlowResponse, bh as UpdateQrCodeRequest, bL as UpdateWabaSubscription, o as UploadBusinessProfileResponse, p as UploadHandle, au as UploadMediaResponse, m as UploadSession, n as UploadSessionResponse, ag as ValidateFlowJsonResponse, bc as VerifyCodeRequest, aP as VideoMediaObject, V as VideoMediaTypesEnum, aQ as VideoMessageRequestBody, W as WABAClass, bU as WabaAccount, bV as WabaAccountFields, bW as WabaAccountFieldsParam, bN as WabaAccountReviewStatus, bP as WabaAccountStatus, bQ as WabaBusinessVerificationStatus, w as WabaConfigEnum, d as WabaConfigType, bT as WabaHealthStatus, bO as WabaHealthStatusCanSendMessage, bS as WabaHealthStatusEntity, bR as WabaHealthStatusError, bK as WabaSubscription, bM as WabaSubscriptions, J as WebhookTypesEnum } from '../waba-RRlZTQUG.
|
|
3
|
-
export { W as WhatsAppClass, a as WhatsAppConfig } from '../whatsapp-
|
|
1
|
+
import { H as HttpMethodsEnum, e as MessageTypesEnum } from '../waba-RRlZTQUG.js';
|
|
2
|
+
export { a$ as AccountMode, aA as AudioMediaObject, G as AudioMediaTypesEnum, aB as AudioMessageRequestBody, h as BaseClass, B as BusinessProfileClass, k as BusinessProfileData, i as BusinessProfileField, j as BusinessProfileFieldsParam, l as BusinessProfileResponse, Z as BusinessVerticalEnum, u as ButtonPositionEnum, t as ButtonTypesEnum, C as CategoryEnum, b0 as CodeVerificationStatus, bE as ComponentTypes, v as ComponentTypesEnum, aC as ContactObject, aD as ContactsMessageRequestBody, x as ConversationTypesEnum, bu as CopyCodeButton, ad as CreateFlowResponse, bg as CreateQrCodeRequest, X as CurrencyCodesEnum, b9 as Cursors, Y as DataLocalizationRegionEnum, aE as DocumentMediaObject, D as DocumentMediaTypesEnum, aF as DocumentMessageRequestBody, E as EncryptionClass, q as EncryptionPublicKeyResponse, a3 as Flow, a0 as FlowActionEnum, a7 as FlowAsset, a8 as FlowAssetsResponse, bv as FlowButton, $ as FlowCategoryEnum, F as FlowClass, am as FlowDataExchangeRequest, an as FlowDataExchangeResponse, ai as FlowDecryptedRequestResponse, ah as FlowEncryptedRequestPayload, f as FlowEndpointRequest, ar as FlowEndpointResponse, ap as FlowErrorNotificationRequest, aq as FlowErrorNotificationResponse, ak as FlowHealthCheckRequest, al as FlowHealthCheckResponse, aj as FlowHttpRequest, ac as FlowMigrationFailure, af as FlowMigrationResponse, ab as FlowMigrationResult, a9 as FlowPreview, aa as FlowPreviewResponse, _ as FlowStatusEnum, ao as FlowSuccessScreenResponse, g as FlowTypeEnum, a2 as FlowValidationError, a1 as FlowValidationErrorPointer, a6 as FlowsListResponse, bk as GeneralHeaderInterface, av as GeneralMessageBody, bj as GeneralRequestBody, b5 as HealthStatus, b4 as HealthStatusEntity, aG as ImageMediaObject, A as ImageMediaTypesEnum, aH as ImageMessageRequestBody, aJ as InteractiveMessageRequestBody, aI as InteractiveObject, I as InteractiveTypesEnum, O as LanguagesEnum, aU as LocationMessageRequestBody, aT as LocationObject, bw as MPMButton, b as MediaClass, as as MediaResponse, at as MediasResponse, az as MessageRequestBody, aW as MessageRequestParams, aR as MessageTemplateObject, aS as MessageTemplateRequestBody, M as MessagesClass, aV as MessagesResponse, b1 as MessagingLimitTier, bx as OTPButton, a5 as Pagination, a4 as PaginationCursors, bp as Paging, s as ParametersTypesEnum, br as PhoneNumberButton, P as PhoneNumberClass, b8 as PhoneNumberResponse, ba as PhoneNumbersResponse, b2 as PlatformType, Q as QrCodeClass, be as QrCodeResponse, bf as QrCodesResponse, a_ as QualityRating, b6 as QualityScore, bt as QuickReplyButton, aM as ReactionMessageRequestBody, aY as ReactionParams, L as ReferralSourceTypesEnum, R as RegistrationClass, bi as RegistrationRequest, N as RequestCodeMethodsEnum, bb as RequestVerificationCodeRequest, c as RequesterClass, bl as RequesterResponseInterface, bn as ResponseData, bo as ResponsePagination, bm as ResponseSuccess, by as SPMButton, y as StatusEnum, aw as StatusObject, aZ as StatusParams, ay as StatusRequestBody, aK as StickerMediaObject, z as StickerMediaTypesEnum, aL as StickerMessageRequestBody, K as SystemChangeTypesEnum, bC as TemplateBody, bz as TemplateButton, T as TemplateClass, bI as TemplateDeleteParams, bD as TemplateFooter, bq as TemplateFormat, bH as TemplateGetParams, bB as TemplateHeader, bA as TemplateHeaderExample, bF as TemplateRequestBody, bG as TemplateResponse, r as TemplateStatusEnum, aX as TextMessageParams, aO as TextMessageRequestBody, aN as TextObject, b7 as Throughput, b3 as ThroughputLevel, a as TwoStepVerificationClass, bd as TwoStepVerificationParams, bJ as TwoStepVerificationRequest, ax as TypingIndicatorObject, bs as URLButton, U as UpdateBusinessProfileRequest, ae as UpdateFlowResponse, bh as UpdateQrCodeRequest, bL as UpdateWabaSubscription, o as UploadBusinessProfileResponse, p as UploadHandle, au as UploadMediaResponse, m as UploadSession, n as UploadSessionResponse, ag as ValidateFlowJsonResponse, bc as VerifyCodeRequest, aP as VideoMediaObject, V as VideoMediaTypesEnum, aQ as VideoMessageRequestBody, W as WABAClass, bU as WabaAccount, bV as WabaAccountFields, bW as WabaAccountFieldsParam, bN as WabaAccountReviewStatus, bP as WabaAccountStatus, bQ as WabaBusinessVerificationStatus, w as WabaConfigEnum, d as WabaConfigType, bT as WabaHealthStatus, bO as WabaHealthStatusCanSendMessage, bS as WabaHealthStatusEntity, bR as WabaHealthStatusError, bK as WabaSubscription, bM as WabaSubscriptions, J as WebhookTypesEnum } from '../waba-RRlZTQUG.js';
|
|
3
|
+
export { W as WhatsAppClass, a as WhatsAppConfig } from '../whatsapp-DmeO83A8.js';
|
|
4
4
|
import 'http';
|
|
5
5
|
|
|
6
6
|
type ResponseHeaderValue = string | string[] | undefined;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{j as EventField,c as FlowActionEnum,b as FlowCategoryEnum,a as FlowStatusEnum,d as FlowTypeEnum,i as MessageStatus,e as WabaAccountReviewStatus,g as WabaAccountStatus,h as WabaBusinessVerificationStatus,f as WabaHealthStatusCanSendMessage}from'../chunk-KW56EPP7.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,h as ButtonPositionEnum,g as ButtonTypesEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'../chunk-IE2YYEC7.js';//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as WhatsAppConfig } from '../whatsapp-
|
|
2
|
-
import { d as WabaConfigType, f as FlowEndpointRequest, am as FlowDataExchangeRequest, a0 as FlowActionEnum, ap as FlowErrorNotificationRequest, ak as FlowHealthCheckRequest } from '../waba-RRlZTQUG.
|
|
1
|
+
import { a as WhatsAppConfig } from '../whatsapp-DmeO83A8.js';
|
|
2
|
+
import { d as WabaConfigType, f as FlowEndpointRequest, am as FlowDataExchangeRequest, a0 as FlowActionEnum, ap as FlowErrorNotificationRequest, ak as FlowHealthCheckRequest } from '../waba-RRlZTQUG.js';
|
|
3
3
|
import 'http';
|
|
4
4
|
|
|
5
5
|
declare const generateXHub256Sig: (body: string, appSecret: string) => string;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{a as generateXHub256Sig,b as importConfig,d as isFlowDataExchangeRequest,e as isFlowErrorRequest,f as isFlowPingRequest,c as isMetaError}from'../chunk-SLDCD6XR.js';export{b as objectToQueryString}from'../chunk-UVPYV4PL.js';import'../chunk-KW56EPP7.js';import'../chunk-IE2YYEC7.js';//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as MessagesClass, T as TemplateClass, P as PhoneNumberClass, Q as QrCodeClass, E as EncryptionClass, a as TwoStepVerificationClass, R as RegistrationClass, b as MediaClass, W as WABAClass, F as FlowClass, B as BusinessProfileClass } from './waba-RRlZTQUG.
|
|
1
|
+
import { M as MessagesClass, T as TemplateClass, P as PhoneNumberClass, Q as QrCodeClass, E as EncryptionClass, a as TwoStepVerificationClass, R as RegistrationClass, b as MediaClass, W as WABAClass, F as FlowClass, B as BusinessProfileClass } from './waba-RRlZTQUG.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/flow.ts","../src/types/waba.ts","../src/types/webhook.ts"],"names":["FlowStatusEnum","FlowCategoryEnum","FlowActionEnum","FlowTypeEnum","WabaAccountReviewStatus","WabaHealthStatusCanSendMessage","WabaAccountStatus","WabaBusinessVerificationStatus","MessageStatus","EventField"],"mappings":"AAMO,IAAKA,OACRA,CAAA,CAAA,KAAA,CAAQ,OACRA,CAAAA,CAAAA,CAAA,UAAY,WACZA,CAAAA,CAAAA,CAAA,SAAY,CAAA,WAAA,CACZA,EAAA,OAAU,CAAA,SAAA,CACVA,CAAA,CAAA,UAAA,CAAa,aALLA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAWAC,CACRA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,OAAS,SACTA,CAAAA,CAAAA,CAAA,MAAS,CAAA,SAAA,CACTA,EAAA,kBAAqB,CAAA,qBAAA,CACrBA,CAAA,CAAA,cAAA,CAAiB,kBACjBA,CAAA,CAAA,SAAA,CAAY,aACZA,CAAA,CAAA,eAAA,CAAkB,mBAClBA,CAAA,CAAA,MAAA,CAAS,QACTA,CAAAA,CAAAA,CAAA,MAAQ,OARAA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAWAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,EAAA,IAAO,CAAA,MAAA,CACPA,CAAA,CAAA,IAAA,CAAO,OACPA,CAAA,CAAA,aAAA,CAAgB,gBAHRA,CAAA,CAAA,EAAA,CAAA,EAAA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AAA,CAAA,QAAW,CAAA,UAAA,CACXA,EAAA,8BAAiC,CAAA,gCAAA,CACjCA,CAAA,CAAA,2BAAA,CAA8B,8BAC9BA,CAAA,CAAA,wBAAA,CAA2B,2BAC3BA,CAAA,CAAA,OAAA,CAAU,UANFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA","file":"chunk-KZQQJAPX.mjs","sourcesContent":["import { IncomingHttpHeaders, IncomingMessage } from 'http';\nimport { ResponseSuccess } from './request';\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\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 asset_type: 'FLOW_JSON';\n file: Blob;\n name: string;\n },\n ): Promise<UpdateFlowResponse>;\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse>;\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n publishFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deprecateFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Migrate Flows\n *\n * @param wabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results\n */\n migrateFlows(\n wabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<FlowMigrationResponse>;\n}\n","import type { ResponseSuccess } from './request';\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\nexport interface UpdateWabaSubscription {\n override_callback_uri: string;\n verify_token: string;\n}\n\nexport interface WabaSubscriptions {\n data: Array<WabaSubscription>;\n}\n\nexport interface WABAClass {\n getWabaAccount(fields?: WabaAccountFieldsParam): Promise<WabaAccount>;\n getAllWabaSubscriptions(): Promise<WabaSubscriptions>;\n updateWabaSubscription(params: UpdateWabaSubscription): Promise<ResponseSuccess>;\n unsubscribeFromWaba(): Promise<ResponseSuccess>;\n}\n\nexport enum WabaAccountReviewStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\nexport enum WabaHealthStatusCanSendMessage {\n Blocked = 'BLOCKED',\n Limited = 'LIMITED',\n Available = 'AVAILABLE',\n}\n\nexport enum WabaAccountStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\nexport enum WabaBusinessVerificationStatus {\n Verified = 'verified',\n PendingSubmission = 'pending_submission',\n Unverified = 'unverified',\n Rejected = 'rejected',\n}\n\nexport interface WabaHealthStatusError {\n error_code?: number;\n error_description?: string;\n possible_solution?: string;\n}\n\nexport interface WabaHealthStatusEntity {\n entity_type?: string;\n id?: string;\n can_send_message?: string;\n errors?: WabaHealthStatusError[];\n}\n\nexport interface WabaHealthStatus {\n can_send_message?: WabaHealthStatusCanSendMessage;\n entities?: WabaHealthStatusEntity[];\n}\n\nexport interface WabaAccount {\n account_review_status?: WabaAccountReviewStatus;\n id?: string;\n health_status?: WabaHealthStatus;\n status?: WabaAccountStatus;\n business_verification_status?: WabaBusinessVerificationStatus;\n message_template_namespace?: string;\n name?: string;\n ownership_type?: string;\n currency?: string;\n}\n\nexport type WabaAccountFields =\n | 'id'\n | 'name'\n | 'account_review_status'\n | 'auth_international_rate_eligibility'\n | 'business_verification_status'\n | 'country'\n | 'currency'\n | 'health_status'\n | 'status'\n | 'ownership_type'\n | 'message_template_namespace';\n\nexport type WabaAccountFieldsParam = WabaAccountFields[];\n","import { MessageTypesEnum } from './enums';\n\nexport interface WebhookContact {\n /**\n * WhatsApp ID of the contact. Business can respond to this contact using this ID.\n */\n wa_id: string;\n /**\n * Additional unique, alphanumeric identifier for a WhatsApp user\n */\n user_id?: string;\n /**\n * Profile of Whatsapp user\n */\n profile: {\n /**\n * The display name of the contact\n */\n name: string;\n };\n}\n\n/**\n * Represents a message received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object\n */\nexport interface WebhookMessage {\n /**\n * The message ID\n */\n id: string;\n\n /**\n * The sender's phone number\n */\n from: string;\n\n /**\n * The timestamp of the message\n */\n timestamp: string;\n\n /**\n * The type of message (text, image, etc.)\n */\n type: MessageTypesEnum;\n\n /**\n * The phone number ID that received the message\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the message\n */\n displayPhoneNumber: string;\n\n /**\n * The profile name of the sender\n */\n profileName: string;\n\n /**\n * Text object for text messages\n */\n text?: {\n /**\n * The text content of the message\n */\n body: string;\n };\n\n /**\n * Image object for image messages\n */\n image?: {\n /**\n * The image caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the image\n */\n sha256?: string;\n /**\n * The ID for the image\n */\n id: string;\n /**\n * The MIME type of the image\n */\n mime_type: string;\n };\n\n /**\n * Video object for video messages\n */\n video?: {\n /**\n * The video caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the video\n */\n sha256?: string;\n /**\n * The ID for the video\n */\n id: string;\n /**\n * The MIME type of the video\n */\n mime_type: string;\n };\n\n /**\n * Audio object for audio messages\n */\n audio?: {\n /**\n * The ID for the audio file\n */\n id: string;\n /**\n * The MIME type of the audio file\n */\n mime_type: string;\n /**\n * Whether the audio is a voice message\n */\n voice?: boolean;\n };\n\n /**\n * Document object for document messages\n */\n document?: {\n /**\n * The document caption (if provided)\n */\n caption?: string;\n /**\n * The document filename\n */\n filename: string;\n /**\n * The SHA256 hash of the document\n */\n sha256?: string;\n /**\n * The ID for the document\n */\n id: string;\n /**\n * The MIME type of the document\n */\n mime_type: string;\n };\n\n /**\n * Sticker object for sticker messages\n */\n sticker?: {\n /**\n * The ID for the sticker\n */\n id: string;\n /**\n * Whether this is an animated sticker\n */\n animated: boolean;\n /**\n * The MIME type of the sticker\n */\n mime_type: string;\n };\n\n /**\n * Reaction object for reaction messages\n */\n reaction?: {\n /**\n * The ID of the message being reacted to\n */\n message_id: string;\n /**\n * Emoji used for the reaction\n */\n emoji: string;\n };\n\n /**\n * Contacts object for contact messages\n */\n contacts?: Array<{\n /**\n * The contact's name\n */\n name: {\n formatted_name: string;\n first_name?: string;\n last_name?: string;\n middle_name?: string;\n suffix?: string;\n prefix?: string;\n };\n /**\n * The contact's phone numbers\n */\n phones?: Array<{\n phone: string;\n type?: string;\n wa_id?: string;\n }>;\n /**\n * The contact's emails\n */\n emails?: Array<{\n email: string;\n type?: string;\n }>;\n /**\n * The contact's addresses\n */\n addresses?: Array<{\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n country?: string;\n country_code?: string;\n type?: string;\n }>;\n /**\n * The contact's organizations\n */\n org?: {\n company?: string;\n department?: string;\n title?: string;\n };\n /**\n * The contact's URLs\n */\n urls?: Array<{\n url: string;\n type?: string;\n }>;\n /**\n * The contact's birthday (YYYY-MM-DD format)\n */\n birthday?: string;\n }>;\n\n /**\n * Location object for location messages\n */\n location?: {\n /**\n * Latitude of the location\n */\n latitude: number;\n /**\n * Longitude of the location\n */\n longitude: number;\n /**\n * Name of the location\n */\n name?: string;\n /**\n * Address of the location\n */\n address?: string;\n };\n\n /**\n * Interactive object for interactive messages\n */\n interactive?: {\n /**\n * Type of the interactive message\n * Can be: button_reply, list_reply, flow, nfm_reply, etc.\n */\n type: string;\n /**\n * ID for the button that was clicked\n */\n button_reply?: {\n id: string;\n title: string;\n };\n /**\n * ID for the list item that was selected\n */\n list_reply?: {\n id: string;\n title: string;\n description?: string;\n };\n\n /**\n * NFM (No-Code Flow Message) reply data\n */\n nfm_reply?: {\n /**\n * Response data in JSON format\n */\n response_json: string;\n /**\n * Body text of the reply\n */\n body: string;\n /**\n * Name of the flow\n */\n name: string;\n };\n };\n\n /**\n * System object for system messages (like user phone number changes)\n */\n system?: {\n /**\n * The type of system update\n */\n type: string;\n /**\n * User's identity if the update is a customer identity change\n */\n identity?: string;\n /**\n * Old and new phone numbers if the update is a phone number change\n */\n customer?: {\n /**\n * The previous phone number\n */\n previous_wa_id: string;\n /**\n * The new phone number\n */\n wa_id: string;\n };\n };\n\n /**\n * Order object for order messages\n */\n order?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product items in the order\n */\n product_items: Array<{\n /**\n * Product ID\n */\n product_retailer_id: string;\n /**\n * Quantity of the product\n */\n quantity: number;\n /**\n * Item price\n */\n item_price: number;\n /**\n * Currency code\n */\n currency: string;\n }>;\n /**\n * Text message included with the order\n */\n text?: string;\n };\n\n /**\n * Context object, included when a user replies or interacts\n */\n context?: {\n /**\n * ID of the message\n */\n id?: string;\n /**\n * ID of the sender\n */\n from?: string;\n /**\n * ID of the message being replied to or interacted with\n */\n message_id: string;\n /**\n * ID of the forwarded message, if applicable\n */\n forwarded?: boolean;\n /**\n * Frequently forwarded status\n */\n frequently_forwarded?: boolean;\n /**\n * Original message information if the message was referred\n */\n referred_product?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product ID\n */\n product_retailer_id: string;\n };\n };\n\n /**\n * Errors array, if the message had errors\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error title\n */\n title: string;\n /**\n * Error message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * Button object for button messages\n */\n button?: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n\n /**\n * The original message data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Represents a non-message event received through the webhook\n */\nexport interface WebhookEvent {\n /**\n * The field type of the event\n */\n field: string;\n\n /**\n * The event data\n */\n value: any;\n}\n\n/**\n * Handler function for processing messages\n */\nexport type MessageHandler = (message: WebhookMessage) => void | Promise<void>;\n\n/**\n * Handler function for processing events\n */\nexport type EventHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * Statuses that can be received in status updates\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n\n/**\n * Event fields that can be received through the webhook\n */\nexport enum EventField {\n MESSAGES = 'messages',\n STATUSES = 'statuses',\n MESSAGE_TEMPLATE_STATUS_UPDATE = 'message_template_status_update',\n PHONE_NUMBER_QUALITY_UPDATE = 'phone_number_quality_update',\n PHONE_NUMBER_NAME_UPDATE = 'phone_number_name_update',\n UNKNOWN = 'unknown',\n}\n"]}
|
package/dist/chunk-N7A7DQDX.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-QE4PKOSW.mjs';import*as p from'crypto';var b=(e,r)=>p.createHmac("sha256",r).update(e,"utf-8").digest("hex");var f="UTILS",u=false,_=new a(f,process.env.DEBUG==="true"||u),l=3e3,T=30,m=2e4,g=e=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!e?.accessToken)throw _.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},N=e=>{g(e);let r={M4D_APP_ID:e?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:e?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:e?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:e?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:e?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||l,MAX_RETRIES_AFTER_WAIT:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||T,REQUEST_TIMEOUT:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||m,DEBUG:e?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:e?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return _.log(`Configuration loaded for App Id ${r.M4D_APP_ID}`),r};function P(e){return e!=null&&typeof e=="object"&&"error"in e&&typeof e.error=="object"&&e.error!=null&&"message"in e.error&&typeof e.error.message=="string"&&"type"in e.error&&typeof e.error.type=="string"&&"code"in e.error&&typeof e.error.code=="number"&&"fbtrace_id"in e.error&&typeof e.error.fbtrace_id=="string"&&(!("error_data"in e.error)||typeof e.error.error_data=="object"&&e.error.error_data!=null&&"messaging_product"in e.error.error_data&&e.error.error_data.messaging_product==="whatsapp"&&"details"in e.error.error_data&&typeof e.error.error_data.details=="string")&&(!("error_subcode"in e.error)||typeof e.error.error_subcode=="number")}function E(e){return typeof e=="object"&&e!==null}function t(e){return typeof e=="string"}var I=["data_exchange","INIT","BACK"],R=["data_exchange","INIT"];function L(e){if(!("flow_token"in e&&t(e.flow_token)&&"action"in e))return false;let{action:r,version:n,screen:o,data:s}=e,a=n==="3.0",i=I.includes(r),d=typeof o>"u"||t(o)&&o!=="SUCCESS",A=r==="data_exchange"||E(s);return a&&i&&d&&A}function U(e){if(!("flow_token"in e&&t(e.flow_token)&&"action"in e))return false;let{action:r,screen:n,data:o}=e,s=R.includes(r),a=t(n),i=E(o)&&"error_key"in o&&t(o.error)&&"error_message"in o&&t(o.error_message);return s&&a&&i}function V(e){return "action"in e&&e.action==="ping"}export{b as a,N as b,P as c,L as d,U as e,V as f};//# sourceMappingURL=chunk-N7A7DQDX.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-N7A7DQDX.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/generateXHub256Sig.ts","../src/utils/importConfig.ts","../src/utils/isMetaError.ts","../src/utils/flowTypeGuards.ts"],"names":["generateXHub256Sig","body","appSecret","LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","isMetaError","error","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest"],"mappings":"8DAEaA,IAAAA,CAAAA,CAAqB,CAACC,CAAcC,CAAAA,CAAAA,GAC/B,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUA,CAAS,CAAA,CAAE,OAAOD,CAAM,CAAA,OAAO,CAAE,CAAA,MAAA,CAAO,KAAK,MCE9EE,CAAW,CAAA,OAAA,CACXC,CAAY,CAAA,KAAA,CACZC,CAAS,CAAA,IAAIC,EAAOH,CAAU,CAAA,OAAA,CAAQ,IAAI,KAAU,GAAA,MAAA,EAAUC,CAAS,CACvEG,CAAAA,CAAAA,CAAwB,GACxBC,CAAAA,CAAAA,CAAiC,EACjCC,CAAAA,CAAAA,CAA0B,IAE1BC,CAAsBC,CAAAA,CAAAA,EAAuC,CAC/D,GAAI,CAAC,OAAA,CAAQ,IAAI,sBAA+B,EAAA,CAACA,CAAQ,EAAA,WAAA,CACrD,MAAAN,CAAAA,CAAO,IAAI,2FAA2F,CAAA,CAChG,IAAI,KAAM,CAAA,gCAAgC,CAExD,CAEaO,CAAAA,CAAAA,CAAgBC,CAAiC,EAAA,CAC1DH,CAAmBG,CAAAA,CAAW,EAE9B,IAAMC,CAAAA,CAA6B,CAC9B,UAAA,CAAuBD,CAAa,EAAA,KAAA,EAAS,QAAQ,GAAI,CAAA,UAAA,EAAc,EACvE,CAAA,cAAA,CAA2BA,CAAa,EAAA,SAAA,EAAa,QAAQ,GAAI,CAAA,cAAA,EAAkB,GACnF,kBAA+BA,CAAAA,CAAAA,EAAa,eAAiB,MAAO,CAAA,OAAA,CAAQ,GAAI,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,CAE/F,OAAO,QAAYA,GAAAA,CAAAA,EAAWA,CAAQ,CAAA,MAAA,GAAW,MACrD","file":"chunk-N7A7DQDX.mjs","sourcesContent":["import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","import { WhatsAppConfig } from 'src/types/whatsapp';\nimport type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from './logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\n};\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from 'src/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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/logger.ts","../src/utils/objectToQueryString.ts"],"names":["Logger","name","debug","data","prefix","objectToQueryString","params","searchParams","key","value","queryString"],"mappings":"AAGA,IAAqBA,EAArB,KAAuD,CAC3C,KACA,KAER,CAAA,WAAA,CAAYC,EAAcC,CAAiB,CAAA,KAAA,CAAO,CAC9C,IAAK,CAAA,IAAA,CAAOD,EACZ,IAAK,CAAA,KAAA,CAAQC,EACjB,CAEA,GAAA,CAAA,GAAOC,EAA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AAKA,CAAAA,CAAM,EAAE,MAAW,GAAA,CAAA,CAC1C,OAAO,EAGX,CAAA,IAAMC,EAAe,IAAI,eAAA,CAEzB,OAAW,CAACC,CAAAA,CAAKC,CAAK,CAAK,GAAA,MAAA,CAAO,QAAQH,CAAM,CAAA,CACxCG,IAAU,MACVF,EAAAA,CAAAA,CAAa,OAAOC,CAAK,CAAA,MAAA,CAAOC,CAAK,CAAC,CAAA,CAI9C,IAAMC,CAAcH,CAAAA,CAAAA,CAAa,UACjC,CAAA,OAAOG,EAAc,CAAIA,CAAAA,EAAAA,CAAW,GAAK,EAC7C","file":"chunk-QE4PKOSW.mjs","sourcesContent":["// @ts-nocheck\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 log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...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.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n searchParams.append(key, String(value));\n }\n }\n\n const queryString = searchParams.toString();\n return queryString ? `?${queryString}` : '';\n};\n"]}
|
package/dist/chunk-R4CFE2XP.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a,b as b$1}from'./chunk-QE4PKOSW.mjs';var w="BaseAPI",I=false,S=new a(w,process.env.DEBUG==="true"||I),n=class{config;client;constructor(e,s){this.config=e,this.client=s,S.log("Initialized with HTTPSClient");}sendJson(e,s,t,o){return this.client.getJson(e,s,t,o)}sendFormData(e,s,t,o){return this.client.sendFormData(e,s,t,o)}sendUrlEncodedForm(e,s,t,o){return this.client.sendUrlEncodedForm(e,s,t,o)}};function c(i){if(!i)return "";let e="";return Array.isArray(i)?e=i.join(","):e=Object.entries(i).filter(([s,t])=>t).map(([s])=>s).join(","),e?`?fields=${e}`:""}var d=class extends n{endpoint="whatsapp_business_profile";constructor(e,s){super(e,s);}async getBusinessProfile(e){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${c(e)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,s,t){let o=b$1({file_length:e,file_type:s,file_name:t});return this.sendJson("POST",`app/uploads/${o}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,s){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,s)}async getUploadHandle(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}};var l=class extends n{endpoint="whatsapp_business_encryption";constructor(e,s){super(e,s);}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let s=new FormData;return s.append("business_public_key",e),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}};var _="FlowAPI",J=false,q=new a(_,process.env.DEBUG==="true"||J),g=class extends n{constructor(e,s){super(e,s),q.log("FlowAPI initialized");}async listFlows(e){return this.sendJson("GET",`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,s){let t={name:s.name,categories:s.categories,...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.clone_flow_id&&{clone_flow_id:s.clone_flow_id},...s.flow_json&&{flow_json:s.flow_json},...s.publish!==void 0&&{publish:s.publish}};return this.sendJson("POST",`/${e}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getFlow(e,s,t){let o=new URLSearchParams;s&&o.append("fields",s),t&&o.append("date_format",t);let r=o.toString()?`?${o.toString()}`:"";return this.sendJson("GET",`/${e}${r}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(e,s=false){let t=`preview.invalidate(${s})`;return this.getFlow(e,t)}async updateFlowMetadata(e,s){let t={...s.name&&{name:s.name},...s.categories&&{categories:s.categories},...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.application_id&&{application_id:s.application_id}};return this.sendJson("POST",`/${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteFlow(e){return this.sendJson("DELETE",`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson("GET",`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,s){let t=new FormData,o;if(s.file instanceof Buffer)o=new globalThis.Blob([s.file]),t.append("file",o);else if(typeof s.file=="object"&&!(s.file instanceof Blob))try{o=new globalThis.Blob([JSON.stringify(s.file,null,2)],{type:"application/json"}),t.append("file",o);}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(s.file instanceof Blob)o=s.file,t.append("file",o);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return t.append("asset_type","FLOW_JSON"),t.append("name",s.name||"flow.json"),this.sendFormData("POST",`/${e}/assets`,this.config.REQUEST_TIMEOUT,t)}async validateFlowJson(e,s){try{let t=await this.updateFlowJson(e,{file:s}),o=!t.validation_errors||t.validation_errors.length===0;return {...t,valid:o}}catch(t){throw q.error("Error during Flow JSON validation attempt:",t),t}}async publishFlow(e){return this.sendJson("POST",`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson("POST",`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,s){let t={source_waba_id:s.source_waba_id,...s.source_flow_names&&{source_flow_names:s.source_flow_names}};return this.sendJson("POST",`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var f=class extends n{endpoint="media";constructor(e,s){super(e,s);}async getMediaById(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,s="whatsapp"){let t=new FormData;return t.append("file",e),t.append("messaging_product",s),t.append("type",e.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}async deleteMedia(e){return this.sendJson("DELETE",`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return this.sendJson("GET",e,this.config.REQUEST_TIMEOUT,null)}};var y=class extends n{commonMethod="POST";commonEndpoint="messages";constructor(e,s){super(e,s);}bodyBuilder(e,s,t,o){let r={messaging_product:"whatsapp",recipient_type:"individual",to:t,type:e,[e]:s};return o&&(r.context={message_id:o}),r}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("audio",s,t,o)))}async contacts(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("contacts",s,t,o)))}async document(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("document",s,t,o)))}async image(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("image",s,t,o)))}async interactive(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,t,o)))}async location(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("location",s,t,o)))}async sticker(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("sticker",s,t,o)))}async template(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("template",s,t,o)))}async text(e){let{body:s,previewUrl:t,to:o,replyMessageId:r}=e,M;return typeof s=="string"?M={body:s,preview_url:t}:M=s,this.send(JSON.stringify(this.bodyBuilder("text",M,o,r)))}async video(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("video",s,t,o)))}async status(e){let{status:s,messageId:t,typingIndicator:o}=e,r={messaging_product:"whatsapp",status:s,message_id:t,...o&&{typing_indicator:o}};return this.send(JSON.stringify(r))}async markAsRead(e){return this.status({status:"read",messageId:e.messageId})}async showTypingIndicator(e){return this.status({status:"read",messageId:e.messageId,typingIndicator:{type:"text"}})}async interactiveList(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,t,o)))}async interactiveCtaUrl(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,t,o)))}async interactiveLocationRequest(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,t,o)))}async interactiveAddressMessage(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,t,o)))}async interactiveReplyButtons(e){let{body:s,to:t,replyMessageId:o}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,t,o)))}async interactiveFlow(e){let{body:s,to:t,replyMessageId:o}=e;return s.action.parameters.flow_message_version===void 0&&(s.action.parameters.flow_message_version="3"),s.action.parameters.mode===void 0&&(s.action.parameters.mode="published"),s.action.parameters.flow_action===void 0&&(s.action.parameters.flow_action="navigate"),s.action.parameters.flow_action==="navigate"?s.action.parameters.flow_action_payload?.screen===void 0&&(s.action.parameters.flow_action_payload={...s.action.parameters.flow_action_payload,screen:"INIT"}):s.action.parameters.flow_action==="data_exchange"&&delete s.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",s,t,o)))}async reaction(e){let{messageId:s,emoji:t,to:o}=e,r={messaging_product:"whatsapp",recipient_type:"individual",to:o,type:"reaction",reaction:{message_id:s,emoji:t}};return this.send(JSON.stringify(r))}};var h=class extends n{endpoint="phone_numbers";constructor(e,s){super(e,s);}async getPhoneNumberById(e){let s=e?b$1({fields:e}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}};var b=class extends n{endpoint="message_qrdls";constructor(e,s){super(e,s);}async createQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}};var R=class extends n{constructor(e,s){super(e,s);}async register(e,s){let t={messaging_product:"whatsapp",pin:e,...s&&{data_localization_region:s}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var P=class extends n{endpoint="message_templates";constructor(e,s){super(e,s);}async getTemplate(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,s){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(e){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${b$1(e)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${b$1(e)}`,this.config.REQUEST_TIMEOUT,null)}};var T=class extends n{constructor(e,s){super(e,s);}async setTwoStepVerificationCode(e){let s={pin:e};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var C=class extends n{constructor(e,s){super(e,s);}async getWabaAccount(e){let s=c(e)?.replace(/,/g,"%2C");return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:e,verify_token:s}){let t={override_callback_uri:e,verify_token:s};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};export{n as a,d as b,l as c,g as d,f as e,y as f,h as g,b as h,R as i,P as j,T as k,C as l};//# sourceMappingURL=chunk-R4CFE2XP.mjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-R4CFE2XP.mjs.map
|