meta-cloud-api 1.0.3 → 1.1.0
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/chunk-5577QQ7V.js +2 -0
- package/dist/chunk-5577QQ7V.js.map +1 -0
- package/dist/{chunk-WGGN32O2.js → chunk-6DFC5L3X.js} +2 -2
- package/dist/chunk-6DFC5L3X.js.map +1 -0
- package/dist/chunk-GM63NGNV.js +2 -0
- package/dist/chunk-GM63NGNV.js.map +1 -0
- package/dist/{chunk-JPGXONBQ.js → chunk-U5FBZ6UB.js} +3 -3
- package/dist/{chunk-JPGXONBQ.js.map → chunk-U5FBZ6UB.js.map} +1 -1
- package/dist/chunk-ZMNXRMWK.js +2 -0
- package/dist/chunk-ZMNXRMWK.js.map +1 -0
- package/dist/core/webhook/frameworks/express.d.ts +9 -6
- package/dist/core/webhook/frameworks/express.js +1 -1
- package/dist/core/webhook/frameworks/nextjs-app.d.ts +47 -0
- package/dist/core/webhook/frameworks/nextjs-app.js +2 -0
- package/dist/core/webhook/frameworks/nextjs-app.js.map +1 -0
- package/dist/core/webhook/frameworks/nextjs.d.ts +7 -4
- package/dist/core/webhook/frameworks/nextjs.js +1 -1
- package/dist/core/webhook/index.d.ts +1 -0
- package/dist/core/webhook/index.js +1 -1
- package/dist/handler-DbySwF0E.d.ts +20 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/utils/index.js +1 -1
- package/package.json +40 -60
- package/dist/chunk-NOJFGTRT.js +0 -2
- package/dist/chunk-NOJFGTRT.js.map +0 -1
- package/dist/chunk-WGGN32O2.js.map +0 -1
- package/dist/chunk-YXZ4L2OK.js +0 -2
- package/dist/chunk-YXZ4L2OK.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {d,c}from'./chunk-U5FBZ6UB.js';var n=class{processor;constructor(e){this.processor=new d(e);}async processVerification(e,s,o){return await this.processor.processVerification(e,s,o)}async processWebhook(e){return await this.processor.processWebhook(e)}async processFlow(e){return await this.processor.processFlow(e)}constructFullUrl(e,s=""){return c(e,s)}applyHeaders(e,s){s.setHeader&&Object.entries(e.headers).forEach(([o,r])=>{s.setHeader(o,r);});}async autoRoute(e,s,...o){switch(e.method?.toUpperCase()){case "GET":return await this.handleGet(e,s,...o);case "POST":return await this.handlePost(e,s,...o);default:if(s.status&&s.json)return s.status(405).json({error:"Method Not Allowed"});throw new Error("Method Not Allowed")}}get webhookProcessor(){return this.processor}};export{n as a};//# sourceMappingURL=chunk-5577QQ7V.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-5577QQ7V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/webhook/frameworks/handler.ts"],"names":["BaseWebhookHandler","config","WebhookProcessor","mode","token","challenge","request","headers","url","constructFullUrl","result","res","key","value","req","args"],"mappings":"sCAqCO,IAAeA,CAAAA,CAAf,KAAgG,CACzF,SAAA,CAEV,YAAYC,CAAAA,CAA2B,CACnC,IAAA,CAAK,SAAA,CAAY,IAAIC,CAAAA,CAAiBD,CAAM,EAChD,CAuBA,MAAgB,mBAAA,CACZE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACsB,CACtB,OAAO,MAAM,IAAA,CAAK,SAAA,CAAU,oBAAoBF,CAAAA,CAAMC,CAAAA,CAAOC,CAAS,CAC1E,CAKA,MAAgB,cAAA,CAAeC,CAAAA,CAA0C,CACrE,OAAO,MAAM,IAAA,CAAK,SAAA,CAAU,cAAA,CAAeA,CAAO,CACtD,CAKA,MAAgB,WAAA,CAAYA,EAA0C,CAClE,OAAO,MAAM,IAAA,CAAK,UAAU,WAAA,CAAYA,CAAO,CACnD,CAKU,iBAAiBC,CAAAA,CAAwDC,CAAAA,CAAc,EAAA,CAAY,CACzG,OAAOC,CAAAA,CAAiBF,CAAAA,CAASC,CAAG,CACxC,CAKU,YAAA,CAAaE,CAAAA,CAAuBC,CAAAA,CAAsB,CAC5DA,EAAI,SAAA,EACJ,MAAA,CAAO,OAAA,CAAQD,CAAAA,CAAO,OAAO,CAAA,CAAE,OAAA,CAAQ,CAAC,CAACE,EAAKC,CAAK,CAAA,GAAM,CACrDF,CAAAA,CAAI,UAAWC,CAAAA,CAAKC,CAAK,EAC7B,CAAC,EAET,CAKA,MAAgB,SAAA,CAAUC,CAAAA,CAAeH,KAAmBI,CAAAA,CAA2B,CAGnF,OAFeD,CAAAA,CAAI,QAAQ,WAAA,EAAY,EAGnC,KAAK,MACD,OAAO,MAAM,IAAA,CAAK,SAAA,CAAUA,EAAKH,CAAAA,CAAK,GAAGI,CAAI,CAAA,CACjD,KAAK,MAAA,CACD,OAAO,MAAM,IAAA,CAAK,WAAWD,CAAAA,CAAKH,CAAAA,CAAK,GAAGI,CAAI,EAClD,QACI,GAAIJ,CAAAA,CAAI,MAAA,EAAUA,EAAI,IAAA,CAClB,OAAOA,CAAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,CAAE,KAAA,CAAO,oBAAqB,CAAC,CAAA,CAE/D,MAAM,IAAI,MAAM,oBAAoB,CAC5C,CACJ,CAKA,IAAI,gBAAA,EAAqC,CACrC,OAAO,IAAA,CAAK,SAChB,CAaJ","file":"chunk-5577QQ7V.js","sourcesContent":["import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Generic request/response interfaces for framework abstraction\nexport interface BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query?: Record<string, any> | URLSearchParams;\n rawBody?: any;\n}\n\nexport interface BaseResponse<T = any> {\n status(code: number): T;\n json?(data: any): T | void;\n send?(data?: any): T | void;\n setHeader?(name: string, value: string): void;\n}\n\n// Base configuration interface\nexport interface BaseWebhookConfig extends WhatsAppConfig {\n // Framework-specific configs can extend this\n}\n\n// Response result interface for consistent return types\nexport interface WebhookResult {\n status: number;\n headers: Record<string, string>;\n body: any;\n}\n\n/**\n * Abstract base class for framework-agnostic webhook handlers\n * Provides common architecture and functionality across all frameworks\n */\nexport abstract class BaseWebhookHandler<TRequest extends BaseRequest, TResponse extends BaseResponse> {\n protected processor: WebhookProcessor;\n\n constructor(config: BaseWebhookConfig) {\n this.processor = new WebhookProcessor(config);\n }\n\n /**\n * Abstract method for handling GET requests (webhook verification)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleGet(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling POST requests (webhook processing)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handlePost(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling flow requests\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleFlow(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Common webhook verification logic\n */\n protected async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResult> {\n return await this.processor.processVerification(mode, token, challenge);\n }\n\n /**\n * Common webhook processing logic\n */\n protected async processWebhook(request: Request): Promise<WebhookResult> {\n return await this.processor.processWebhook(request);\n }\n\n /**\n * Common flow processing logic\n */\n protected async processFlow(request: Request): Promise<WebhookResult> {\n return await this.processor.processFlow(request);\n }\n\n /**\n * Helper to construct full URL from headers and path\n */\n protected constructFullUrl(headers: Record<string, string | string[] | undefined>, url: string = ''): string {\n return constructFullUrl(headers, url);\n }\n\n /**\n * Helper to apply result headers to response\n */\n protected applyHeaders(result: WebhookResult, res: TResponse): void {\n if (res.setHeader) {\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader!(key, value);\n });\n }\n }\n\n /**\n * Auto-routing method handler that dispatches based on request method\n */\n protected async autoRoute(req: TRequest, res: TResponse, ...args: any[]): Promise<any> {\n const method = req.method?.toUpperCase();\n\n switch (method) {\n case 'GET':\n return await this.handleGet(req, res, ...args);\n case 'POST':\n return await this.handlePost(req, res, ...args);\n default:\n if (res.status && res.json) {\n return res.status(405).json({ error: 'Method Not Allowed' });\n }\n throw new Error('Method Not Allowed');\n }\n }\n\n /**\n * Get the processor instance for handler registration\n */\n get webhookProcessor(): WebhookProcessor {\n return this.processor;\n }\n\n /**\n * Abstract method to return the clean handler object\n * Each framework implements this to return their specific handler structure\n */\n abstract getHandlers(): {\n GET: (...args: any[]) => Promise<any>;\n POST: (...args: any[]) => Promise<any>;\n webhook: (...args: any[]) => Promise<any>;\n flow: (...args: any[]) => Promise<any>;\n processor: WebhookProcessor;\n };\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function c(n){return typeof n=="object"&&n!==null}function o(n){return typeof n=="string"}var f=["data_exchange","INIT","BACK"],E=["data_exchange","INIT"];function w(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,version:i,screen:t,data:s}=n,r=i==="3.0",a=f.includes(e),l=typeof t>"u"||o(t)&&t!=="SUCCESS",u=e==="data_exchange"||c(s);return r&&a&&l&&u}function A(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,screen:i,data:t}=n,s=E.includes(e),r=o(i),a=c(t)&&"error_key"in t&&o(t.error)&&"error_message"in t&&o(t.error_message);return s&&r&&a}function d(n){return "action"in n&&n.action==="ping"}export{w as a,A as b,d as c};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
function c(n){return typeof n=="object"&&n!==null}function o(n){return typeof n=="string"}var f=["data_exchange","INIT","BACK"],E=["data_exchange","INIT"];function w(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,version:i,screen:t,data:s}=n,r=i==="3.0",a=f.includes(e),l=typeof t>"u"||o(t)&&t!=="SUCCESS",u=e==="data_exchange"||c(s);return r&&a&&l&&u}function A(n){if(!("flow_token"in n&&o(n.flow_token)&&"action"in n))return false;let{action:e,screen:i,data:t}=n,s=E.includes(e),r=o(i),a=c(t)&&"error_key"in t&&o(t.error)&&"error_message"in t&&o(t.error_message);return s&&r&&a}function d(n){return "action"in n&&n.action==="ping"}export{w as a,A as b,d as c};//# sourceMappingURL=chunk-6DFC5L3X.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-6DFC5L3X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/flowTypeGuards.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest"],"mappings":"AAaA,SAASA,CAAAA,CAASC,CAAAA,CAAkD,CAChE,OAAO,OAAOA,CAAAA,EAAU,QAAA,EAAYA,CAAAA,GAAU,IAClD,CAOA,SAASC,CAAAA,CAASD,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAAA,EAAU,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAA,eAAA,CAAA,MAAA,CAAA,MAAuE,CAAA,CAG/FC,EAAgB,CAAA,eAAA,CAAA,MAAkD,CAAA,CASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAA,GAAgBA,GAAWJ,CAAAA,CAASI,CAAAA,CAAQ,UAAU,CAAA,EAAK,QAAA,GAAYA,CAAAA,CAAAA,CACzE,OAAO,MAAA,CAGX,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,OAAA,CAAAC,EAAS,MAAA,CAAAC,CAAAA,CAAQ,IAAA,CAAAC,CAAK,EAAIJ,CAAAA,CAGpCK,CAAAA,CAAkBH,CAAAA,GAAY,KAAA,CAG9BI,CAAAA,CAAiBT,CAAAA,CAAsB,QAAA,CAASI,CAAa,EAG7DM,CAAAA,CAAiB,OAAOJ,CAAAA,CAAW,GAAA,EAAgBP,EAASO,CAAM,CAAA,EAAKA,CAAAA,GAAW,SAAA,CAGlFK,EAAeP,CAAAA,GAAW,eAAA,EAAgCP,CAAAA,CAASU,CAAI,CAAA,CAG7E,OAAOC,CAAAA,EAAmBC,CAAAA,EAAkBC,GAAkBC,CAClE,CASO,SAASC,CAAAA,CAAmBT,EAQjC,CAEE,GAAI,EAAE,YAAA,GAAgBA,GAAWJ,CAAAA,CAASI,CAAAA,CAAQ,UAAU,CAAA,EAAK,QAAA,GAAYA,CAAAA,CAAAA,CACzE,OAAO,MAAA,CAGX,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,MAAA,CAAAE,EAAQ,IAAA,CAAAC,CAAK,CAAA,CAAIJ,CAAAA,CAG3BM,EAAiBR,CAAAA,CAAc,QAAA,CAASG,CAAa,CAAA,CAGrDM,CAAAA,CAAiBX,CAAAA,CAASO,CAAM,CAAA,CAGhCK,EACFd,CAAAA,CAASU,CAAI,CAAA,EACb,WAAA,GAAeA,GACfR,CAAAA,CAASQ,CAAAA,CAAK,KAAK,CAAA,EACnB,kBAAmBA,CAAAA,EACnBR,CAAAA,CAASQ,CAAAA,CAAK,aAAa,CAAA,CAG/B,OAAOE,CAAAA,EAAkBC,CAAAA,EAAkBC,CAC/C,CASO,SAASE,CAAAA,CAAkBV,CAAAA,CAAiE,CAE/F,OAAO,QAAA,GAAYA,CAAAA,EAAWA,CAAAA,CAAQ,SAAW,MACrD","file":"chunk-6DFC5L3X.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '../api/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-5577QQ7V.js';var a=class extends a$1{constructor(e){super(e);}async parseRequestBody(e){if(e.method==="POST"&&!e.body){let s=[];if(typeof e[Symbol.asyncIterator]=="function"){for await(let o of e)s.push(o);let t=Buffer.concat(s).toString();if(t.trim())try{e.body=JSON.parse(t);}catch{throw new Error("Invalid JSON in request body")}else e.body={};}}}async handleGet(e,s){try{let{"hub.mode":t,"hub.verify_token":o,"hub.challenge":r}=e.query,n=await this.processVerification(t||null,o||null,r||null);return this.applyHeaders(n,s),s.status(n.status).send(n.body)}catch(t){return console.error("Webhook verification error:",t),s.status(500).json({error:"Internal Server Error"})}}async handlePost(e,s){try{await this.parseRequestBody(e);}catch(t){return console.error("Webhook processing error:",t),t instanceof Error&&t.message==="Invalid JSON in request body"?s.status(400).json({error:"Invalid JSON"}):s.status(500).json({error:"Internal Server Error"})}try{let t=this.constructFullUrl(e.headers,e.url),o=new Request(t,{method:"POST",headers:e.headers,body:JSON.stringify(e.body)}),r=await this.processWebhook(o);return this.applyHeaders(r,s),s.status(r.status).send(r.body)}catch(t){return console.error("Webhook processing error:",t),s.status(500).json({error:"Internal Server Error"})}}async handleFlow(e,s){try{let t=this.constructFullUrl(e.headers,e.url),o=new Request(t,{method:e.method,headers:e.headers,body:e.method==="POST"?JSON.stringify(e.body):void 0}),r=await this.processFlow(o);return this.applyHeaders(r,s),s.status(r.status).send(r.body)}catch(t){return console.error("Flow error:",t),s.status(500).json({error:"Internal Server Error"})}}getHandlers(){return {GET:(e,s)=>this.handleGet(e,s),POST:(e,s)=>this.handlePost(e,s),webhook:(e,s)=>this.autoRoute(e,s),flow:(e,s)=>this.handleFlow(e,s),processor:this.webhookProcessor}}};function p(i){return new a(i).getHandlers()}export{p as a};//# sourceMappingURL=chunk-GM63NGNV.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-GM63NGNV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/webhook/frameworks/nextjs.ts"],"names":["NextJsWebhookHandler","BaseWebhookHandler","config","req","chunks","chunk","body","res","mode","token","challenge","result","error","fullUrl","webRequest","webhookHandler"],"mappings":"2CA0BA,IAAMA,CAAAA,CAAN,cAGUC,GAAwC,CAC9C,YAAYC,CAAAA,CAA6B,CACrC,MAAMA,CAAM,EAChB,CAGA,MAAc,gBAAA,CAAiBC,EAA8B,CACzD,GAAIA,EAAI,MAAA,GAAW,MAAA,EAAU,CAACA,CAAAA,CAAI,IAAA,CAAM,CACpC,IAAMC,CAAAA,CAAmB,EAAC,CAG1B,GAAI,OAAQD,CAAAA,CAAY,MAAA,CAAO,aAAa,CAAA,EAAM,UAAA,CAAY,CAC1D,UAAA,IAAiBE,CAAAA,IAASF,EACtBC,CAAAA,CAAO,IAAA,CAAKC,CAAK,CAAA,CAGrB,IAAMC,CAAAA,CAAO,MAAA,CAAO,MAAA,CAAOF,CAAM,EAAE,QAAA,EAAS,CAG5C,GAAIE,CAAAA,CAAK,IAAA,GACL,GAAI,CACAH,EAAI,IAAA,CAAO,IAAA,CAAK,MAAMG,CAAI,EAC9B,MAAgB,CACZ,MAAM,IAAI,KAAA,CAAM,8BAA8B,CAClD,CAAA,KAEAH,CAAAA,CAAI,KAAO,GAEnB,CACJ,CACJ,CAEA,MAAgB,SAAA,CAAUA,CAAAA,CAAeI,EAA8B,CACnE,GAAI,CAC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CAAKI,CAAG,CAAA,CAC/D,IAAA,CAAM,CAACJ,CAAAA,CAAeI,CAAAA,GAAmB,KAAK,UAAA,CAAWJ,CAAAA,CAAKI,CAAG,CAAA,CAGjE,OAAA,CAAS,CAACJ,CAAAA,CAAeI,CAAAA,GAAmB,KAAK,SAAA,CAAUJ,CAAAA,CAAKI,CAAG,CAAA,CAGnE,IAAA,CAAM,CAACJ,EAAeI,CAAAA,GAAmB,IAAA,CAAK,WAAWJ,CAAAA,CAAKI,CAAG,EAGjE,SAAA,CAAW,IAAA,CAAK,gBACpB,CACJ,CACJ,EAGO,SAASQ,CAAAA,CACZb,EACF,CAEE,OADgB,IAAIF,CAAAA,CAA0CE,CAAM,CAAA,CACrD,WAAA,EACnB","file":"chunk-GM63NGNV.js","sourcesContent":["import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from './handler';\n\n// Next.js specific interfaces\nexport interface BaseApiRequest extends BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Partial<Record<string, string | string[]>>;\n rawBody?: any;\n}\n\nexport interface BaseApiResponse extends BaseResponse {\n status(code: number): any;\n json(data: any): void | any;\n send(data?: any): void | any;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextJsWebhookConfig extends BaseWebhookConfig {\n // Next.js specific config can be added here\n}\n\n/**\n * Next.js Page Router webhook handler extending the base handler\n */\nclass NextJsWebhookHandler<\n TRequest extends BaseApiRequest,\n TResponse extends BaseApiResponse,\n> extends BaseWebhookHandler<TRequest, TResponse> {\n constructor(config: NextJsWebhookConfig) {\n super(config);\n }\n\n // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest): Promise<void> {\n if (req.method === 'POST' && !req.body) {\n const chunks: Buffer[] = [];\n\n // Check if req is a stream (has Symbol.asyncIterator)\n if (typeof (req as any)[Symbol.asyncIterator] === 'function') {\n for await (const chunk of req as any) {\n chunks.push(chunk);\n }\n\n const body = Buffer.concat(chunks).toString();\n\n // Only attempt to parse if there's actual content\n if (body.trim()) {\n try {\n req.body = JSON.parse(body);\n } catch (error) {\n throw new Error('Invalid JSON in request body');\n }\n } else {\n req.body = {};\n }\n }\n }\n }\n\n protected async handleGet(req: TRequest, res: TResponse): Promise<any> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handlePost(req: TRequest, res: TResponse): Promise<any> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req);\n } catch (error) {\n console.error('Webhook processing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n return res.status(400).json({ error: 'Invalid JSON' });\n }\n\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook processing error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handleFlow(req: TRequest, res: TResponse): Promise<any> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Flow error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: TRequest, res: TResponse) => this.handleGet(req, res),\n POST: (req: TRequest, res: TResponse) => this.handlePost(req, res),\n\n // Auto-routing webhook handler\n webhook: (req: TRequest, res: TResponse) => this.autoRoute(req, res),\n\n // Flow handler\n flow: (req: TRequest, res: TResponse) => this.handleFlow(req, res),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\n// Generic webhook handler that accepts any compatible request/response types\nexport function webhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n return handler.getHandlers();\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {c,b,a as a$1}from'./chunk-
|
|
2
|
-
`),d=e.FLOW_API_PASSPHRASE,i=y.createPrivateKey({key:p,passphrase:d}),g;try{s.info("Decrypting AES key"),g=y.privateDecrypt({key:i,padding:y.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch(F){throw s.error("Failed to decrypt AES key:",F),new Error("Failed to decrypt the request. Please verify your private key.")}let u=Buffer.from(t,"base64"),l=Buffer.from(o,"base64"),f=u.subarray(0,-16),c=u.subarray(-16);s.info("Decrypting flow data");let b=y.createDecipheriv("aes-128-gcm",g,l);b.setAuthTag(c);let v=Buffer.concat([b.update(f),b.final()]).toString("utf-8");return s.info("Flow request decryption complete"),{decryptedBody:JSON.parse(v),aesKeyBuffer:g,initialVectorBuffer:l}}function A(a,e,r){s.info("Encrypting flow response");let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=y.createCipheriv("aes-128-gcm",e,Buffer.from(t)),p=Buffer.concat([o.update(JSON.stringify(a||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64");return s.info("Flow response encryption complete"),p}catch(o){throw s.error("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var m=new a("WEBHOOK_PROCESSOR",process.env.DEBUG==="true"),W=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$2(e),this.client=new b$1(e),m.log("WebhookProcessor instantiated");}async processVerification(e,r,t){return e==="subscribe"&&r===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:t||"",headers:{"Content-Type":"text/plain"}}:{status:403,body:JSON.stringify({error:"Forbidden"}),headers:{"Content-Type":"application/json"}}}async processWebhook(e){try{let r=await M(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing webhook: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}async processFlow(e){try{let r=await S(e,this.config,this.client,this.flowHandlers),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing flow: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}onMessage(e,r){this.messageHandlers.set(e,r),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}getClient(){return this.client}getConfig(){return this.config}};export{M as a,S as b,C as c,W as d};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {c,b,a as a$1}from'./chunk-6DFC5L3X.js';import {a as a$2,b as b$1}from'./chunk-BAOZ4U74.js';import {a}from'./chunk-FKXSL2JK.js';import y from'crypto';var O="WEBHOOK_UTILS",s=new a(O,process.env.DEBUG==="true");async function M(a,e,r){try{s.info("Processing webhook messages request");let t=await a.json();if(s.info("Webhook request body:",t),t.object!=="whatsapp_business_account"){let p="Received webhook for non-WhatsApp event";return s.warn(p,{body:t}),new Response(JSON.stringify({error:p}),{status:404})}let o=[];for(let p of t.entry)try{s.info("Processing webhook entry:",{entryId:p.id});let d=p.changes;for(let i of d)i.field==="messages"&&(s.info("Processing messages change:",{change:i}),await T(p.id,i.value,e,r));}catch(d){let i=`Error processing webhook: ${d}`;s.error(i,{entry:p,error:d}),o.push(i);}return s.info("Webhook processing complete",{errorCount:o.length}),new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(t){return s.error("Error processing webhook:",t),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async function S(a,e,r,t){try{s.info("Processing flow request");let o=await a.text(),p=a.headers.get("x-hub-signature-256");if(s.info("Flow request signature:",{signature:p}),!_(o,p,e.WEBHOOK_VERIFICATION_TOKEN||""))return s.warn("Invalid request signature",{signature:p}),new Response(JSON.stringify({error:"Unauthorized"}),{status:401});let d=JSON.parse(o);s.info("Flow request data:",d);let{decryptedBody:i}=q(d,e);s.info("Decrypted flow request:",i);let g=t.get("*");if(!g)return s.warn("No handler registered for flow action:",{action:i.action}),new Response(JSON.stringify({error:"Handler not found"}),{status:404});if(c(i))return s.info("Handling flow ping request"),new Response(JSON.stringify({version:"3.0",data:{status:"active"}}),{status:200});if(b(i))return s.warn("Flow error request received:",i),new Response(null,{status:200});if(a$1(i)){s.info("Processing flow data exchange request");let u=await g(r,i);s.info("Flow handler result:",u);let l=A(u,Buffer.from(d.aes_key,"base64"),Buffer.from(d.initial_vector,"base64"));return s.info("Encrypted flow response generated"),new Response(JSON.stringify(l),{status:200})}return s.warn("Unknown flow request type:",i),new Response(JSON.stringify({error:"Unknown request type"}),{status:400})}catch(o){return s.error("Error handling flow request:",o),new Response(JSON.stringify({error:"Internal server error"}),{status:500})}}function _(a,e,r){if(!e)return s.warn("Missing signature in request"),false;s.info("Signature verification details:",{bodyLength:a.length,verificationTokenLength:r.length,rawSignature:e,cleanedSignature:e.replace("sha256=","")});let t=y.createHmac("sha256",r).update(a).digest("hex");return s.info("Signature verification:",{received:e.replace("sha256=",""),expected:t}),y.timingSafeEqual(Buffer.from(e.replace("sha256=","")),Buffer.from(t))}function C(a,e){let r=a["x-forwarded-proto"]||"http",t=a.host||"localhost";return `${r}://${t}${e||"/"}`}async function T(a,e,r,t){s.info("Processing messages:",{waba_id:a,value:e});let o=e.metadata,p=e.contacts,d=a,i=o?.display_phone_number||"",g=o?.phone_number_id||"",u=p?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){s.info("Processing statuses:",{statusCount:e.statuses.length});let l=e.statuses;for(let n of l){let f={wabaId:d,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:g,displayPhoneNumber:i,profileName:u,statuses:e.statuses[0],originalData:n};s.info("Processing status:",f),await w(t.messageHandlers.get("statuses"),r,f,"statuses");}return}if(e.messages&&e.messages.length>0){s.info("Processing messages:",{messageCount:e.messages.length});let l=e.messages;for(let n of l){let f=n.type;s.info("Processing message:",{messageType:f,messageId:n.id});let c={wabaId:d,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:g,displayPhoneNumber:i,profileName:u,originalData:n};switch(f){case "text":c.text=n.text;break;case "image":c.image=n.image;break;case "video":c.video=n.video;break;case "audio":c.audio=n.audio;break;case "document":c.document=n.document;break;case "sticker":c.sticker=n.sticker;break;case "location":c.location=n.location;break;case "contacts":c.contacts=n.contacts;break;case "interactive":c.interactive=n.interactive;break;case "button":c.button=n.button;break;case "order":c.order=n.order;break;case "system":c.system=n.system;break;case "reaction":c.reaction=n.reaction;break;default:s.warn("Unknown message type:",{messageType:f});break}s.info("Executing message handlers"),await w(t.preProcessHandler,r,c,"pre-process"),await w(t.messageHandlers.get(f),r,c,f),await w(t.postProcessHandler,r,c,"post-process");}}}async function w(a,e,r,t){if(a)try{s.info("Executing handler:",{handlerType:t,messageId:r.id}),await a(e,r),s.info("Handler execution complete:",{handlerType:t,messageId:r.id});}catch(o){s.error(`Error in ${t} handler:`,{error:o,messageId:r.id});}else s.info("No handler registered:",{handlerType:t});}function q(a,e){s.info("Decrypting flow request");let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=a;if(!r||!t||!o)throw s.error("Missing required encryption properties"),new Error("Missing required encryption properties");let p=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
|
|
2
|
+
`),d=e.FLOW_API_PASSPHRASE,i=y.createPrivateKey({key:p,passphrase:d}),g;try{s.info("Decrypting AES key"),g=y.privateDecrypt({key:i,padding:y.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch(F){throw s.error("Failed to decrypt AES key:",F),new Error("Failed to decrypt the request. Please verify your private key.")}let u=Buffer.from(t,"base64"),l=Buffer.from(o,"base64"),f=u.subarray(0,-16),c=u.subarray(-16);s.info("Decrypting flow data");let b=y.createDecipheriv("aes-128-gcm",g,l);b.setAuthTag(c);let v=Buffer.concat([b.update(f),b.final()]).toString("utf-8");return s.info("Flow request decryption complete"),{decryptedBody:JSON.parse(v),aesKeyBuffer:g,initialVectorBuffer:l}}function A(a,e,r){s.info("Encrypting flow response");let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=y.createCipheriv("aes-128-gcm",e,Buffer.from(t)),p=Buffer.concat([o.update(JSON.stringify(a||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64");return s.info("Flow response encryption complete"),p}catch(o){throw s.error("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var m=new a("WEBHOOK_PROCESSOR",process.env.DEBUG==="true"),W=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$2(e),this.client=new b$1(e),m.log("WebhookProcessor instantiated");}async processVerification(e,r,t){return e==="subscribe"&&r===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:t||"",headers:{"Content-Type":"text/plain"}}:{status:403,body:JSON.stringify({error:"Forbidden"}),headers:{"Content-Type":"application/json"}}}async processWebhook(e){try{let r=await M(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing webhook: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}async processFlow(e){try{let r=await S(e,this.config,this.client,this.flowHandlers),t=await r.text(),o=r.headers.get("content-type")||"application/json";return {status:r.status,body:t,headers:{"Content-Type":o}}}catch(r){return m.log(`Error processing flow: ${r}`),{status:500,body:JSON.stringify({error:"Internal Server Error"}),headers:{"Content-Type":"application/json"}}}}onMessage(e,r){this.messageHandlers.set(e,r),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}getClient(){return this.client}getConfig(){return this.config}};export{M as a,S as b,C as c,W as d};//# sourceMappingURL=chunk-U5FBZ6UB.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-U5FBZ6UB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts"],"names":["LIB_NAME","LOGGER","Logger","processWebhookMessages","request","whatsapp","handlers","body","errorMsg","errors","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","signature","verifySignature","data","decryptedBody","decryptFlowRequest","handler","isFlowPingRequest","isFlowErrorRequest","isFlowDataExchangeRequest","result","encryptedResponse","encryptFlowResponse","verificationToken","expectedSignature","crypto","constructFullUrl","headers","url","protocol","host","waba_id","value","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookProcessor","importConfig","WhatsApp","mode","token","challenge","webResponse","contentType","type"],"mappings":"6JAUA,IAAMA,CAAAA,CAAW,eAAA,CACXC,CAAAA,CAAS,IAAIC,CAAAA,CAAOF,CAAAA,CAAU,OAAA,CAAQ,GAAA,CAAI,KAAA,GAAU,MAAM,EAQhE,eAAsBG,CAAAA,CAClBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAKiB,CACjB,GAAI,CACAL,CAAAA,CAAO,IAAA,CAAK,qCAAqC,CAAA,CACjD,IAAMM,CAAAA,CAAO,MAAMH,CAAAA,CAAQ,IAAA,EAAK,CAIhC,GAHAH,CAAAA,CAAO,IAAA,CAAK,uBAAA,CAAyBM,CAAI,CAAA,CAGrCA,CAAAA,CAAK,MAAA,GAAW,2BAAA,CAA6B,CAC7C,IAAMC,CAAAA,CAAW,yCAAA,CACjB,OAAAP,CAAAA,CAAO,IAAA,CAAKO,CAAAA,CAAU,CAAE,IAAA,CAAAD,CAAK,CAAC,CAAA,CACvB,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,CAAE,MAAOC,CAAS,CAAC,CAAA,CAAG,CAAE,MAAA,CAAQ,GAAI,CAAC,CAC5E,CAEA,IAAMC,CAAAA,CAAmB,EAAC,CAG1B,IAAA,IAAWC,KAASH,CAAAA,CAAK,KAAA,CACrB,GAAI,CACAN,CAAAA,CAAO,IAAA,CAAK,2BAAA,CAA6B,CAAE,OAAA,CAASS,CAAAA,CAAM,EAAG,CAAC,CAAA,CAC9D,IAAMC,EAAUD,CAAAA,CAAM,OAAA,CACtB,IAAA,IAAWE,CAAAA,IAAUD,CAAAA,CACbC,CAAAA,CAAO,KAAA,GAAU,UAAA,GACjBX,CAAAA,CAAO,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BA,CAAAA,CAC1BtB,CAAAA,CAAO,GAAA,CAAI,iCAAiC,EAChD,CAEA,MAAA,CAAOgF,CAAAA,CAAoB1D,CAAAA,CAA4B,CACnD,IAAA,CAAK,YAAA,CAAa,GAAA,CAAI0D,CAAAA,CAAM1D,CAAO,CAAA,CACnCtB,EAAO,GAAA,CAAI,CAAA,4BAAA,EAA+BgF,CAAI,CAAA,CAAE,EACpD,CAEA,SAAA,EAAsB,CAClB,OAAO,IAAA,CAAK,MAChB,CAEA,SAAA,EAA4B,CACxB,OAAO,IAAA,CAAK,MAChB,CACJ","file":"chunk-JPGXONBQ.js","sourcesContent":["import crypto from 'crypto';\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n LOGGER.info('Processing webhook messages request');\n const body = await request.json();\n LOGGER.info('Webhook request body:', body);\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.warn(errorMsg, { body });\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n LOGGER.info('Processing webhook entry:', { entryId: entry.id });\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n LOGGER.info('Processing messages change:', { change });\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n LOGGER.info('Webhook processing complete', { errorCount: errors.length });\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n LOGGER.info('Processing flow request');\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n LOGGER.info('Flow request signature:', { signature });\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature', { signature });\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n LOGGER.info('Flow request data:', data);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n LOGGER.info('Decrypted flow request:', decryptedBody);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow action:', { action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n LOGGER.info('Handling flow ping request');\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.warn('Flow error request received:', decryptedBody);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n LOGGER.info('Processing flow data exchange request');\n const result = await handler(whatsapp, decryptedBody);\n LOGGER.info('Flow handler result:', result);\n\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n LOGGER.info('Encrypted flow response generated');\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n LOGGER.info('Signature verification details:', {\n bodyLength: body.length,\n verificationTokenLength: verificationToken.length,\n rawSignature: signature,\n cleanedSignature: signature.replace('sha256=', ''),\n });\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n LOGGER.info('Signature verification:', {\n received: signature.replace('sha256=', ''),\n expected: expectedSignature,\n });\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n LOGGER.info('Processing messages:', { waba_id, value });\n\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n LOGGER.info('Processing statuses:', { statusCount: value.statuses.length });\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n LOGGER.info('Processing status:', processedStatus);\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n LOGGER.info('Processing messages:', { messageCount: value.messages.length });\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n LOGGER.info('Processing message:', { messageType, messageId: message.id });\n\n const processedMessage: WebhookMessage = {\n wabaId,\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 switch (messageType) {\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 case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.warn('Unknown message type:', { messageType });\n break;\n }\n\n // Execute handlers in sequence\n LOGGER.info('Executing message handlers');\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n LOGGER.info('Executing handler:', { handlerType, messageId: message.id });\n await handler(whatsapp, message);\n LOGGER.info('Handler execution complete:', { handlerType, messageId: message.id });\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: message.id });\n }\n } else {\n LOGGER.info('No handler registered:', { handlerType });\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n LOGGER.error('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts"],"names":["LIB_NAME","LOGGER","Logger","processWebhookMessages","request","whatsapp","handlers","body","errorMsg","errors","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","signature","verifySignature","data","decryptedBody","decryptFlowRequest","handler","isFlowPingRequest","isFlowErrorRequest","isFlowDataExchangeRequest","result","encryptedResponse","encryptFlowResponse","verificationToken","expectedSignature","crypto","constructFullUrl","headers","url","protocol","host","waba_id","value","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookProcessor","importConfig","WhatsApp","mode","token","challenge","webResponse","contentType","type"],"mappings":"6JAUA,IAAMA,CAAAA,CAAW,eAAA,CACXC,CAAAA,CAAS,IAAIC,CAAAA,CAAOF,CAAAA,CAAU,OAAA,CAAQ,GAAA,CAAI,KAAA,GAAU,MAAM,EAQhE,eAAsBG,CAAAA,CAClBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAKiB,CACjB,GAAI,CACAL,CAAAA,CAAO,IAAA,CAAK,qCAAqC,CAAA,CACjD,IAAMM,CAAAA,CAAO,MAAMH,CAAAA,CAAQ,IAAA,EAAK,CAIhC,GAHAH,CAAAA,CAAO,IAAA,CAAK,uBAAA,CAAyBM,CAAI,CAAA,CAGrCA,CAAAA,CAAK,MAAA,GAAW,2BAAA,CAA6B,CAC7C,IAAMC,CAAAA,CAAW,yCAAA,CACjB,OAAAP,CAAAA,CAAO,IAAA,CAAKO,CAAAA,CAAU,CAAE,IAAA,CAAAD,CAAK,CAAC,CAAA,CACvB,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,CAAE,MAAOC,CAAS,CAAC,CAAA,CAAG,CAAE,MAAA,CAAQ,GAAI,CAAC,CAC5E,CAEA,IAAMC,CAAAA,CAAmB,EAAC,CAG1B,IAAA,IAAWC,KAASH,CAAAA,CAAK,KAAA,CACrB,GAAI,CACAN,CAAAA,CAAO,IAAA,CAAK,2BAAA,CAA6B,CAAE,OAAA,CAASS,CAAAA,CAAM,EAAG,CAAC,CAAA,CAC9D,IAAMC,EAAUD,CAAAA,CAAM,OAAA,CACtB,IAAA,IAAWE,CAAAA,IAAUD,CAAAA,CACbC,CAAAA,CAAO,KAAA,GAAU,UAAA,GACjBX,CAAAA,CAAO,IAAA,CAAK,6BAAA,CAA+B,CAAE,MAAA,CAAAW,CAAO,CAAC,CAAA,CACrD,MAAMC,CAAAA,CAAgBH,CAAAA,CAAM,EAAA,CAAIE,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AAA,CAAK,YAAA,CAAa,GAAA,CAAI0D,CAAAA,CAAM1D,CAAO,CAAA,CACnCtB,EAAO,GAAA,CAAI,CAAA,4BAAA,EAA+BgF,CAAI,CAAA,CAAE,EACpD,CAEA,SAAA,EAAsB,CAClB,OAAO,IAAA,CAAK,MAChB,CAEA,SAAA,EAA4B,CACxB,OAAO,IAAA,CAAK,MAChB,CACJ","file":"chunk-U5FBZ6UB.js","sourcesContent":["import crypto from 'crypto';\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n LOGGER.info('Processing webhook messages request');\n const body = await request.json();\n LOGGER.info('Webhook request body:', body);\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.warn(errorMsg, { body });\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n LOGGER.info('Processing webhook entry:', { entryId: entry.id });\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n LOGGER.info('Processing messages change:', { change });\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n LOGGER.info('Webhook processing complete', { errorCount: errors.length });\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n LOGGER.info('Processing flow request');\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n LOGGER.info('Flow request signature:', { signature });\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature', { signature });\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n LOGGER.info('Flow request data:', data);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n LOGGER.info('Decrypted flow request:', decryptedBody);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow action:', { action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n LOGGER.info('Handling flow ping request');\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.warn('Flow error request received:', decryptedBody);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n LOGGER.info('Processing flow data exchange request');\n const result = await handler(whatsapp, decryptedBody);\n LOGGER.info('Flow handler result:', result);\n\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n LOGGER.info('Encrypted flow response generated');\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n LOGGER.info('Signature verification details:', {\n bodyLength: body.length,\n verificationTokenLength: verificationToken.length,\n rawSignature: signature,\n cleanedSignature: signature.replace('sha256=', ''),\n });\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n LOGGER.info('Signature verification:', {\n received: signature.replace('sha256=', ''),\n expected: expectedSignature,\n });\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n LOGGER.info('Processing messages:', { waba_id, value });\n\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n LOGGER.info('Processing statuses:', { statusCount: value.statuses.length });\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n LOGGER.info('Processing status:', processedStatus);\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n LOGGER.info('Processing messages:', { messageCount: value.messages.length });\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n LOGGER.info('Processing message:', { messageType, messageId: message.id });\n\n const processedMessage: WebhookMessage = {\n wabaId,\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 switch (messageType) {\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 case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.warn('Unknown message type:', { messageType });\n break;\n }\n\n // Execute handlers in sequence\n LOGGER.info('Executing message handlers');\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n LOGGER.info('Executing handler:', { handlerType, messageId: message.id });\n await handler(whatsapp, message);\n LOGGER.info('Handler execution complete:', { handlerType, messageId: message.id });\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: message.id });\n }\n } else {\n LOGGER.info('No handler registered:', { handlerType });\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n LOGGER.error('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-5577QQ7V.js';var u=class extends a{constructor(e){super(e);}async handleGet(e,s,t){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":o}=e.query,a=await this.processVerification(n||null,r||null,o||null);return this.applyHeaders(a,s),s.status(a.status).send(a.body)}catch(n){return t(n),s}}async handlePost(e,s,t){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),o=await this.processWebhook(r);return this.applyHeaders(o,s),s.status(o.status).send(o.body)}catch(n){return t(n),s}}async handleFlow(e,s,t){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:e.method==="POST"?JSON.stringify(e.body):void 0}),o=await this.processFlow(r);return this.applyHeaders(o,s),s.status(o.status).send(o.body)}catch(n){return t(n),s}}getHandlers(){return {GET:(e,s,t)=>this.handleGet(e,s,t),POST:(e,s,t)=>this.handlePost(e,s,t),webhook:(e,s,t)=>this.autoRoute(e,s,t),flow:(e,s,t)=>this.handleFlow(e,s,t),processor:this.webhookProcessor}}};function x(i){return new u(i).getHandlers()}export{x as a};//# sourceMappingURL=chunk-ZMNXRMWK.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-ZMNXRMWK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/webhook/frameworks/express.ts"],"names":["ExpressWebhookHandler","BaseWebhookHandler","config","req","res","next","mode","token","challenge","result","error","fullUrl","webRequest","webhookHandler"],"mappings":"oCA8BA,IAAMA,CAAAA,CAAN,cAAoCC,CAAoD,CACpF,WAAA,CAAYC,CAAAA,CAA8B,CACtC,KAAA,CAAMA,CAAM,EAChB,CAEA,MAAgB,SAAA,CAAUC,CAAAA,CAAqBC,CAAAA,CAAsBC,CAAAA,CAA8C,CAC/G,GAAI,CACA,GAAM,CAAE,UAAA,CAAYC,CAAAA,CAAM,kBAAA,CAAoBC,CAAAA,CAAO,eAAA,CAAiBC,CAAU,CAAA,CAAIL,EAAI,KAAA,CAElFM,CAAAA,CAAS,MAAM,IAAA,CAAK,mBAAA,CACrBH,CAAAA,EAAmB,IAAA,CACnBC,CAAAA,EAAoB,IAAA,CACpBC,CAAAA,EAAwB,IAC7B,CAAA,CAEA,OAAA,IAAA,CAAK,YAAA,CAAaC,CAAAA,CAAQL,CAAG,EACtBA,CAAAA,CAAI,MAAA,CAAOK,CAAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAKA,CAAAA,CAAO,IAAI,CACrD,CAAA,MAASC,CAAAA,CAAO,CACZ,OAAAL,CAAAA,CAAKK,CAAK,CAAA,CACHN,CACX,CACJ,CAEA,MAAgB,UAAA,CACZD,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACwB,CACxB,GAAI,CACA,IAAMM,CAAAA,CAAU,IAAA,CAAK,gBAAA,CAAiBR,CAAAA,CAAI,OAAA,CAASA,EAAI,GAAG,CAAA,CACpDS,CAAAA,CAAa,IAAI,UAAA,CAA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,CACX,CACJ,CAEA,WAAA,EAAc,CACV,OAAO,CAEH,GAAA,CAAK,CAACD,CAAAA,CAAqBC,CAAAA,CAAsBC,CAAAA,GAAuB,IAAA,CAAK,SAAA,CAAUF,CAAAA,CAAKC,EAAKC,CAAI,CAAA,CACrG,IAAA,CAAM,CAACF,CAAAA,CAAqBC,CAAAA,CAAsBC,CAAAA,GAAuB,IAAA,CAAK,UAAA,CAAWF,CAAAA,CAAKC,CAAAA,CAAKC,CAAI,CAAA,CAGvG,OAAA,CAAS,CAACF,CAAAA,CAAqBC,EAAsBC,CAAAA,GAAuB,IAAA,CAAK,SAAA,CAAUF,CAAAA,CAAKC,CAAAA,CAAKC,CAAI,CAAA,CAGzG,IAAA,CAAM,CAACF,CAAAA,CAAqBC,CAAAA,CAAsBC,CAAAA,GAAuB,IAAA,CAAK,UAAA,CAAWF,CAAAA,CAAKC,CAAAA,CAAKC,CAAI,CAAA,CAGvG,SAAA,CAAW,IAAA,CAAK,gBACpB,CACJ,CACJ,CAAA,CAEO,SAASQ,CAAAA,CAAeX,CAAAA,CAA8B,CAEzD,OADgB,IAAIF,CAAAA,CAAsBE,CAAM,CAAA,CACjC,aACnB","file":"chunk-ZMNXRMWK.js","sourcesContent":["import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from './handler';\n\n// Express-like interfaces to avoid direct Express dependency\nexport interface ExpressRequest extends BaseRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Record<string, any>;\n rawBody?: any;\n}\n\nexport interface ExpressResponse extends BaseResponse<ExpressResponse> {\n status(code: number): ExpressResponse;\n json(data: any): ExpressResponse;\n send(data?: any): ExpressResponse;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextFunction {\n (error?: any): void;\n}\n\nexport interface ExpressWebhookConfig extends BaseWebhookConfig {\n path?: string;\n}\n\n/**\n * Express-specific webhook handler extending the base handler\n */\nclass ExpressWebhookHandler extends BaseWebhookHandler<ExpressRequest, ExpressResponse> {\n constructor(config: ExpressWebhookConfig) {\n super(config);\n }\n\n protected async handleGet(req: ExpressRequest, res: ExpressResponse, next: NextFunction): Promise<ExpressResponse> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n protected async handlePost(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<ExpressResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n protected async handleFlow(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<ExpressResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleGet(req, res, next),\n POST: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handlePost(req, res, next),\n\n // Auto-routing webhook handler\n webhook: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.autoRoute(req, res, next),\n\n // Flow handler\n flow: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleFlow(req, res, next),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\nexport function webhookHandler(config: ExpressWebhookConfig) {\n const handler = new ExpressWebhookHandler(config);\n return handler.getHandlers();\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as BaseWebhookConfig, a as BaseRequest, b as BaseResponse } from '../../../handler-DbySwF0E.js';
|
|
2
2
|
import { c as WebhookProcessor } from '../../../WebhookProcessor-BXYunz4N.js';
|
|
3
|
+
import '../../../types/config.js';
|
|
3
4
|
import '../../../enums-BZd9T2ul.js';
|
|
4
5
|
import '../../../common-lV0NsO7t.js';
|
|
5
6
|
import '../../../request-vYMaEfk5.js';
|
|
@@ -20,7 +21,7 @@ import '../../../TemplateApi-xGgIZt89.js';
|
|
|
20
21
|
import '../../../TwoStepVerificationApi-DfNPIz-C.js';
|
|
21
22
|
import '../../../WabaApi-DqQi_68m.js';
|
|
22
23
|
|
|
23
|
-
interface ExpressRequest {
|
|
24
|
+
interface ExpressRequest extends BaseRequest {
|
|
24
25
|
method: string;
|
|
25
26
|
url: string;
|
|
26
27
|
headers: Record<string, string | string[] | undefined>;
|
|
@@ -28,7 +29,7 @@ interface ExpressRequest {
|
|
|
28
29
|
query: Record<string, any>;
|
|
29
30
|
rawBody?: any;
|
|
30
31
|
}
|
|
31
|
-
interface ExpressResponse {
|
|
32
|
+
interface ExpressResponse extends BaseResponse<ExpressResponse> {
|
|
32
33
|
status(code: number): ExpressResponse;
|
|
33
34
|
json(data: any): ExpressResponse;
|
|
34
35
|
send(data?: any): ExpressResponse;
|
|
@@ -37,12 +38,14 @@ interface ExpressResponse {
|
|
|
37
38
|
interface NextFunction {
|
|
38
39
|
(error?: any): void;
|
|
39
40
|
}
|
|
40
|
-
interface ExpressWebhookConfig extends
|
|
41
|
+
interface ExpressWebhookConfig extends BaseWebhookConfig {
|
|
41
42
|
path?: string;
|
|
42
43
|
}
|
|
43
44
|
declare function webhookHandler(config: ExpressWebhookConfig): {
|
|
44
|
-
|
|
45
|
-
|
|
45
|
+
GET: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => Promise<ExpressResponse>;
|
|
46
|
+
POST: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => Promise<ExpressResponse>;
|
|
47
|
+
webhook: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => Promise<any>;
|
|
48
|
+
flow: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => Promise<ExpressResponse>;
|
|
46
49
|
processor: WebhookProcessor;
|
|
47
50
|
};
|
|
48
51
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as webhookHandler}from'../../../chunk-
|
|
1
|
+
export{a as webhookHandler}from'../../../chunk-ZMNXRMWK.js';import'../../../chunk-5577QQ7V.js';import'../../../chunk-U5FBZ6UB.js';import'../../../chunk-6DFC5L3X.js';import'../../../chunk-BAOZ4U74.js';import'../../../chunk-FKXSL2JK.js';import'../../../chunk-AMHQGG6Z.js';import'../../../chunk-VHAODWCN.js';import'../../../chunk-JPAV644F.js';import'../../../chunk-PHPQ5HP3.js';import'../../../chunk-IYSR44P6.js';import'../../../chunk-SNNRWNGZ.js';import'../../../chunk-L4ESAO2S.js';import'../../../chunk-7QBIZCJ4.js';import'../../../chunk-JXCLRKQ7.js';import'../../../chunk-LV3TULSI.js';import'../../../chunk-CRZ7EUYR.js';import'../../../chunk-JC6YMVID.js';import'../../../chunk-NLF2JGYY.js';import'../../../chunk-FSKBLPGE.js';import'../../../chunk-MJEG3K4V.js';import'../../../chunk-RIL6QABY.js';import'../../../chunk-KMAH6636.js';//# sourceMappingURL=express.js.map
|
|
2
2
|
//# sourceMappingURL=express.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { WhatsAppConfig } from '../../../types/config.js';
|
|
2
|
+
import { c as WebhookProcessor } from '../../../WebhookProcessor-BXYunz4N.js';
|
|
3
|
+
import '../../../enums-BZd9T2ul.js';
|
|
4
|
+
import '../../../common-lV0NsO7t.js';
|
|
5
|
+
import '../../../request-vYMaEfk5.js';
|
|
6
|
+
import '../../../WhatsApp-pTZPQm81.js';
|
|
7
|
+
import '../../../httpsClient-v4gmltzS.js';
|
|
8
|
+
import 'https';
|
|
9
|
+
import '../../../EncryptionApi-D7pt-OXT.js';
|
|
10
|
+
import '../../../base-CdGDdVEl.js';
|
|
11
|
+
import '../../../FlowApi-B2ffO-HD.js';
|
|
12
|
+
import '../../../MediaApi-BrEKpqi_.js';
|
|
13
|
+
import '../../../MessageApi-BgsSpDno.js';
|
|
14
|
+
import '../../../common-BiRA_uz3.js';
|
|
15
|
+
import '../../../PhoneNumberApi-DKlu9PHl.js';
|
|
16
|
+
import '../../../BusinessProfileApi-WXscSgo-.js';
|
|
17
|
+
import '../../../QrCodeApi-7vDwIBHR.js';
|
|
18
|
+
import '../../../RegistrationApi-qO_qoti9.js';
|
|
19
|
+
import '../../../TemplateApi-xGgIZt89.js';
|
|
20
|
+
import '../../../TwoStepVerificationApi-DfNPIz-C.js';
|
|
21
|
+
import '../../../WabaApi-DqQi_68m.js';
|
|
22
|
+
|
|
23
|
+
interface NextRequest extends Request {
|
|
24
|
+
nextUrl: {
|
|
25
|
+
searchParams: URLSearchParams;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
interface NextResponse {
|
|
29
|
+
json(data: any): NextResponse;
|
|
30
|
+
}
|
|
31
|
+
interface NextJsAppWebhookConfig extends WhatsAppConfig {
|
|
32
|
+
}
|
|
33
|
+
declare function webhookHandler(config: NextJsAppWebhookConfig): {
|
|
34
|
+
GET: (request: NextRequest) => Promise<Response>;
|
|
35
|
+
POST: (request: NextRequest) => Promise<Response>;
|
|
36
|
+
webhook: {
|
|
37
|
+
GET: (request: NextRequest) => Promise<Response>;
|
|
38
|
+
POST: (request: NextRequest) => Promise<Response>;
|
|
39
|
+
};
|
|
40
|
+
flow: {
|
|
41
|
+
GET: (request: NextRequest) => Promise<Response>;
|
|
42
|
+
POST: (request: NextRequest) => Promise<Response>;
|
|
43
|
+
};
|
|
44
|
+
processor: WebhookProcessor;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export { type NextJsAppWebhookConfig, type NextRequest, type NextResponse, webhookHandler };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {d}from'../../../chunk-U5FBZ6UB.js';import'../../../chunk-6DFC5L3X.js';import'../../../chunk-BAOZ4U74.js';import'../../../chunk-FKXSL2JK.js';import'../../../chunk-AMHQGG6Z.js';import'../../../chunk-VHAODWCN.js';import'../../../chunk-JPAV644F.js';import'../../../chunk-PHPQ5HP3.js';import'../../../chunk-IYSR44P6.js';import'../../../chunk-SNNRWNGZ.js';import'../../../chunk-L4ESAO2S.js';import'../../../chunk-7QBIZCJ4.js';import'../../../chunk-JXCLRKQ7.js';import'../../../chunk-LV3TULSI.js';import'../../../chunk-CRZ7EUYR.js';import'../../../chunk-JC6YMVID.js';import'../../../chunk-NLF2JGYY.js';import'../../../chunk-FSKBLPGE.js';import'../../../chunk-MJEG3K4V.js';import'../../../chunk-RIL6QABY.js';import'../../../chunk-KMAH6636.js';function p(u){let s=new d(u);return {GET:async r=>{try{let{searchParams:e}=new URL(r.url),o=e.get("hub.mode"),n=e.get("hub.verify_token"),a=e.get("hub.challenge"),t=await s.processVerification(o,n,a);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error("Webhook verification error:",e),new Response("Internal Server Error",{status:500})}},POST:async r=>{try{let e=await s.processWebhook(r);return new Response(e.body,{status:e.status,headers:e.headers})}catch(e){return console.error("Webhook processing error:",e),new Response("Internal Server Error",{status:500})}},webhook:{GET:async r=>{try{let{searchParams:e}=new URL(r.url),o=e.get("hub.mode"),n=e.get("hub.verify_token"),a=e.get("hub.challenge"),t=await s.processVerification(o,n,a);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error("Webhook verification error:",e),new Response("Internal Server Error",{status:500})}},POST:async r=>{try{let e=await s.processWebhook(r);return new Response(e.body,{status:e.status,headers:e.headers})}catch(e){return console.error("Webhook processing error:",e),new Response("Internal Server Error",{status:500})}}},flow:{GET:async r=>{try{let e=await s.processFlow(r);return Response.json(e.body,{status:e.status,headers:e.headers})}catch(e){return console.error("Flow GET error:",e),new Response("Internal Server Error",{status:500})}},POST:async r=>{try{let e=await s.processFlow(r);return Response.json(e.body,{status:e.status,headers:e.headers})}catch(e){return console.error("Flow POST error:",e),new Response("Internal Server Error",{status:500})}}},processor:s}}export{p as webhookHandler};//# sourceMappingURL=nextjs-app.js.map
|
|
2
|
+
//# sourceMappingURL=nextjs-app.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/core/webhook/frameworks/nextjs-app.ts"],"names":["webhookHandler","config","processor","WebhookProcessor","request","searchParams","mode","token","challenge","result","error"],"mappings":"uuBAkBO,SAASA,EAAeC,CAAAA,CAAgC,CAC3D,IAAMC,CAAAA,CAAY,IAAIC,CAAAA,CAAiBF,CAAM,CAAA,CAE7C,OAAO,CAEH,GAAA,CAAK,MAAOG,GAAyB,CACjC,GAAI,CACA,GAAM,CAAE,YAAA,CAAAC,CAAa,EAAI,IAAI,GAAA,CAAID,EAAQ,GAAG,CAAA,CACtCE,EAAOD,CAAAA,CAAa,GAAA,CAAI,UAAU,CAAA,CAClCE,EAAQF,CAAAA,CAAa,GAAA,CAAI,kBAAkB,CAAA,CAC3CG,CAAAA,CAAYH,EAAa,GAAA,CAAI,eAAe,CAAA,CAE5CI,CAAAA,CAAS,MAAMP,CAAAA,CAAU,mBAAA,CAAoBI,CAAAA,CAAMC,CAAAA,CAAOC,CAAS,CAAA,CAGzE,OAAO,IAAI,QAAA,CAASC,EAAO,IAAA,CAAM,CAC7B,OAAQA,CAAAA,CAAO,MAAA,CACf,QAASA,CAAAA,CAAO,OACpB,CAAC,CACL,OAASC,CAAAA,CAAO,CACZ,eAAQ,KAAA,CAAM,6BAAA,CAA+BA,CAAK,CAAA,CAC3C,IAAI,QAAA,CAAS,uBAAA,CAAyB,CAAE,MAAA,CAAQ,GAA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,IAAA,CAAM,CAC7B,MAAA,CAAQA,EAAO,MAAA,CACf,OAAA,CAASA,CAAAA,CAAO,OACpB,CAAC,CACL,CAAA,MAASC,EAAO,CACZ,OAAA,OAAA,CAAQ,MAAM,2BAAA,CAA6BA,CAAK,CAAA,CACzC,IAAI,SAAS,uBAAA,CAAyB,CAAE,OAAQ,GAAI,CAAC,CAChE,CACJ,CACJ,CAAA,CAGA,IAAA,CAAM,CACF,GAAA,CAAK,MAAON,GAAyB,CACjC,GAAI,CACA,IAAMK,CAAAA,CAAS,MAAMP,CAAAA,CAAU,YAAYE,CAAO,CAAA,CAElD,OAAO,QAAA,CAAS,KAAKK,CAAAA,CAAO,IAAA,CAAM,CAC9B,MAAA,CAAQA,EAAO,MAAA,CACf,OAAA,CAASA,EAAO,OACpB,CAAC,CACL,CAAA,MAASC,CAAAA,CAAO,CACZ,OAAA,OAAA,CAAQ,MAAM,iBAAA,CAAmBA,CAAK,EAC/B,IAAI,QAAA,CAAS,wBAAyB,CAAE,MAAA,CAAQ,GAAI,CAAC,CAChE,CACJ,CAAA,CAEA,KAAM,MAAON,CAAAA,EAAyB,CAClC,GAAI,CACA,IAAMK,CAAAA,CAAS,MAAMP,CAAAA,CAAU,WAAA,CAAYE,CAAO,CAAA,CAElD,OAAO,SAAS,IAAA,CAAKK,CAAAA,CAAO,IAAA,CAAM,CAC9B,OAAQA,CAAAA,CAAO,MAAA,CACf,QAASA,CAAAA,CAAO,OACpB,CAAC,CACL,CAAA,MAASC,CAAAA,CAAO,CACZ,eAAQ,KAAA,CAAM,kBAAA,CAAoBA,CAAK,CAAA,CAChC,IAAI,SAAS,uBAAA,CAAyB,CAAE,MAAA,CAAQ,GAAI,CAAC,CAChE,CACJ,CACJ,CAAA,CAGA,SAAA,CAAAR,CACJ,CACJ","file":"nextjs-app.js","sourcesContent":["import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\n\n// Define Next.js types locally to avoid requiring Next.js as a dependency\nexport interface NextRequest extends Request {\n nextUrl: {\n searchParams: URLSearchParams;\n };\n}\n\nexport interface NextResponse {\n json(data: any): NextResponse;\n}\n\nexport interface NextJsAppWebhookConfig extends WhatsAppConfig {\n // App Router specific config (currently none, but interface reserved for future use)\n}\n\nexport function webhookHandler(config: NextJsAppWebhookConfig) {\n const processor = new WebhookProcessor(config);\n\n return {\n // Clean GET/POST handlers following whatsapp-api-js methodology\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n\n // Return plain text response for webhook verification\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n\n // Return JSON response for webhook processing\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n // Legacy webhook object for backward compatibility\n webhook: {\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n },\n\n // Flow handler for App Router\n flow: {\n GET: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n return Response.json(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow GET error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n return Response.json(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow POST error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n },\n\n // Expose processor for handler registration\n processor,\n };\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as BaseRequest, b as BaseResponse, B as BaseWebhookConfig } from '../../../handler-DbySwF0E.js';
|
|
2
2
|
import { c as WebhookProcessor } from '../../../WebhookProcessor-BXYunz4N.js';
|
|
3
|
+
import '../../../types/config.js';
|
|
3
4
|
import '../../../enums-BZd9T2ul.js';
|
|
4
5
|
import '../../../common-lV0NsO7t.js';
|
|
5
6
|
import '../../../request-vYMaEfk5.js';
|
|
@@ -20,7 +21,7 @@ import '../../../TemplateApi-xGgIZt89.js';
|
|
|
20
21
|
import '../../../TwoStepVerificationApi-DfNPIz-C.js';
|
|
21
22
|
import '../../../WabaApi-DqQi_68m.js';
|
|
22
23
|
|
|
23
|
-
interface BaseApiRequest {
|
|
24
|
+
interface BaseApiRequest extends BaseRequest {
|
|
24
25
|
method?: string;
|
|
25
26
|
url?: string;
|
|
26
27
|
headers: Record<string, string | string[] | undefined>;
|
|
@@ -28,15 +29,17 @@ interface BaseApiRequest {
|
|
|
28
29
|
query: Partial<Record<string, string | string[]>>;
|
|
29
30
|
rawBody?: any;
|
|
30
31
|
}
|
|
31
|
-
interface BaseApiResponse {
|
|
32
|
+
interface BaseApiResponse extends BaseResponse {
|
|
32
33
|
status(code: number): any;
|
|
33
34
|
json(data: any): void | any;
|
|
34
35
|
send(data?: any): void | any;
|
|
35
36
|
setHeader(name: string, value: string): void;
|
|
36
37
|
}
|
|
37
|
-
interface NextJsWebhookConfig extends
|
|
38
|
+
interface NextJsWebhookConfig extends BaseWebhookConfig {
|
|
38
39
|
}
|
|
39
40
|
declare function webhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(config: NextJsWebhookConfig): {
|
|
41
|
+
GET: (req: TRequest, res: TResponse) => Promise<any>;
|
|
42
|
+
POST: (req: TRequest, res: TResponse) => Promise<any>;
|
|
40
43
|
webhook: (req: TRequest, res: TResponse) => Promise<any>;
|
|
41
44
|
flow: (req: TRequest, res: TResponse) => Promise<any>;
|
|
42
45
|
processor: WebhookProcessor;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as webhookHandler}from'../../../chunk-
|
|
1
|
+
export{a as webhookHandler}from'../../../chunk-GM63NGNV.js';import'../../../chunk-5577QQ7V.js';import'../../../chunk-U5FBZ6UB.js';import'../../../chunk-6DFC5L3X.js';import'../../../chunk-BAOZ4U74.js';import'../../../chunk-FKXSL2JK.js';import'../../../chunk-AMHQGG6Z.js';import'../../../chunk-VHAODWCN.js';import'../../../chunk-JPAV644F.js';import'../../../chunk-PHPQ5HP3.js';import'../../../chunk-IYSR44P6.js';import'../../../chunk-SNNRWNGZ.js';import'../../../chunk-L4ESAO2S.js';import'../../../chunk-7QBIZCJ4.js';import'../../../chunk-JXCLRKQ7.js';import'../../../chunk-LV3TULSI.js';import'../../../chunk-CRZ7EUYR.js';import'../../../chunk-JC6YMVID.js';import'../../../chunk-NLF2JGYY.js';import'../../../chunk-FSKBLPGE.js';import'../../../chunk-MJEG3K4V.js';import'../../../chunk-RIL6QABY.js';import'../../../chunk-KMAH6636.js';//# sourceMappingURL=nextjs.js.map
|
|
2
2
|
//# sourceMappingURL=nextjs.js.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { ExpressRequest, ExpressResponse, webhookHandler as ExpressWebhook, ExpressWebhookConfig, NextFunction } from './frameworks/express.js';
|
|
2
2
|
export { webhookHandler as NextJsWebhook, NextJsWebhookConfig } from './frameworks/nextjs.js';
|
|
3
3
|
export { F as FlowHandler, e as MessageHandler, M as MessageStatus, W as WebhookContact, a as WebhookEvent, b as WebhookMessage, c as WebhookProcessor, d as WebhookResponse, g as constructFullUrl, f as processFlowRequest, p as processWebhookMessages } from '../../WebhookProcessor-BXYunz4N.js';
|
|
4
|
+
import '../../handler-DbySwF0E.js';
|
|
4
5
|
import '../../types/config.js';
|
|
5
6
|
import '../../enums-BZd9T2ul.js';
|
|
6
7
|
import '../../common-lV0NsO7t.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as generateXHub256Sig}from'../../chunk-RWCVPWRC.js';export{a as ExpressWebhook}from'../../chunk-
|
|
1
|
+
export{a as generateXHub256Sig}from'../../chunk-RWCVPWRC.js';export{a as ExpressWebhook}from'../../chunk-ZMNXRMWK.js';export{a as NextJsWebhook}from'../../chunk-GM63NGNV.js';import'../../chunk-5577QQ7V.js';export{d as WebhookProcessor,c as constructFullUrl,b as processFlowRequest,a as processWebhookMessages}from'../../chunk-U5FBZ6UB.js';import'../../chunk-6DFC5L3X.js';import'../../chunk-BAOZ4U74.js';import'../../chunk-FKXSL2JK.js';import'../../chunk-AMHQGG6Z.js';import'../../chunk-VHAODWCN.js';import'../../chunk-JPAV644F.js';import'../../chunk-PHPQ5HP3.js';import'../../chunk-IYSR44P6.js';import'../../chunk-SNNRWNGZ.js';import'../../chunk-L4ESAO2S.js';import'../../chunk-7QBIZCJ4.js';import'../../chunk-JXCLRKQ7.js';import'../../chunk-LV3TULSI.js';import'../../chunk-CRZ7EUYR.js';import'../../chunk-JC6YMVID.js';import'../../chunk-NLF2JGYY.js';import'../../chunk-FSKBLPGE.js';import'../../chunk-MJEG3K4V.js';import'../../chunk-RIL6QABY.js';import'../../chunk-KMAH6636.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { WhatsAppConfig } from './types/config.js';
|
|
2
|
+
|
|
3
|
+
interface BaseRequest {
|
|
4
|
+
method?: string;
|
|
5
|
+
url?: string;
|
|
6
|
+
headers: Record<string, string | string[] | undefined>;
|
|
7
|
+
body?: any;
|
|
8
|
+
query?: Record<string, any> | URLSearchParams;
|
|
9
|
+
rawBody?: any;
|
|
10
|
+
}
|
|
11
|
+
interface BaseResponse<T = any> {
|
|
12
|
+
status(code: number): T;
|
|
13
|
+
json?(data: any): T | void;
|
|
14
|
+
send?(data?: any): T | void;
|
|
15
|
+
setHeader?(name: string, value: string): void;
|
|
16
|
+
}
|
|
17
|
+
interface BaseWebhookConfig extends WhatsAppConfig {
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type { BaseWebhookConfig as B, BaseRequest as a, BaseResponse as b };
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import'./chunk-RWCVPWRC.js';export{a as ExpressWebhook}from'./chunk-
|
|
1
|
+
import'./chunk-RWCVPWRC.js';export{a as ExpressWebhook}from'./chunk-ZMNXRMWK.js';export{a as NextJsWebhook}from'./chunk-GM63NGNV.js';import'./chunk-5577QQ7V.js';import'./chunk-U5FBZ6UB.js';export{a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'./chunk-6DFC5L3X.js';export{b as WhatsApp,b as WhatsAppLegacy}from'./chunk-BAOZ4U74.js';export{c as isMetaError}from'./chunk-FKXSL2JK.js';import'./chunk-AMHQGG6Z.js';export{a as TemplateApi}from'./chunk-VHAODWCN.js';import'./chunk-JPAV644F.js';import'./chunk-PHPQ5HP3.js';import'./chunk-IYSR44P6.js';export{b as TwoStepVerificationApi}from'./chunk-SNNRWNGZ.js';import'./chunk-L4ESAO2S.js';export{b as MessagesApi}from'./chunk-7QBIZCJ4.js';export{b as MediaApi}from'./chunk-JXCLRKQ7.js';export{b as BusinessProfileApi}from'./chunk-LV3TULSI.js';import'./chunk-CRZ7EUYR.js';export{b as FlowApi}from'./chunk-JC6YMVID.js';export{a as FlowTypeEnum}from'./chunk-NLF2JGYY.js';export{b as PhoneNumberApi}from'./chunk-FSKBLPGE.js';import'./chunk-MJEG3K4V.js';import'./chunk-RIL6QABY.js';export{i as ComponentTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum}from'./chunk-KMAH6636.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/utils/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'../chunk-
|
|
1
|
+
export{a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'../chunk-6DFC5L3X.js';export{a as Logger,b as formatConfigTable,e as getUserAgent,d as getVersion,c as isMetaError}from'../chunk-FKXSL2JK.js';export{a as buildFieldsQueryString}from'../chunk-CRZ7EUYR.js';import'../chunk-NLF2JGYY.js';export{a as objectToQueryString}from'../chunk-MJEG3K4V.js';import'../chunk-KMAH6636.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "meta-cloud-api",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "TypeScript wrapper for Meta's Cloud API",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -15,95 +15,70 @@
|
|
|
15
15
|
"import": "./dist/index.js",
|
|
16
16
|
"default": "./dist/index.js"
|
|
17
17
|
},
|
|
18
|
-
"./
|
|
18
|
+
"./api": {
|
|
19
|
+
"types": "./dist/api/index.d.ts",
|
|
20
|
+
"import": "./dist/api/index.js",
|
|
21
|
+
"default": "./dist/api/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./api/messages": {
|
|
19
24
|
"types": "./dist/api/messages/index.d.ts",
|
|
20
25
|
"import": "./dist/api/messages/index.js",
|
|
21
26
|
"default": "./dist/api/messages/index.js"
|
|
22
27
|
},
|
|
23
|
-
"./
|
|
28
|
+
"./api/messages/builders": {
|
|
29
|
+
"types": "./dist/api/messages/builders/index.d.ts",
|
|
30
|
+
"import": "./dist/api/messages/builders/index.js",
|
|
31
|
+
"default": "./dist/api/messages/builders/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./api/media": {
|
|
24
34
|
"types": "./dist/api/media/index.d.ts",
|
|
25
35
|
"import": "./dist/api/media/index.js",
|
|
26
36
|
"default": "./dist/api/media/index.js"
|
|
27
37
|
},
|
|
28
|
-
"./
|
|
29
|
-
"types": "./dist/api/profile/index.d.ts",
|
|
30
|
-
"import": "./dist/api/profile/index.js",
|
|
31
|
-
"default": "./dist/api/profile/index.js"
|
|
32
|
-
},
|
|
33
|
-
"./flow": {
|
|
38
|
+
"./api/flow": {
|
|
34
39
|
"types": "./dist/api/flow/index.d.ts",
|
|
35
40
|
"import": "./dist/api/flow/index.js",
|
|
36
41
|
"default": "./dist/api/flow/index.js"
|
|
37
42
|
},
|
|
38
|
-
"./phone": {
|
|
43
|
+
"./api/phone": {
|
|
39
44
|
"types": "./dist/api/phone/index.d.ts",
|
|
40
45
|
"import": "./dist/api/phone/index.js",
|
|
41
46
|
"default": "./dist/api/phone/index.js"
|
|
42
47
|
},
|
|
43
|
-
"./
|
|
48
|
+
"./api/profile": {
|
|
49
|
+
"types": "./dist/api/profile/index.d.ts",
|
|
50
|
+
"import": "./dist/api/profile/index.js",
|
|
51
|
+
"default": "./dist/api/profile/index.js"
|
|
52
|
+
},
|
|
53
|
+
"./api/template": {
|
|
44
54
|
"types": "./dist/api/template/index.d.ts",
|
|
45
55
|
"import": "./dist/api/template/index.js",
|
|
46
56
|
"default": "./dist/api/template/index.js"
|
|
47
57
|
},
|
|
48
|
-
"./
|
|
49
|
-
"types": "./dist/api/waba/index.d.ts",
|
|
50
|
-
"import": "./dist/api/waba/index.js",
|
|
51
|
-
"default": "./dist/api/waba/index.js"
|
|
52
|
-
},
|
|
53
|
-
"./qrCode": {
|
|
58
|
+
"./api/qrCode": {
|
|
54
59
|
"types": "./dist/api/qrCode/index.d.ts",
|
|
55
60
|
"import": "./dist/api/qrCode/index.js",
|
|
56
61
|
"default": "./dist/api/qrCode/index.js"
|
|
57
62
|
},
|
|
58
|
-
"./
|
|
59
|
-
"types": "./dist/api/twoStepVerification/index.d.ts",
|
|
60
|
-
"import": "./dist/api/twoStepVerification/index.js",
|
|
61
|
-
"default": "./dist/api/twoStepVerification/index.js"
|
|
62
|
-
},
|
|
63
|
-
"./encryption": {
|
|
64
|
-
"types": "./dist/api/encryption/index.d.ts",
|
|
65
|
-
"import": "./dist/api/encryption/index.js",
|
|
66
|
-
"default": "./dist/api/encryption/index.js"
|
|
67
|
-
},
|
|
68
|
-
"./registration": {
|
|
63
|
+
"./api/registration": {
|
|
69
64
|
"types": "./dist/api/registration/index.d.ts",
|
|
70
65
|
"import": "./dist/api/registration/index.js",
|
|
71
66
|
"default": "./dist/api/registration/index.js"
|
|
72
67
|
},
|
|
73
|
-
"./
|
|
74
|
-
"types": "./dist/
|
|
75
|
-
"import": "./dist/
|
|
76
|
-
"default": "./dist/
|
|
77
|
-
},
|
|
78
|
-
"./shared/utils": {
|
|
79
|
-
"types": "./dist/shared/utils/index.d.ts",
|
|
80
|
-
"import": "./dist/shared/utils/index.js",
|
|
81
|
-
"default": "./dist/shared/utils/index.js"
|
|
82
|
-
},
|
|
83
|
-
"./api": {
|
|
84
|
-
"types": "./dist/api/index.d.ts",
|
|
85
|
-
"import": "./dist/api/index.js",
|
|
86
|
-
"default": "./dist/api/index.js"
|
|
87
|
-
},
|
|
88
|
-
"./api/messages": {
|
|
89
|
-
"types": "./dist/api/messages.d.ts",
|
|
90
|
-
"import": "./dist/api/messages.js",
|
|
91
|
-
"default": "./dist/api/messages.js"
|
|
92
|
-
},
|
|
93
|
-
"./api/messages/builders": {
|
|
94
|
-
"types": "./dist/api/messages/builders/index.d.ts",
|
|
95
|
-
"import": "./dist/api/messages/builders/index.js",
|
|
96
|
-
"default": "./dist/api/messages/builders/index.js"
|
|
68
|
+
"./api/encryption": {
|
|
69
|
+
"types": "./dist/api/encryption/index.d.ts",
|
|
70
|
+
"import": "./dist/api/encryption/index.js",
|
|
71
|
+
"default": "./dist/api/encryption/index.js"
|
|
97
72
|
},
|
|
98
|
-
"./api/
|
|
99
|
-
"types": "./dist/api/
|
|
100
|
-
"import": "./dist/api/
|
|
101
|
-
"default": "./dist/api/
|
|
73
|
+
"./api/twoStepVerification": {
|
|
74
|
+
"types": "./dist/api/twoStepVerification/index.d.ts",
|
|
75
|
+
"import": "./dist/api/twoStepVerification/index.js",
|
|
76
|
+
"default": "./dist/api/twoStepVerification/index.js"
|
|
102
77
|
},
|
|
103
|
-
"./api/
|
|
104
|
-
"types": "./dist/api/
|
|
105
|
-
"import": "./dist/api/
|
|
106
|
-
"default": "./dist/api/
|
|
78
|
+
"./api/waba": {
|
|
79
|
+
"types": "./dist/api/waba/index.d.ts",
|
|
80
|
+
"import": "./dist/api/waba/index.js",
|
|
81
|
+
"default": "./dist/api/waba/index.js"
|
|
107
82
|
},
|
|
108
83
|
"./utils": {
|
|
109
84
|
"types": "./dist/utils/index.d.ts",
|
|
@@ -125,6 +100,11 @@
|
|
|
125
100
|
"import": "./dist/core/webhook/frameworks/nextjs.js",
|
|
126
101
|
"default": "./dist/core/webhook/frameworks/nextjs.js"
|
|
127
102
|
},
|
|
103
|
+
"./webhook/nextjs-app": {
|
|
104
|
+
"types": "./dist/core/webhook/frameworks/nextjs-app.d.ts",
|
|
105
|
+
"import": "./dist/core/webhook/frameworks/nextjs-app.js",
|
|
106
|
+
"default": "./dist/core/webhook/frameworks/nextjs-app.js"
|
|
107
|
+
},
|
|
128
108
|
"./types": {
|
|
129
109
|
"types": "./dist/types/index.d.ts",
|
|
130
110
|
"import": "./dist/types/index.js",
|
package/dist/chunk-NOJFGTRT.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {d,c}from'./chunk-JPGXONBQ.js';function b(h){let d$1=new d(h);return {webhook:async(e,r,i)=>{try{if(e.method==="GET"){let{"hub.mode":s,"hub.verify_token":n,"hub.challenge":t}=e.query,o=await d$1.processVerification(s||null,n||null,t||null);return Object.entries(o.headers).forEach(([a,l])=>{r.setHeader(a,l);}),r.status(o.status).send(o.body)}if(e.method==="POST"){let s=c(e.headers,e.url),n=new globalThis.Request(s,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),t=await d$1.processWebhook(n);return Object.entries(t.headers).forEach(([o,a])=>{r.setHeader(o,a);}),r.status(t.status).send(t.body)}return r.status(405).json({error:"Method Not Allowed"})}catch(s){i(s);return}},flow:async(e,r,i)=>{try{let s=c(e.headers,e.url),n=new globalThis.Request(s,{method:e.method,headers:e.headers,body:e.method==="POST"?JSON.stringify(e.body):void 0}),t=await d$1.processFlow(n);return Object.entries(t.headers).forEach(([o,a])=>{r.setHeader(o,a);}),r.status(t.status).send(t.body)}catch(s){i(s);return}},processor:d$1}}export{b as a};//# sourceMappingURL=chunk-NOJFGTRT.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-NOJFGTRT.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/webhook/frameworks/express.ts"],"names":["webhookHandler","config","processor","WebhookProcessor","req","res","next","mode","token","challenge","result","key","value","fullUrl","constructFullUrl","webRequest","error"],"mappings":"sCA6BO,SAASA,CAAAA,CAAeC,CAAAA,CAA8B,CACzD,IAAMC,GAAAA,CAAY,IAAIC,CAAAA,CAAiBF,CAAM,CAAA,CAE7C,OAAO,CAEH,OAAA,CAAS,MAAOG,CAAAA,CAAqBC,CAAAA,CAAsBC,CAAAA,GAAuB,CAC9E,GAAI,CACA,GAAIF,CAAAA,CAAI,MAAA,GAAW,KAAA,CAAO,CACtB,GAAM,CAAE,UAAA,CAAYG,CAAAA,CAAM,kBAAA,CAAoBC,CAAAA,CAAO,eAAA,C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,CAAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,CAAE,KAAA,CAAO,oBAAqB,CAAC,CAC/D,CAAA,MAASW,CAAAA,CAAO,CACZV,CAAAA,CAAKU,CAAK,CAAA,CACV,MACJ,CACJ,CAAA,CAGA,IAAA,CAAM,MAAOZ,CAAAA,CAAqBC,CAAAA,CAAsBC,CAAAA,GAAuB,CAC3E,GAAI,CAEA,IAAMO,CAAAA,CAAUC,CAAAA,CAAiBV,CAAAA,CAAI,OAAA,CAASA,CAAAA,CAAI,GAAG,CAAA,CAC/CW,CAAAA,CAAa,IAAI,UAAA,CAAW,OAAA,CAAQF,CAAAA,CAAS,CAC/C,MAAA,CAAQT,CAAAA,CAAI,OACZ,OAAA,CAASA,CAAAA,CAAI,OAAA,CACb,IAAA,CAAMA,CAAAA,CAAI,MAAA,GAAW,MAAA,CAAS,IAAA,CAAK,SAAA,CAAUA,CAAAA,CAAI,IAAI,CAAA,CAAI,KAAA,CAC7D,CAAC,CAAA,CAEKM,CAAAA,CAAS,MAAMR,GAAAA,CAAU,WAAA,CAAYa,CAAU,CAAA,CAErD,OAAA,MAAA,CAAO,OAAA,CAAQL,CAAAA,CAAO,OAAO,CAAA,CAAE,OAAA,CAAQ,CAAC,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAM,CACrDP,CAAAA,CAAI,SAAA,CAAUM,CAAAA,CAAKC,CAAK,EAC5B,CAAC,CAAA,CAEMP,CAAAA,CAAI,MAAA,CAAOK,CAAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAKA,CAAAA,CAAO,IAAI,CACrD,CAAA,MAASM,CAAAA,CAAO,CACZV,CAAAA,CAAKU,CAAK,CAAA,CACV,MACJ,CACJ,CAAA,CAGA,SAAA,CAAAd,GACJ,CACJ","file":"chunk-NOJFGTRT.js","sourcesContent":["import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Express-like interfaces to avoid direct Express dependency\nexport interface ExpressRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Record<string, any>;\n rawBody?: any;\n}\n\nexport interface ExpressResponse {\n status(code: number): ExpressResponse;\n json(data: any): ExpressResponse;\n send(data?: any): ExpressResponse;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextFunction {\n (error?: any): void;\n}\n\nexport interface ExpressWebhookConfig extends WhatsAppConfig {\n path?: string;\n}\n\nexport function webhookHandler(config: ExpressWebhookConfig) {\n const processor = new WebhookProcessor(config);\n\n return {\n // Main webhook handler\n webhook: async (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => {\n try {\n if (req.method === 'GET') {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await processor.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n return res.status(result.status).send(result.body);\n }\n\n if (req.method === 'POST') {\n // Create Web Standard Request from Express request with proper full URL\n const fullUrl = constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await processor.processWebhook(webRequest);\n\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n return res.status(result.status).send(result.body);\n }\n\n return res.status(405).json({ error: 'Method Not Allowed' });\n } catch (error) {\n next(error);\n return;\n }\n },\n\n // Flow handler\n flow: async (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => {\n try {\n // Create Web Standard Request from Express request with proper full URL\n const fullUrl = constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await processor.processFlow(webRequest);\n\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return;\n }\n },\n\n // Expose processor for handler registration\n processor,\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/flowTypeGuards.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest"],"mappings":"AAaA,SAASA,CAAAA,CAASC,CAAAA,CAAkD,CAChE,OAAO,OAAOA,CAAAA,EAAU,QAAA,EAAYA,CAAAA,GAAU,IAClD,CAOA,SAASC,CAAAA,CAASD,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAAA,EAAU,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAA,eAAA,CAAA,MAAA,CAAA,MAAuE,CAAA,CAG/FC,EAAgB,CAAA,eAAA,CAAA,MAAkD,CAAA,CASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAA,GAAgBA,GAAWJ,CAAAA,CAASI,CAAAA,CAAQ,UAAU,CAAA,EAAK,QAAA,GAAYA,CAAAA,CAAAA,CACzE,OAAO,MAAA,CAGX,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,OAAA,CAAAC,EAAS,MAAA,CAAAC,CAAAA,CAAQ,IAAA,CAAAC,CAAK,EAAIJ,CAAAA,CAGpCK,CAAAA,CAAkBH,CAAAA,GAAY,KAAA,CAG9BI,CAAAA,CAAiBT,CAAAA,CAAsB,QAAA,CAASI,CAAa,EAG7DM,CAAAA,CAAiB,OAAOJ,CAAAA,CAAW,GAAA,EAAgBP,EAASO,CAAM,CAAA,EAAKA,CAAAA,GAAW,SAAA,CAGlFK,EAAeP,CAAAA,GAAW,eAAA,EAAgCP,CAAAA,CAASU,CAAI,CAAA,CAG7E,OAAOC,CAAAA,EAAmBC,CAAAA,EAAkBC,GAAkBC,CAClE,CASO,SAASC,CAAAA,CAAmBT,EAQjC,CAEE,GAAI,EAAE,YAAA,GAAgBA,GAAWJ,CAAAA,CAASI,CAAAA,CAAQ,UAAU,CAAA,EAAK,QAAA,GAAYA,CAAAA,CAAAA,CACzE,OAAO,MAAA,CAGX,GAAM,CAAE,MAAA,CAAAC,CAAAA,CAAQ,MAAA,CAAAE,EAAQ,IAAA,CAAAC,CAAK,CAAA,CAAIJ,CAAAA,CAG3BM,EAAiBR,CAAAA,CAAc,QAAA,CAASG,CAAa,CAAA,CAGrDM,CAAAA,CAAiBX,CAAAA,CAASO,CAAM,CAAA,CAGhCK,EACFd,CAAAA,CAASU,CAAI,CAAA,EACb,WAAA,GAAeA,GACfR,CAAAA,CAASQ,CAAAA,CAAK,KAAK,CAAA,EACnB,kBAAmBA,CAAAA,EACnBR,CAAAA,CAASQ,CAAAA,CAAK,aAAa,CAAA,CAG/B,OAAOE,CAAAA,EAAkBC,CAAAA,EAAkBC,CAC/C,CASO,SAASE,CAAAA,CAAkBV,CAAAA,CAAiE,CAE/F,OAAO,QAAA,GAAYA,CAAAA,EAAWA,CAAAA,CAAQ,SAAW,MACrD","file":"chunk-WGGN32O2.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@api/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n"]}
|
package/dist/chunk-YXZ4L2OK.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {d,c}from'./chunk-JPGXONBQ.js';function y(c$1){let d$1=new d(c$1);return {webhook:async(e,t)=>{try{if(e.method==="GET"){let{"hub.mode":s,"hub.verify_token":n,"hub.challenge":r}=e.query,o=await d$1.processVerification(s||null,n||null,r||null);return Object.entries(o.headers).forEach(([a,h])=>{t.setHeader(a,h);}),t.status(o.status).send(o.body)}if(e.method==="POST"){let s=c(e.headers,e.url),n=new Request(s,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),r=await d$1.processWebhook(n);return Object.entries(r.headers).forEach(([o,a])=>{t.setHeader(o,a);}),t.status(r.status).send(r.body)}return t.status(405).json({error:"Method Not Allowed"})}catch(s){return console.error("Webhook error:",s),t.status(500).json({error:"Internal Server Error"})}},flow:async(e,t)=>{try{let s=c(e.headers,e.url),n=new Request(s,{method:e.method,headers:e.headers,body:e.method==="POST"?JSON.stringify(e.body):void 0}),r=await d$1.processFlow(n);return Object.entries(r.headers).forEach(([o,a])=>{t.setHeader(o,a);}),t.status(r.status).send(r.body)}catch(s){return console.error("Flow error:",s),t.status(500).json({error:"Internal Server Error"})}},processor:d$1}}export{y as a};//# sourceMappingURL=chunk-YXZ4L2OK.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-YXZ4L2OK.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/webhook/frameworks/nextjs.ts"],"names":["webhookHandler","config","processor","WebhookProcessor","req","res","mode","token","challenge","result","key","value","fullUrl","constructFullUrl","webRequest","error"],"mappings":"sCA0BO,SAASA,CAAAA,CACZC,GAAAA,CACF,CACE,IAAMC,GAAAA,CAAY,IAAIC,CAAAA,CAAiBF,GAAM,CAAA,CAE7C,OAAO,CAEH,OAAA,CAAS,MAAOG,CAAAA,CAAeC,CAAAA,GAAmB,CAC9C,GAAI,CACA,GAAID,CAAAA,CAAI,MAAA,GAAW,KAAA,CAAO,CACtB,GAAM,CAAE,UAAA,CAAYE,CAAAA,CAAM,kBAAA,CAAoBC,EAAO,eAAA,CAAiBC,CAAU,CAAA,CAAIJ,CAAAA,CAAI,KAAA,CAElFK,CAAAA,CAAS,MAAMP,GAAAA,CAAU,mBAAA,CAC1BI,CAAAA,EAAmB,IAAA,CACnBC,CAAAA,EAAoB,IAAA,CACpBC,CAAAA,EAAwB,IAC7B,CAAA,CAEA,cAAO,OAAA,CAAQC,CAAAA,CAAO,OAAO,CAAA,CAAE,OAAA,CAAQ,CAAC,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAM,CACrDN,CAAAA,CAAI,SAAA,CAAUK,CAAAA,CAAKC,CAAK,EAC5B,CAAC,CAAA,CAEMN,CAAAA,CAAI,MAAA,CAAOI,CAAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAKA,CAAAA,CAAO,IAAI,CACrD,CAEA,GAAIL,CAAAA,CAAI,MAAA,GAAW,MAAA,CAAQ,CAEvB,IAAMQ,CAAAA,CAAUC,CAAAA,CAAiBT,CAAAA,CAAI,OAAA,CAASA,CAAAA,CAAI,GAAG,CAAA,CAE/CU,CAAAA,CAAa,IAAI,OAAA,CAAQF,CAAAA,CAAS,CACpC,MAAA,CAAQR,CAAAA,CAAI,MAAA,CACZ,OAAA,CAASA,EAAI,OAAA,CACb,IAAA,CAAM,IAAA,CAAK,SAAA,CAAUA,CAAAA,CAAI,IAAI,CACjC,CAAC,CA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AAC,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAM,CACrDN,CAAAA,CAAI,SAAA,CAAUK,CAAAA,CAAKC,CAAK,EAC5B,CAAC,CAAA,CAEMN,CAAAA,CAAI,MAAA,CAAOI,CAAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAKA,CAAAA,CAAO,IAAI,CACrD,CAAA,MAASM,CAAAA,CAAO,CACZ,OAAA,OAAA,CAAQ,MAAM,aAAA,CAAeA,CAAK,CAAA,CAC3BV,CAAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,CAAE,KAAA,CAAO,uBAAwB,CAAC,CAClE,CACJ,CAAA,CAGA,SAAA,CAAAH,GACJ,CACJ","file":"chunk-YXZ4L2OK.js","sourcesContent":["import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Generic interfaces for better type compatibility\nexport interface BaseApiRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Partial<Record<string, string | string[]>>;\n rawBody?: any;\n}\n\nexport interface BaseApiResponse {\n status(code: number): any;\n json(data: any): void | any;\n send(data?: any): void | any;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextJsWebhookConfig extends WhatsAppConfig {\n // Next.js specific config can be added here\n}\n\n// Generic webhook handler that accepts any compatible request/response types\nexport function webhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const processor = new WebhookProcessor(config);\n\n return {\n // Main webhook handler\n webhook: async (req: TRequest, res: TResponse) => {\n try {\n if (req.method === 'GET') {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await processor.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n return res.status(result.status).send(result.body);\n }\n\n if (req.method === 'POST') {\n // Create Web Standard Request from Next.js request\n const fullUrl = constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await processor.processWebhook(webRequest);\n\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n return res.status(result.status).send(result.body);\n }\n\n return res.status(405).json({ error: 'Method Not Allowed' });\n } catch (error) {\n console.error('Webhook error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n },\n\n // Flow handler\n flow: async (req: TRequest, res: TResponse) => {\n try {\n const fullUrl = constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await processor.processFlow(webRequest);\n\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Flow error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n },\n\n // Expose processor for handler registration\n processor,\n };\n}\n"]}
|