meta-cloud-api 0.1.12 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/base.d.mts +1 -1
- package/dist/api/base.d.ts +1 -1
- package/dist/api/businessProfile.d.mts +1 -1
- package/dist/api/businessProfile.d.ts +1 -1
- package/dist/api/businessProfile.js +1 -1
- package/dist/api/businessProfile.mjs +1 -1
- package/dist/api/encryption.d.mts +1 -1
- package/dist/api/encryption.d.ts +1 -1
- package/dist/api/encryption.js +1 -1
- package/dist/api/flow.d.mts +1 -1
- package/dist/api/flow.d.ts +1 -1
- package/dist/api/flow.js +1 -1
- package/dist/api/index.d.mts +1 -1
- package/dist/api/index.d.ts +1 -1
- package/dist/api/index.js +1 -1
- package/dist/api/index.mjs +1 -1
- package/dist/api/media.d.mts +1 -1
- package/dist/api/media.d.ts +1 -1
- package/dist/api/media.js +1 -1
- package/dist/api/messages.d.mts +1 -1
- package/dist/api/messages.d.ts +1 -1
- package/dist/api/messages.js +1 -1
- package/dist/api/messages.mjs +1 -1
- package/dist/api/phoneNumber.d.mts +1 -1
- package/dist/api/phoneNumber.d.ts +1 -1
- package/dist/api/phoneNumber.js +1 -1
- package/dist/api/qrCode.d.mts +1 -1
- package/dist/api/qrCode.d.ts +1 -1
- package/dist/api/qrCode.js +1 -1
- package/dist/api/registration.d.mts +1 -1
- package/dist/api/registration.d.ts +1 -1
- package/dist/api/registration.js +1 -1
- package/dist/api/template.d.mts +1 -1
- package/dist/api/template.d.ts +1 -1
- package/dist/api/template.js +1 -1
- package/dist/api/template.mjs +1 -1
- package/dist/api/twoStepVerification.d.mts +1 -1
- package/dist/api/twoStepVerification.d.ts +1 -1
- package/dist/api/twoStepVerification.js +1 -1
- package/dist/api/waba.d.mts +1 -1
- package/dist/api/waba.d.ts +1 -1
- package/dist/api/waba.js +1 -1
- package/dist/api/waba.mjs +1 -1
- package/dist/{enums-D7paGoTY.d.mts → enums-DEhBfoMC.d.mts} +16 -11
- package/dist/{enums-D7paGoTY.d.ts → enums-DEhBfoMC.d.ts} +16 -11
- package/dist/httpsClient.d.mts +1 -1
- package/dist/httpsClient.d.ts +1 -1
- package/dist/index.d.mts +11 -11
- package/dist/index.d.ts +11 -11
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/request.d.mts +1 -1
- package/dist/request.d.ts +1 -1
- package/dist/types/base.d.mts +1 -1
- package/dist/types/base.d.ts +1 -1
- package/dist/types/businessProfile.d.mts +1 -1
- package/dist/types/businessProfile.d.ts +1 -1
- package/dist/types/config.d.mts +1 -1
- package/dist/types/config.d.ts +1 -1
- package/dist/types/encryption.d.mts +1 -1
- package/dist/types/encryption.d.ts +1 -1
- package/dist/types/enums.d.mts +1 -1
- package/dist/types/enums.d.ts +1 -1
- package/dist/types/enums.js +1 -1
- package/dist/types/enums.js.map +1 -1
- package/dist/types/enums.mjs +1 -1
- package/dist/types/enums.mjs.map +1 -1
- package/dist/types/flow.d.mts +1 -1
- package/dist/types/flow.d.ts +1 -1
- package/dist/types/httpsClient.d.mts +1 -1
- package/dist/types/httpsClient.d.ts +1 -1
- package/dist/types/index.d.mts +11 -10
- package/dist/types/index.d.ts +11 -10
- package/dist/types/index.js +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/index.mjs +1 -1
- package/dist/types/index.mjs.map +1 -1
- package/dist/types/media.d.mts +1 -1
- package/dist/types/media.d.ts +1 -1
- package/dist/types/messages.d.mts +1 -1
- package/dist/types/messages.d.ts +1 -1
- package/dist/types/phoneNumber.d.mts +1 -1
- package/dist/types/phoneNumber.d.ts +1 -1
- package/dist/types/qrCode.d.mts +1 -1
- package/dist/types/qrCode.d.ts +1 -1
- package/dist/types/registration.d.mts +1 -1
- package/dist/types/registration.d.ts +1 -1
- package/dist/types/request.d.mts +1 -1
- package/dist/types/request.d.ts +1 -1
- package/dist/types/template.d.mts +1 -1
- package/dist/types/template.d.ts +1 -1
- package/dist/types/twoStepVerification.d.mts +1 -1
- package/dist/types/twoStepVerification.d.ts +1 -1
- package/dist/types/waba.d.mts +1 -1
- package/dist/types/waba.d.ts +1 -1
- package/dist/types/webhook.d.mts +4 -20
- package/dist/types/webhook.d.ts +4 -20
- package/dist/types/webhook.js +1 -1
- package/dist/types/webhook.js.map +1 -1
- package/dist/types/webhook.mjs +1 -1
- package/dist/types/webhook.mjs.map +1 -1
- package/dist/types/whatsapp.d.mts +1 -1
- package/dist/types/whatsapp.d.ts +1 -1
- package/dist/utils/filters.d.mts +3 -2
- package/dist/utils/filters.d.ts +3 -2
- package/dist/utils/filters.js +1 -1
- package/dist/utils/filters.js.map +1 -1
- package/dist/utils/filters.mjs +1 -1
- package/dist/utils/filters.mjs.map +1 -1
- package/dist/utils/importConfig.d.mts +1 -1
- package/dist/utils/importConfig.d.ts +1 -1
- package/dist/utils/importConfig.js +1 -1
- package/dist/utils/importConfig.mjs +1 -1
- package/dist/utils/index.d.mts +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.mjs +1 -1
- package/dist/webhook.d.mts +19 -10
- package/dist/webhook.d.ts +19 -10
- package/dist/webhook.js +1 -1
- package/dist/webhook.js.map +1 -1
- package/dist/webhook.mjs +1 -1
- package/dist/webhook.mjs.map +1 -1
- package/dist/whatsapp.d.mts +1 -1
- package/dist/whatsapp.d.ts +1 -1
- package/dist/whatsapp.js +1 -1
- package/dist/whatsapp.js.map +1 -1
- package/dist/whatsapp.mjs +1 -1
- package/dist/whatsapp.mjs.map +1 -1
- package/package.json +1 -1
package/dist/utils/filters.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as MessageTypesEnum } from '../enums-DEhBfoMC.mjs';
|
|
2
|
+
import { WebhookMessage } from '../types/webhook.mjs';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Filters for message handling, inspired by PyWa
|
|
@@ -9,7 +10,7 @@ declare const filters: {
|
|
|
9
10
|
* @param type Message type to filter for
|
|
10
11
|
* @returns A filter function
|
|
11
12
|
*/
|
|
12
|
-
type: (type:
|
|
13
|
+
type: (type: MessageTypesEnum | string) => ((message: WebhookMessage) => boolean);
|
|
13
14
|
/**
|
|
14
15
|
* Filters text messages
|
|
15
16
|
* @param message Message to check
|
package/dist/utils/filters.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as MessageTypesEnum } from '../enums-DEhBfoMC.js';
|
|
2
|
+
import { WebhookMessage } from '../types/webhook.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Filters for message handling, inspired by PyWa
|
|
@@ -9,7 +10,7 @@ declare const filters: {
|
|
|
9
10
|
* @param type Message type to filter for
|
|
10
11
|
* @returns A filter function
|
|
11
12
|
*/
|
|
12
|
-
type: (type:
|
|
13
|
+
type: (type: MessageTypesEnum | string) => ((message: WebhookMessage) => boolean);
|
|
13
14
|
/**
|
|
14
15
|
* Filters text messages
|
|
15
16
|
* @param message Message to check
|
package/dist/utils/filters.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var A=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var P=(t,i)=>{for(var o in i)A(t,o,{get:i[o],enumerable:!0})},S=(t,i,o,l)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of R(i))!_.call(t,a)&&a!==o&&A(t,a,{get:()=>i[a],enumerable:!(l=p(i,a))||l.enumerable});return t};var D=t=>S(A({},"__esModule",{value:!0}),t);var e={};P(e,{filters:()=>N});module.exports=D(e);var N={type:t=>i=>i.type===t,text:t=>t.type==="text",image:t=>t.type==="image",audio:t=>t.type==="audio",video:t=>t.type==="video",document:t=>t.type==="document",sticker:t=>t.type==="sticker",location:t=>t.type==="location",contacts:t=>t.type==="contacts",button:t=>t.type==="button",interactive:t=>t.type==="interactive",system:t=>t.type==="system",order:t=>t.type==="order",matches:t=>{let i=Array.isArray(t)?t:[t];return o=>{if(o.type!=="text"||!o.text)return!1;let l=o.text.body;for(let a of i)if(typeof a=="string"){if(l.includes(a))return!0}else if(a instanceof RegExp&&a.test(l))return!0;return!1}},isReply:t=>!!t.context&&!!t.context.message_id,isReplyTo:t=>i=>!!i.context&&i.context.message_id===t,isForwarded:t=>!!t.context&&!!t.context.forwarded,isFrequentlyForwarded:t=>!!t.context&&!!t.context.frequently_forwarded,and:(...t)=>i=>{for(let o of t)if(!o(i))return!1;return!0},or:(...t)=>i=>{for(let o of t)if(o(i))return!0;return!1},not:t=>i=>!t(i),from:t=>i=>i.from===t,all:()=>()=>!0};0&&(module.exports={filters});
|
|
2
2
|
//# sourceMappingURL=filters.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/filters.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/utils/filters.ts"],"sourcesContent":["import { MessageTypesEnum } from 'src/types';\nimport { WebhookMessage } from '../types/webhook';\n\n/**\n * Filters for message handling, inspired by PyWa\n */\nexport const filters = {\n /**\n * Filters messages by type\n * @param type Message type to filter for\n * @returns A filter function\n */\n type: (type: MessageTypesEnum | string): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage) => message.type === type;\n },\n\n /**\n * Filters text messages\n * @param message Message to check\n * @returns True if the message is a text message\n */\n text: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Text;\n },\n\n /**\n * Filters image messages\n * @param message Message to check\n * @returns True if the message is an image message\n */\n image: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Image;\n },\n\n /**\n * Filters audio messages\n * @param message Message to check\n * @returns True if the message is an audio message\n */\n audio: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Audio;\n },\n\n /**\n * Filters video messages\n * @param message Message to check\n * @returns True if the message is a video message\n */\n video: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Video;\n },\n\n /**\n * Filters document messages\n * @param message Message to check\n * @returns True if the message is a document message\n */\n document: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Document;\n },\n\n /**\n * Filters sticker messages\n * @param message Message to check\n * @returns True if the message is a sticker message\n */\n sticker: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Sticker;\n },\n\n /**\n * Filters location messages\n * @param message Message to check\n * @returns True if the message is a location message\n */\n location: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Location;\n },\n\n /**\n * Filters contact messages\n * @param message Message to check\n * @returns True if the message is a contacts message\n */\n contacts: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Contacts;\n },\n\n /**\n * Filters button messages\n * @param message Message to check\n * @returns True if the message is a button message\n */\n button: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Button;\n },\n\n /**\n * Filters interactive messages\n * @param message Message to check\n * @returns True if the message is an interactive message\n */\n interactive: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Interactive;\n },\n\n /**\n * Filters system messages\n * @param message Message to check\n * @returns True if the message is a system message\n */\n system: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.System;\n },\n\n /**\n * Filters order messages\n * @param message Message to check\n * @returns True if the message is an order message\n */\n order: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Order;\n },\n\n /**\n * Matches text content against a pattern\n * @param patterns String or regular expression or array of patterns to match against\n * @returns A filter function\n */\n matches: (patterns: string | RegExp | (string | RegExp)[]): ((message: WebhookMessage) => boolean) => {\n const patternsArray = Array.isArray(patterns) ? patterns : [patterns];\n\n return (message: WebhookMessage): boolean => {\n if (message.type !== MessageTypesEnum.Text || !message.text) {\n return false;\n }\n\n const text = message.text.body;\n\n for (const pattern of patternsArray) {\n if (typeof pattern === 'string') {\n if (text.includes(pattern)) {\n return true;\n }\n } else if (pattern instanceof RegExp) {\n if (pattern.test(text)) {\n return true;\n }\n }\n }\n\n return false;\n };\n },\n\n /**\n * Checks if a message is a reply to another message\n * @returns A filter function that returns true if the message is a reply\n */\n isReply: (message: WebhookMessage): boolean => {\n return !!message.context && !!message.context.message_id;\n },\n\n /**\n * Checks if a message is a reply to a specific message\n * @param messageId The ID of the original message to check for\n * @returns A filter function that returns true if the message is a reply to the specified message\n */\n isReplyTo: (messageId: string): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n return !!message.context && message.context.message_id === messageId;\n };\n },\n\n /**\n * Checks if a message is forwarded\n * @returns A filter function that returns true if the message is forwarded\n */\n isForwarded: (message: WebhookMessage): boolean => {\n return !!message.context && !!message.context.forwarded;\n },\n\n /**\n * Checks if a message is frequently forwarded\n * @returns A filter function that returns true if the message is frequently forwarded\n */\n isFrequentlyForwarded: (message: WebhookMessage): boolean => {\n return !!message.context && !!message.context.frequently_forwarded;\n },\n\n /**\n * Combines multiple filters with AND logic\n * @param filterFunctions Array of filter functions to combine\n * @returns A filter function that returns true only if all filters return true\n */\n and: (...filterFunctions: ((message: WebhookMessage) => boolean)[]): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n for (const filter of filterFunctions) {\n if (!filter(message)) {\n return false;\n }\n }\n return true;\n };\n },\n\n /**\n * Combines multiple filters with OR logic\n * @param filterFunctions Array of filter functions to combine\n * @returns A filter function that returns true if any filter returns true\n */\n or: (...filterFunctions: ((message: WebhookMessage) => boolean)[]): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n for (const filter of filterFunctions) {\n if (filter(message)) {\n return true;\n }\n }\n return false;\n };\n },\n\n /**\n * Negates a filter\n * @param filterFunction Filter function to negate\n * @returns A filter function that returns the opposite of the input filter\n */\n not: (filterFunction: (message: WebhookMessage) => boolean): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n return !filterFunction(message);\n };\n },\n\n /**\n * Filters messages from a specific sender\n * @param from Sender phone number to filter for\n * @returns A filter function\n */\n from: (from: string): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n return message.from === from;\n };\n },\n\n /**\n * Filter function that accepts all messages\n * @returns Always returns true\n */\n all: (): ((message: WebhookMessage) => boolean) => {\n return (): boolean => true;\n },\n};\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAMO,IAAMI,EAAU,CAMnB,KAAOC,GACKC,GAA4BA,EAAQ,OAASD,EAQzD,KAAOC,GACIA,EAAQ,OAAS,OAQ5B,MAAQA,GACGA,EAAQ,OAAS,QAQ5B,MAAQA,GACGA,EAAQ,OAAS,QAQ5B,MAAQA,GACGA,EAAQ,OAAS,QAQ5B,SAAWA,GACAA,EAAQ,OAAS,WAQ5B,QAAUA,GACCA,EAAQ,OAAS,UAQ5B,SAAWA,GACAA,EAAQ,OAAS,WAQ5B,SAAWA,GACAA,EAAQ,OAAS,WAQ5B,OAASA,GACEA,EAAQ,OAAS,SAQ5B,YAAcA,GACHA,EAAQ,OAAS,cAQ5B,OAASA,GACEA,EAAQ,OAAS,SAQ5B,MAAQA,GACGA,EAAQ,OAAS,QAQ5B,QAAUC,GAA4F,CAClG,IAAMC,EAAgB,MAAM,QAAQD,CAAQ,EAAIA,EAAW,CAACA,CAAQ,EAEpE,OAAQD,GAAqC,CACzC,GAAIA,EAAQ,OAAS,QAAyB,CAACA,EAAQ,KACnD,MAAO,GAGX,IAAMG,EAAOH,EAAQ,KAAK,KAE1B,QAAWI,KAAWF,EAClB,GAAI,OAAOE,GAAY,UACnB,GAAID,EAAK,SAASC,CAAO,EACrB,MAAO,WAEJA,aAAmB,QACtBA,EAAQ,KAAKD,CAAI,EACjB,MAAO,GAKnB,MAAO,EACX,CACJ,EAMA,QAAUH,GACC,CAAC,CAACA,EAAQ,SAAW,CAAC,CAACA,EAAQ,QAAQ,WAQlD,UAAYK,GACAL,GACG,CAAC,CAACA,EAAQ,SAAWA,EAAQ,QAAQ,aAAeK,EAQnE,YAAcL,GACH,CAAC,CAACA,EAAQ,SAAW,CAAC,CAACA,EAAQ,QAAQ,UAOlD,sBAAwBA,GACb,CAAC,CAACA,EAAQ,SAAW,CAAC,CAACA,EAAQ,QAAQ,qBAQlD,IAAK,IAAIM,IACGN,GAAqC,CACzC,QAAWO,KAAUD,EACjB,GAAI,CAACC,EAAOP,CAAO,EACf,MAAO,GAGf,MAAO,EACX,EAQJ,GAAI,IAAIM,IACIN,GAAqC,CACzC,QAAWO,KAAUD,EACjB,GAAIC,EAAOP,CAAO,EACd,MAAO,GAGf,MAAO,EACX,EAQJ,IAAMQ,GACMR,GACG,CAACQ,EAAeR,CAAO,EAStC,KAAOS,GACKT,GACGA,EAAQ,OAASS,EAQhC,IAAK,IACM,IAAe,EAE9B","names":["filters_exports","__export","filters","__toCommonJS","filters","type","message","patterns","patternsArray","text","pattern","messageId","filterFunctions","filter","filterFunction","from"]}
|
package/dist/utils/filters.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var H={type:t=>i=>i.type===t,text:t=>t.type==="text",image:t=>t.type==="image",audio:t=>t.type==="audio",video:t=>t.type==="video",document:t=>t.type==="document",sticker:t=>t.type==="sticker",location:t=>t.type==="location",contacts:t=>t.type==="contacts",button:t=>t.type==="button",interactive:t=>t.type==="interactive",system:t=>t.type==="system",order:t=>t.type==="order",matches:t=>{let i=Array.isArray(t)?t:[t];return o=>{if(o.type!=="text"||!o.text)return!1;let l=o.text.body;for(let a of i)if(typeof a=="string"){if(l.includes(a))return!0}else if(a instanceof RegExp&&a.test(l))return!0;return!1}},isReply:t=>!!t.context&&!!t.context.message_id,isReplyTo:t=>i=>!!i.context&&i.context.message_id===t,isForwarded:t=>!!t.context&&!!t.context.forwarded,isFrequentlyForwarded:t=>!!t.context&&!!t.context.frequently_forwarded,and:(...t)=>i=>{for(let o of t)if(!o(i))return!1;return!0},or:(...t)=>i=>{for(let o of t)if(o(i))return!0;return!1},not:t=>i=>!t(i),from:t=>i=>i.from===t,all:()=>()=>!0};export{H as filters};
|
|
2
2
|
//# sourceMappingURL=filters.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/filters.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/utils/filters.ts"],"sourcesContent":["import { MessageTypesEnum } from 'src/types';\nimport { WebhookMessage } from '../types/webhook';\n\n/**\n * Filters for message handling, inspired by PyWa\n */\nexport const filters = {\n /**\n * Filters messages by type\n * @param type Message type to filter for\n * @returns A filter function\n */\n type: (type: MessageTypesEnum | string): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage) => message.type === type;\n },\n\n /**\n * Filters text messages\n * @param message Message to check\n * @returns True if the message is a text message\n */\n text: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Text;\n },\n\n /**\n * Filters image messages\n * @param message Message to check\n * @returns True if the message is an image message\n */\n image: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Image;\n },\n\n /**\n * Filters audio messages\n * @param message Message to check\n * @returns True if the message is an audio message\n */\n audio: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Audio;\n },\n\n /**\n * Filters video messages\n * @param message Message to check\n * @returns True if the message is a video message\n */\n video: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Video;\n },\n\n /**\n * Filters document messages\n * @param message Message to check\n * @returns True if the message is a document message\n */\n document: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Document;\n },\n\n /**\n * Filters sticker messages\n * @param message Message to check\n * @returns True if the message is a sticker message\n */\n sticker: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Sticker;\n },\n\n /**\n * Filters location messages\n * @param message Message to check\n * @returns True if the message is a location message\n */\n location: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Location;\n },\n\n /**\n * Filters contact messages\n * @param message Message to check\n * @returns True if the message is a contacts message\n */\n contacts: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Contacts;\n },\n\n /**\n * Filters button messages\n * @param message Message to check\n * @returns True if the message is a button message\n */\n button: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Button;\n },\n\n /**\n * Filters interactive messages\n * @param message Message to check\n * @returns True if the message is an interactive message\n */\n interactive: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Interactive;\n },\n\n /**\n * Filters system messages\n * @param message Message to check\n * @returns True if the message is a system message\n */\n system: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.System;\n },\n\n /**\n * Filters order messages\n * @param message Message to check\n * @returns True if the message is an order message\n */\n order: (message: WebhookMessage): boolean => {\n return message.type === MessageTypesEnum.Order;\n },\n\n /**\n * Matches text content against a pattern\n * @param patterns String or regular expression or array of patterns to match against\n * @returns A filter function\n */\n matches: (patterns: string | RegExp | (string | RegExp)[]): ((message: WebhookMessage) => boolean) => {\n const patternsArray = Array.isArray(patterns) ? patterns : [patterns];\n\n return (message: WebhookMessage): boolean => {\n if (message.type !== MessageTypesEnum.Text || !message.text) {\n return false;\n }\n\n const text = message.text.body;\n\n for (const pattern of patternsArray) {\n if (typeof pattern === 'string') {\n if (text.includes(pattern)) {\n return true;\n }\n } else if (pattern instanceof RegExp) {\n if (pattern.test(text)) {\n return true;\n }\n }\n }\n\n return false;\n };\n },\n\n /**\n * Checks if a message is a reply to another message\n * @returns A filter function that returns true if the message is a reply\n */\n isReply: (message: WebhookMessage): boolean => {\n return !!message.context && !!message.context.message_id;\n },\n\n /**\n * Checks if a message is a reply to a specific message\n * @param messageId The ID of the original message to check for\n * @returns A filter function that returns true if the message is a reply to the specified message\n */\n isReplyTo: (messageId: string): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n return !!message.context && message.context.message_id === messageId;\n };\n },\n\n /**\n * Checks if a message is forwarded\n * @returns A filter function that returns true if the message is forwarded\n */\n isForwarded: (message: WebhookMessage): boolean => {\n return !!message.context && !!message.context.forwarded;\n },\n\n /**\n * Checks if a message is frequently forwarded\n * @returns A filter function that returns true if the message is frequently forwarded\n */\n isFrequentlyForwarded: (message: WebhookMessage): boolean => {\n return !!message.context && !!message.context.frequently_forwarded;\n },\n\n /**\n * Combines multiple filters with AND logic\n * @param filterFunctions Array of filter functions to combine\n * @returns A filter function that returns true only if all filters return true\n */\n and: (...filterFunctions: ((message: WebhookMessage) => boolean)[]): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n for (const filter of filterFunctions) {\n if (!filter(message)) {\n return false;\n }\n }\n return true;\n };\n },\n\n /**\n * Combines multiple filters with OR logic\n * @param filterFunctions Array of filter functions to combine\n * @returns A filter function that returns true if any filter returns true\n */\n or: (...filterFunctions: ((message: WebhookMessage) => boolean)[]): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n for (const filter of filterFunctions) {\n if (filter(message)) {\n return true;\n }\n }\n return false;\n };\n },\n\n /**\n * Negates a filter\n * @param filterFunction Filter function to negate\n * @returns A filter function that returns the opposite of the input filter\n */\n not: (filterFunction: (message: WebhookMessage) => boolean): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n return !filterFunction(message);\n };\n },\n\n /**\n * Filters messages from a specific sender\n * @param from Sender phone number to filter for\n * @returns A filter function\n */\n from: (from: string): ((message: WebhookMessage) => boolean) => {\n return (message: WebhookMessage): boolean => {\n return message.from === from;\n };\n },\n\n /**\n * Filter function that accepts all messages\n * @returns Always returns true\n */\n all: (): ((message: WebhookMessage) => boolean) => {\n return (): boolean => true;\n },\n};\n"],"mappings":"AAMO,IAAMA,EAAU,CAMnB,KAAOC,GACKC,GAA4BA,EAAQ,OAASD,EAQzD,KAAOC,GACIA,EAAQ,OAAS,OAQ5B,MAAQA,GACGA,EAAQ,OAAS,QAQ5B,MAAQA,GACGA,EAAQ,OAAS,QAQ5B,MAAQA,GAC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OS,GACKT,GACGA,EAAQ,OAASS,EAQhC,IAAK,IACM,IAAe,EAE9B","names":["filters","type","message","patterns","patternsArray","text","pattern","messageId","filterFunctions","filter","filterFunction","from"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { WhatsAppConfig } from '../types/whatsapp.mjs';
|
|
2
2
|
import { WabaConfigType } from '../types/config.mjs';
|
|
3
3
|
import '../types/businessProfile.mjs';
|
|
4
|
-
import '../enums-
|
|
4
|
+
import '../enums-DEhBfoMC.mjs';
|
|
5
5
|
import '../types/request.mjs';
|
|
6
6
|
import '../types/encryption.mjs';
|
|
7
7
|
import '../types/flow.mjs';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { WhatsAppConfig } from '../types/whatsapp.js';
|
|
2
2
|
import { WabaConfigType } from '../types/config.js';
|
|
3
3
|
import '../types/businessProfile.js';
|
|
4
|
-
import '../enums-
|
|
4
|
+
import '../enums-DEhBfoMC.js';
|
|
5
5
|
import '../types/request.js';
|
|
6
6
|
import '../types/encryption.js';
|
|
7
7
|
import '../types/flow.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var P=Object.defineProperty;var
|
|
1
|
+
"use strict";var P=Object.defineProperty;var t=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var G=(S,A)=>{for(var R in A)P(S,R,{get:A[R],enumerable:!0})},_=(S,A,R,U)=>{if(A&&typeof A=="object"||typeof A=="function")for(let D of I(A))!B.call(S,D)&&D!==R&&P(S,D,{get:()=>A[D],enumerable:!(U=t(A,D))||U.enumerable});return S};var T=S=>_(P({},"__esModule",{value:!0}),S);var Y={};G(Y,{importConfig:()=>X});module.exports=T(Y);var N=class{name;debug;constructor(A,R=!1){this.name=A,this.debug=R}log(...A){if(this.debug){let R=`[ ${Date.now()} ]`;this.name&&(R+=` - ${this.name}`),console.log.apply(console,[R,": ",...A])}}error(...A){let R=`[ ${Date.now()} ] - ERROR`;this.name&&(R+=` - ${this.name}`),console.error.apply(console,[R,": ",...A])}warn(...A){let R=`[ ${Date.now()} ] - WARN`;this.name&&(R+=` - ${this.name}`),console.warn.apply(console,[R,": ",...A])}info(...A){let R=`[ ${Date.now()} ] - INFO`;this.name&&(R+=` - ${this.name}`),console.info.apply(console,[R,": ",...A])}};var K="UTILS",M=!1,O=new N(K,process.env.DEBUG==="true"||M),i="graph.facebook.com",F=3e3,p=30,H=2e4,L=S=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!S?.accessToken)throw O.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},X=S=>{L(S);let A={WA_BASE_URL:process.env.WA_BASE_URL||i,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:S?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:S?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:S?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:parseInt(process.env.LISTENER_PORT||"")||F,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||p,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||H,DEBUG:process.env.DEBUG==="true"};return O.log(`Configuration loaded for App Id ${A.M4D_APP_ID}`),A};0&&(module.exports={importConfig});
|
|
2
2
|
//# sourceMappingURL=importConfig.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var D=class{name;debug;constructor(R,A=!1){this.name=R,this.debug=A}log(...R){if(this.debug){let A=`[ ${Date.now()} ]`;this.name&&(A+=` - ${this.name}`),console.log.apply(console,[A,": ",...R])}}error(...R){let A=`[ ${Date.now()} ] - ERROR`;this.name&&(A+=` - ${this.name}`),console.error.apply(console,[A,": ",...R])}warn(...R){let A=`[ ${Date.now()} ] - WARN`;this.name&&(A+=` - ${this.name}`),console.warn.apply(console,[A,": ",...R])}info(...R){let A=`[ ${Date.now()} ] - INFO`;this.name&&(A+=` - ${this.name}`),console.info.apply(console,[A,": ",...R])}};var P="UTILS",U=!1,N=new D(P,process.env.DEBUG==="true"||U),
|
|
1
|
+
var D=class{name;debug;constructor(R,A=!1){this.name=R,this.debug=A}log(...R){if(this.debug){let A=`[ ${Date.now()} ]`;this.name&&(A+=` - ${this.name}`),console.log.apply(console,[A,": ",...R])}}error(...R){let A=`[ ${Date.now()} ] - ERROR`;this.name&&(A+=` - ${this.name}`),console.error.apply(console,[A,": ",...R])}warn(...R){let A=`[ ${Date.now()} ] - WARN`;this.name&&(A+=` - ${this.name}`),console.warn.apply(console,[A,": ",...R])}info(...R){let A=`[ ${Date.now()} ] - INFO`;this.name&&(A+=` - ${this.name}`),console.info.apply(console,[A,": ",...R])}};var P="UTILS",U=!1,N=new D(P,process.env.DEBUG==="true"||U),O="graph.facebook.com",t=3e3,I=30,B=2e4,G=S=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!S?.accessToken)throw N.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},F=S=>{G(S);let R={WA_BASE_URL:process.env.WA_BASE_URL||O,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:S?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:S?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:S?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:parseInt(process.env.LISTENER_PORT||"")||t,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||I,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||B,DEBUG:process.env.DEBUG==="true"};return N.log(`Configuration loaded for App Id ${R.M4D_APP_ID}`),R};export{F as importConfig};
|
|
2
2
|
//# sourceMappingURL=importConfig.mjs.map
|
package/dist/utils/index.d.mts
CHANGED
|
@@ -4,7 +4,7 @@ export { MetaError, isMetaError } from './isMetaError.mjs';
|
|
|
4
4
|
export { objectToQueryString } from './objectToQueryString.mjs';
|
|
5
5
|
import '../types/whatsapp.mjs';
|
|
6
6
|
import '../types/businessProfile.mjs';
|
|
7
|
-
import '../enums-
|
|
7
|
+
import '../enums-DEhBfoMC.mjs';
|
|
8
8
|
import '../types/request.mjs';
|
|
9
9
|
import '../types/encryption.mjs';
|
|
10
10
|
import '../types/flow.mjs';
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { MetaError, isMetaError } from './isMetaError.js';
|
|
|
4
4
|
export { objectToQueryString } from './objectToQueryString.js';
|
|
5
5
|
import '../types/whatsapp.js';
|
|
6
6
|
import '../types/businessProfile.js';
|
|
7
|
-
import '../enums-
|
|
7
|
+
import '../enums-DEhBfoMC.js';
|
|
8
8
|
import '../types/request.js';
|
|
9
9
|
import '../types/encryption.js';
|
|
10
10
|
import '../types/flow.js';
|
package/dist/utils/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var i=Object.create;var N=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var i=Object.create;var N=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,T=Object.prototype.hasOwnProperty;var p=(t,A)=>{for(var R in A)N(t,R,{get:A[R],enumerable:!0})},U=(t,A,R,P)=>{if(A&&typeof A=="object"||typeof A=="function")for(let S of B(A))!T.call(t,S)&&S!==R&&N(t,S,{get:()=>A[S],enumerable:!(P=I(A,S))||P.enumerable});return t};var K=(t,A,R)=>(R=t!=null?i(G(t)):{},U(A||!t||!t.__esModule?N(R,"default",{value:t,enumerable:!0}):R,t)),M=t=>U(N({},"__esModule",{value:!0}),t);var v={};p(v,{generateXHub256Sig:()=>F,importConfig:()=>h,isMetaError:()=>Z,objectToQueryString:()=>W});module.exports=M(v);var _=K(require("crypto")),F=(t,A)=>_.createHmac("sha256",A).update(t,"utf-8").digest("hex");var D=class{name;debug;constructor(A,R=!1){this.name=A,this.debug=R}log(...A){if(this.debug){let R=`[ ${Date.now()} ]`;this.name&&(R+=` - ${this.name}`),console.log.apply(console,[R,": ",...A])}}error(...A){let R=`[ ${Date.now()} ] - ERROR`;this.name&&(R+=` - ${this.name}`),console.error.apply(console,[R,": ",...A])}warn(...A){let R=`[ ${Date.now()} ] - WARN`;this.name&&(R+=` - ${this.name}`),console.warn.apply(console,[R,": ",...A])}info(...A){let R=`[ ${Date.now()} ] - INFO`;this.name&&(R+=` - ${this.name}`),console.info.apply(console,[R,": ",...A])}};var H="UTILS",L=!1,O=new D(H,process.env.DEBUG==="true"||L),f="graph.facebook.com",l=3e3,X=30,Y=2e4,x=t=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!t?.accessToken)throw O.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},h=t=>{x(t);let A={WA_BASE_URL:process.env.WA_BASE_URL||f,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:t?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:t?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:t?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:parseInt(process.env.LISTENER_PORT||"")||l,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||X,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||Y,DEBUG:process.env.DEBUG==="true"};return O.log(`Configuration loaded for App Id ${A.M4D_APP_ID}`),A};function Z(t){return t!=null&&typeof t=="object"&&"error"in t&&typeof t.error=="object"&&t.error!=null&&"message"in t.error&&typeof t.error.message=="string"&&"type"in t.error&&typeof t.error.type=="string"&&"code"in t.error&&typeof t.error.code=="number"&&"fbtrace_id"in t.error&&typeof t.error.fbtrace_id=="string"&&(!("error_data"in t.error)||typeof t.error.error_data=="object"&&t.error.error_data!=null&&"messaging_product"in t.error.error_data&&t.error.error_data.messaging_product==="whatsapp"&&"details"in t.error.error_data&&typeof t.error.error_data.details=="string")&&(!("error_subcode"in t.error)||typeof t.error.error_subcode=="number")}var W=t=>{if(!t||Object.keys(t).length===0)return"";let A=new URLSearchParams;for(let[P,S]of Object.entries(t))S!==void 0&&A.append(P,String(S));let R=A.toString();return R?`?${R}`:""};0&&(module.exports={generateXHub256Sig,importConfig,isMetaError,objectToQueryString});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/utils/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as P from"crypto";var p=(A
|
|
1
|
+
import*as P from"crypto";var p=(t,A)=>P.createHmac("sha256",A).update(t,"utf-8").digest("hex");var S=class{name;debug;constructor(A,R=!1){this.name=A,this.debug=R}log(...A){if(this.debug){let R=`[ ${Date.now()} ]`;this.name&&(R+=` - ${this.name}`),console.log.apply(console,[R,": ",...A])}}error(...A){let R=`[ ${Date.now()} ] - ERROR`;this.name&&(R+=` - ${this.name}`),console.error.apply(console,[R,": ",...A])}warn(...A){let R=`[ ${Date.now()} ] - WARN`;this.name&&(R+=` - ${this.name}`),console.warn.apply(console,[R,": ",...A])}info(...A){let R=`[ ${Date.now()} ] - INFO`;this.name&&(R+=` - ${this.name}`),console.info.apply(console,[R,": ",...A])}};var _="UTILS",O=!1,N=new S(_,process.env.DEBUG==="true"||O),i="graph.facebook.com",I=3e3,B=30,G=2e4,T=t=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!t?.accessToken)throw N.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},l=t=>{T(t);let A={WA_BASE_URL:process.env.WA_BASE_URL||i,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:t?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:t?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:t?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:parseInt(process.env.LISTENER_PORT||"")||I,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||B,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||G,DEBUG:process.env.DEBUG==="true"};return N.log(`Configuration loaded for App Id ${A.M4D_APP_ID}`),A};function Y(t){return t!=null&&typeof t=="object"&&"error"in t&&typeof t.error=="object"&&t.error!=null&&"message"in t.error&&typeof t.error.message=="string"&&"type"in t.error&&typeof t.error.type=="string"&&"code"in t.error&&typeof t.error.code=="number"&&"fbtrace_id"in t.error&&typeof t.error.fbtrace_id=="string"&&(!("error_data"in t.error)||typeof t.error.error_data=="object"&&t.error.error_data!=null&&"messaging_product"in t.error.error_data&&t.error.error_data.messaging_product==="whatsapp"&&"details"in t.error.error_data&&typeof t.error.error_data.details=="string")&&(!("error_subcode"in t.error)||typeof t.error.error_subcode=="number")}var h=t=>{if(!t||Object.keys(t).length===0)return"";let A=new URLSearchParams;for(let[U,D]of Object.entries(t))D!==void 0&&A.append(U,String(D));let R=A.toString();return R?`?${R}`:""};export{p as generateXHub256Sig,l as importConfig,Y as isMetaError,h as objectToQueryString};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/webhook.d.mts
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as MessageTypesEnum } from './enums-DEhBfoMC.mjs';
|
|
2
2
|
import { WebhookMessage, WebhookEvent } from './types/webhook.mjs';
|
|
3
|
-
import './
|
|
3
|
+
import { WhatsAppConfig } from './types/whatsapp.mjs';
|
|
4
|
+
import './types/businessProfile.mjs';
|
|
5
|
+
import './types/request.mjs';
|
|
6
|
+
import './types/encryption.mjs';
|
|
7
|
+
import './types/flow.mjs';
|
|
8
|
+
import './types/media.mjs';
|
|
9
|
+
import './types/messages.mjs';
|
|
10
|
+
import './types/base.mjs';
|
|
11
|
+
import './types/config.mjs';
|
|
12
|
+
import './types/phoneNumber.mjs';
|
|
13
|
+
import './types/qrCode.mjs';
|
|
14
|
+
import './types/registration.mjs';
|
|
15
|
+
import './types/template.mjs';
|
|
16
|
+
import './types/twoStepVerification.mjs';
|
|
17
|
+
import './types/waba.mjs';
|
|
4
18
|
|
|
5
19
|
interface IRequest {
|
|
6
20
|
body: any;
|
|
7
|
-
query: Record<string, any
|
|
8
|
-
[key: string]: string | string[];
|
|
9
|
-
}>;
|
|
21
|
+
query: Record<string, any>;
|
|
10
22
|
method?: string;
|
|
11
23
|
}
|
|
12
24
|
interface IResponse {
|
|
@@ -26,7 +38,7 @@ declare class WebhookHandler {
|
|
|
26
38
|
* Create a new WebhookHandler
|
|
27
39
|
* @param config The WhatsApp configuration
|
|
28
40
|
*/
|
|
29
|
-
constructor(config:
|
|
41
|
+
constructor(config: WhatsAppConfig);
|
|
30
42
|
/**
|
|
31
43
|
* Handle a GET request for webhook verification
|
|
32
44
|
*/
|
|
@@ -43,16 +55,13 @@ declare class WebhookHandler {
|
|
|
43
55
|
* Process incoming messages
|
|
44
56
|
*/
|
|
45
57
|
private processMessages;
|
|
46
|
-
/**
|
|
47
|
-
* Process other webhook events
|
|
48
|
-
*/
|
|
49
58
|
private processEvent;
|
|
50
59
|
/**
|
|
51
60
|
* Register a message handler for a specific message type
|
|
52
61
|
* @param type Message type to handle, or '*' for all types
|
|
53
62
|
* @param handler The handler function
|
|
54
63
|
*/
|
|
55
|
-
onMessage(type:
|
|
64
|
+
onMessage(type: MessageTypesEnum, handler: (message: WebhookMessage) => void | Promise<void>): void;
|
|
56
65
|
/**
|
|
57
66
|
* Register a general event handler
|
|
58
67
|
* @param field Event field to handle, or '*' for all fields
|
package/dist/webhook.d.ts
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as MessageTypesEnum } from './enums-DEhBfoMC.js';
|
|
2
2
|
import { WebhookMessage, WebhookEvent } from './types/webhook.js';
|
|
3
|
-
import './
|
|
3
|
+
import { WhatsAppConfig } from './types/whatsapp.js';
|
|
4
|
+
import './types/businessProfile.js';
|
|
5
|
+
import './types/request.js';
|
|
6
|
+
import './types/encryption.js';
|
|
7
|
+
import './types/flow.js';
|
|
8
|
+
import './types/media.js';
|
|
9
|
+
import './types/messages.js';
|
|
10
|
+
import './types/base.js';
|
|
11
|
+
import './types/config.js';
|
|
12
|
+
import './types/phoneNumber.js';
|
|
13
|
+
import './types/qrCode.js';
|
|
14
|
+
import './types/registration.js';
|
|
15
|
+
import './types/template.js';
|
|
16
|
+
import './types/twoStepVerification.js';
|
|
17
|
+
import './types/waba.js';
|
|
4
18
|
|
|
5
19
|
interface IRequest {
|
|
6
20
|
body: any;
|
|
7
|
-
query: Record<string, any
|
|
8
|
-
[key: string]: string | string[];
|
|
9
|
-
}>;
|
|
21
|
+
query: Record<string, any>;
|
|
10
22
|
method?: string;
|
|
11
23
|
}
|
|
12
24
|
interface IResponse {
|
|
@@ -26,7 +38,7 @@ declare class WebhookHandler {
|
|
|
26
38
|
* Create a new WebhookHandler
|
|
27
39
|
* @param config The WhatsApp configuration
|
|
28
40
|
*/
|
|
29
|
-
constructor(config:
|
|
41
|
+
constructor(config: WhatsAppConfig);
|
|
30
42
|
/**
|
|
31
43
|
* Handle a GET request for webhook verification
|
|
32
44
|
*/
|
|
@@ -43,16 +55,13 @@ declare class WebhookHandler {
|
|
|
43
55
|
* Process incoming messages
|
|
44
56
|
*/
|
|
45
57
|
private processMessages;
|
|
46
|
-
/**
|
|
47
|
-
* Process other webhook events
|
|
48
|
-
*/
|
|
49
58
|
private processEvent;
|
|
50
59
|
/**
|
|
51
60
|
* Register a message handler for a specific message type
|
|
52
61
|
* @param type Message type to handle, or '*' for all types
|
|
53
62
|
* @param handler The handler function
|
|
54
63
|
*/
|
|
55
|
-
onMessage(type:
|
|
64
|
+
onMessage(type: MessageTypesEnum, handler: (message: WebhookMessage) => void | Promise<void>): void;
|
|
56
65
|
/**
|
|
57
66
|
* Register a general event handler
|
|
58
67
|
* @param field Event field to handle, or '*' for all fields
|
package/dist/webhook.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var P=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var b=(a,t)=>{for(var i in t)P(a,i,{get:t[i],enumerable:!0})},U=(a,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of I(t))!N.call(a,o)&&o!==i&&P(a,o,{get:()=>t[o],enumerable:!(s=D(t,o))||s.enumerable});return a};var O=a=>U(P({},"__esModule",{value:!0}),a);var w={};b(w,{default:()=>_});module.exports=O(w);var l=class{name;debug;constructor(t,i=!1){this.name=t,this.debug=i}log(...t){if(this.debug){let i=`[ ${Date.now()} ]`;this.name&&(i+=` - ${this.name}`),console.log.apply(console,[i,": ",...t])}}error(...t){let i=`[ ${Date.now()} ] - ERROR`;this.name&&(i+=` - ${this.name}`),console.error.apply(console,[i,": ",...t])}warn(...t){let i=`[ ${Date.now()} ] - WARN`;this.name&&(i+=` - ${this.name}`),console.warn.apply(console,[i,": ",...t])}info(...t){let i=`[ ${Date.now()} ] - INFO`;this.name&&(i+=` - ${this.name}`),console.info.apply(console,[i,": ",...t])}};var h="UTILS",T=!1,S=new l(h,process.env.DEBUG==="true"||T),g="graph.facebook.com",x=3e3,B=30,G=2e4,v=a=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!a?.accessToken)throw S.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},f=a=>{v(a);let t={WA_BASE_URL:process.env.WA_BASE_URL||g,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:a?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:a?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:a?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:parseInt(process.env.LISTENER_PORT||"")||x,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||B,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||G,DEBUG:process.env.DEBUG==="true"};return S.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};var M="WEBHOOK",F=!1,A=new l(M,process.env.DEBUG==="true"||F),_=class{config;messageHandlers=new Map;eventHandlers=new Map;constructor(t){let i=f(t);this.config=i,A.log("WebhookHandler instantiated!")}handleVerificationRequest(t,i){let s=t.query["hub.mode"],o=t.query["hub.verify_token"],e=t.query["hub.challenge"];s==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(A.log("Webhook verified successfully"),i.status(200).send(e)):(A.log("Webhook verification failed"),i.status(403).end())}async handleWebhookRequest(t,i){let s=t.body;if(s.object!=="whatsapp_business_account"){A.log("Received webhook for non-WhatsApp event"),i.status(404).end();return}for(let o of s.entry)try{let e=o.changes;for(let r of e)r.field==="messages"?await this.processMessages(r.value):await this.processEvent(r.field,r.value)}catch(e){A.log(`Error processing webhook: ${e}`)}i.status(200).end()}handleRequest(t,i){if(t.method==="GET")return this.handleVerificationRequest(t,i);if(t.method==="POST")return this.handleWebhookRequest(t,i);i.status(405).end()}async processMessages(t){let s=t.metadata.phone_number_id,o=t.messages;if(o&&o.length>0)for(let e of o){let r=e.type,p={id:e.id,from:e.from,timestamp:e.timestamp,type:e.type,phoneNumberId:s,originalData:e};switch(e.type){case"text":p.text=e.text;break;case"image":p.image=e.image;break;case"video":p.video=e.video;break;case"audio":p.audio=e.audio;break;case"document":p.document=e.document;break;case"sticker":p.sticker=e.sticker;break;case"location":p.location=e.location;break;case"contacts":p.contacts=e.contacts;break;case"interactive":p.interactive=e.interactive;break;case"button":p.button=e.button;break;case"order":p.order=e.order;break;case"system":p.system=e.system;break;default:break}if(e.context&&(p.context=e.context),e.errors&&(p.errors=e.errors),this.messageHandlers.has(r)){let R=this.messageHandlers.get(r);R&&await Promise.resolve(R(p))}if(this.messageHandlers.has("*")){let R=this.messageHandlers.get("*");R&&await Promise.resolve(R(p))}}t.statuses&&t.statuses.length>0&&await this.processEvent("statuses",t)}async processEvent(t,i){let s={field:t,value:i};if(this.eventHandlers.has(t)){let o=this.eventHandlers.get(t);o&&await Promise.resolve(o(s))}if(this.eventHandlers.has("*")){let o=this.eventHandlers.get("*");o&&await Promise.resolve(o(s))}}onMessage(t,i){this.messageHandlers.set(t,i),A.log(`Registered handler for message type: ${t}`)}onEvent(t,i){this.eventHandlers.set(t,i),A.log(`Registered handler for event field: ${t}`)}};
|
|
2
2
|
//# sourceMappingURL=webhook.js.map
|
package/dist/webhook.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webhook.ts","../src/utils/logger.ts"],"sourcesContent":["import { WabaConfigType } from './types/config';\n\nimport { EventField, MessageType, WebhookEvent, WebhookMessage } from './types/webhook';\nimport Logger from './utils/logger';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport interface IRequest {\n body: any;\n query:\n | Record<string, any>\n | Partial<{\n [key: string]: string | string[];\n }>;\n method?: string;\n}\nexport interface IResponse {\n status: (code: number) => IResponse;\n send: (body: any) => IResponse | void;\n json: (body: any) => IResponse | void;\n end: () => void;\n}\n\n/**\n * Webhook handler for WhatsApp Cloud API\n */\nexport default class WebhookHandler {\n private config: WabaConfigType;\n private messageHandlers: Map<string, (message: WebhookMessage) => void | Promise<void>> = new Map();\n private eventHandlers: Map<string, (event: WebhookEvent) => void | Promise<void>> = new Map();\n\n /**\n * Create a new WebhookHandler\n * @param config The WhatsApp configuration\n */\n constructor(config: WabaConfigType) {\n this.config = config;\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle a GET request for webhook verification\n */\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void {\n const mode = req.query['hub.mode'];\n const token = req.query['hub.verify_token'];\n const challenge = req.query['hub.challenge'];\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n LOGGER.log('Webhook verified successfully');\n res.status(200).send(challenge);\n } else {\n LOGGER.log('Webhook verification failed');\n res.status(403).end();\n }\n }\n\n /**\n * Handle a POST request for webhook events\n */\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void> {\n const body = req.body;\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n LOGGER.log('Received webhook for non-WhatsApp event');\n res.status(404).end();\n return;\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === EventField.MESSAGES) {\n await this.processMessages(change.value);\n } else {\n // Handle other event types\n await this.processEvent(change.field, change.value);\n }\n }\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n }\n }\n\n // Always respond with 200 to acknowledge receipt\n res.status(200).end();\n }\n\n /**\n * Handle webhook requests (both verification and events)\n */\n public handleRequest(req: IRequest, res: IResponse): void | Promise<void> {\n if (req.method === 'GET') {\n return this.handleVerificationRequest(req, res);\n } else if (req.method === 'POST') {\n return this.handleWebhookRequest(req, res);\n } else {\n res.status(405).end(); // Method not allowed\n }\n }\n\n // /**\n // * Initialize the webhook with an Express app (legacy support)\n // * @param app Express application instance\n // * @param path The path to listen on, defaults to /webhook\n // */\n // public initialize(app: any, path: string = '/webhook'): void {\n // // Set up middleware to handle requests\n // app.all(path, async (req: any, res: any) => {\n // const request = expressAdapter.createRequest(req);\n // const response = expressAdapter.createResponse(res);\n // await this.handleRequest(request, response);\n // });\n\n // LOGGER.log(`Webhook initialized at path: ${path}`);\n // }\n\n /**\n * Process incoming messages\n */\n private async processMessages(value: any): Promise<void> {\n // Extract metadata\n const metadata = value.metadata;\n const phoneNumberId = metadata.phone_number_id;\n const messages = value.messages as WebhookMessage[];\n\n // Process messages if present\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n // Create the base message object\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: messageType,\n phoneNumberId,\n originalData: message,\n };\n\n // Add type-specific data based on the message type\n switch (messageType) {\n case MessageType.TEXT:\n processedMessage.text = message.text;\n break;\n case MessageType.IMAGE:\n processedMessage.image = message.image;\n break;\n case MessageType.VIDEO:\n processedMessage.video = message.video;\n break;\n case MessageType.AUDIO:\n processedMessage.audio = message.audio;\n break;\n case MessageType.DOCUMENT:\n processedMessage.document = message.document;\n break;\n case MessageType.STICKER:\n processedMessage.sticker = message.sticker;\n break;\n case MessageType.LOCATION:\n processedMessage.location = message.location;\n break;\n case MessageType.CONTACTS:\n processedMessage.contacts = message.contacts;\n break;\n case MessageType.INTERACTIVE:\n processedMessage.interactive = message.interactive;\n break;\n case MessageType.BUTTON:\n processedMessage.button = message.button;\n break;\n case MessageType.ORDER:\n processedMessage.order = message.order;\n break;\n case MessageType.SYSTEM:\n processedMessage.system = message.system;\n break;\n default:\n // Unknown message type\n break;\n }\n\n // Add context if available\n if (message.context) {\n processedMessage.context = message.context;\n }\n\n // Add errors if available\n if (message.errors) {\n processedMessage.errors = message.errors;\n }\n\n // Dispatch to appropriate message handler\n if (this.messageHandlers.has(messageType)) {\n const handler = this.messageHandlers.get(messageType);\n if (handler) {\n await Promise.resolve(handler(processedMessage));\n }\n }\n\n // Also dispatch to general message handler if exists\n if (this.messageHandlers.has('*')) {\n const handler = this.messageHandlers.get('*');\n if (handler) {\n await Promise.resolve(handler(processedMessage));\n }\n }\n }\n }\n\n // Process status messages if present\n if (value.statuses && value.statuses.length > 0) {\n // Process as events\n await this.processEvent(EventField.STATUSES, value);\n }\n }\n\n /**\n * Process other webhook events\n */\n private async processEvent(field: string, value: any): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n };\n\n // Dispatch to appropriate event handler\n if (this.eventHandlers.has(field)) {\n const handler = this.eventHandlers.get(field);\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n\n // Also dispatch to general event handler if exists\n if (this.eventHandlers.has('*')) {\n const handler = this.eventHandlers.get('*');\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n }\n\n /**\n * Register a message handler for a specific message type\n * @param type Message type to handle, or '*' for all types\n * @param handler The handler function\n */\n public onMessage(type: string, handler: (message: WebhookMessage) => void | Promise<void>): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered handler for message type: ${type}`);\n }\n\n /**\n * Register a general event handler\n * @param field Event field to handle, or '*' for all fields\n * @param handler The handler function\n */\n public onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered handler for event field: ${field}`);\n }\n}\n","// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAA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IAAMF,EAAU,KAAK,cAAc,IAAI,GAAG,EACtCA,GACA,MAAM,QAAQ,QAAQA,EAAQE,CAAK,CAAC,CAE5C,CACJ,CAOO,UAAUC,EAAcH,EAAkE,CAC7F,KAAK,gBAAgB,IAAIG,EAAMH,CAAO,EACtCpB,EAAO,IAAI,wCAAwCuB,CAAI,EAAE,CAC7D,CAOO,QAAQF,EAAeD,EAA8D,CACxF,KAAK,cAAc,IAAIC,EAAOD,CAAO,EACrCpB,EAAO,IAAI,uCAAuCqB,CAAK,EAAE,CAC7D,CACJ","names":["webhook_exports","__export","WebhookHandler","__toCommonJS","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","WebhookHandler","config","req","res","mode","token","challenge","body","entry","changes","change","error","value","phoneNumberId","messages","message","messageType","processedMessage","handler","field","event","type"]}
|
|
1
|
+
{"version":3,"sources":["../src/webhook.ts","../src/utils/logger.ts","../src/utils/importConfig.ts"],"sourcesContent":["import { MessageTypesEnum, WhatsAppConfig } from './types';\nimport { WabaConfigType } from './types/config';\n\nimport { EventField, WebhookEvent, WebhookMessage } from './types/webhook';\nimport { importConfig } from './utils';\nimport Logger from './utils/logger';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport interface IRequest {\n body: any;\n query: Record<string, any>;\n method?: string;\n}\nexport interface IResponse {\n status: (code: number) => IResponse;\n send: (body: any) => IResponse | void;\n json: (body: any) => IResponse | void;\n end: () => void;\n}\n\n/**\n * Webhook handler for WhatsApp Cloud API\n */\nexport default class WebhookHandler {\n private config: WabaConfigType;\n private messageHandlers: Map<string, (message: WebhookMessage) => void | Promise<void>> = new Map();\n private eventHandlers: Map<string, (event: WebhookEvent) => void | Promise<void>> = new Map();\n\n /**\n * Create a new WebhookHandler\n * @param config The WhatsApp configuration\n */\n constructor(config: WhatsAppConfig) {\n const configuration = importConfig(config);\n this.config = configuration;\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle a GET request for webhook verification\n */\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void {\n const mode = req.query['hub.mode'];\n const token = req.query['hub.verify_token'];\n const challenge = req.query['hub.challenge'];\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n LOGGER.log('Webhook verified successfully');\n res.status(200).send(challenge);\n } else {\n LOGGER.log('Webhook verification failed');\n res.status(403).end();\n }\n }\n\n /**\n * Handle a POST request for webhook events\n */\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void> {\n const body = req.body;\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n LOGGER.log('Received webhook for non-WhatsApp event');\n res.status(404).end();\n return;\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === EventField.MESSAGES) {\n await this.processMessages(change.value);\n } else {\n // Handle other event types\n await this.processEvent(change.field, change.value);\n }\n }\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n }\n }\n\n // Always respond with 200 to acknowledge receipt\n res.status(200).end();\n }\n\n /**\n * Handle webhook requests (both verification and events)\n */\n public handleRequest(req: IRequest, res: IResponse): void | Promise<void> {\n if (req.method === 'GET') {\n return this.handleVerificationRequest(req, res);\n } else if (req.method === 'POST') {\n return this.handleWebhookRequest(req, res);\n } else {\n res.status(405).end(); // Method not allowed\n }\n }\n\n /**\n * Process incoming messages\n */\n private async processMessages(value: any): Promise<void> {\n // Extract metadata\n const metadata = value.metadata;\n const phoneNumberId = metadata.phone_number_id;\n const messages = value.messages as WebhookMessage[];\n\n // Process messages if present\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n // Create the base message object\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n originalData: message,\n };\n\n // Add type-specific data based on the message type\n switch (message.type) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n default:\n // Unknown message type\n break;\n }\n\n // Add context if available\n if (message.context) {\n processedMessage.context = message.context;\n }\n\n // Add errors if available\n if (message.errors) {\n processedMessage.errors = message.errors;\n }\n\n // Dispatch to appropriate message handler\n if (this.messageHandlers.has(messageType)) {\n const handler = this.messageHandlers.get(messageType);\n if (handler) {\n await Promise.resolve(handler(processedMessage));\n }\n }\n\n // Also dispatch to general message handler if exists\n if (this.messageHandlers.has('*')) {\n const handler = this.messageHandlers.get('*');\n if (handler) {\n await Promise.resolve(handler(processedMessage));\n }\n }\n }\n }\n\n if (value.statuses && value.statuses.length > 0) {\n await this.processEvent(EventField.STATUSES, value);\n }\n }\n\n private async processEvent(field: string, value: any): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n };\n\n if (this.eventHandlers.has(field)) {\n const handler = this.eventHandlers.get(field);\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n\n if (this.eventHandlers.has('*')) {\n const handler = this.eventHandlers.get('*');\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n }\n\n /**\n * Register a message handler for a specific message type\n * @param type Message type to handle, or '*' for all types\n * @param handler The handler function\n */\n public onMessage(type: MessageTypesEnum, handler: (message: WebhookMessage) => void | Promise<void>): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered handler for message type: ${type}`);\n }\n\n /**\n * Register a general event handler\n * @param field Event field to handle, or '*' for all fields\n * @param handler The handler function\n */\n public onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered handler for event field: ${field}`);\n }\n}\n","// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import { WhatsAppConfig } from 'src/types/whatsapp';\nimport type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from './logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_BASE_URL = 'graph.facebook.com';\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.BaseURL]: process.env.WA_BASE_URL || DEFAULT_BASE_URL,\n [WabaConfigEnum.AppId]: process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]: process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]: parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') || DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]: parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: process.env.DEBUG === 'true',\n };\n\n LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\n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AOO,UAAUC,EAAwBH,EAAkE,CACvG,KAAK,gBAAgB,IAAIG,EAAMH,CAAO,EACtCtB,EAAO,IAAI,wCAAwCyB,CAAI,EAAE,CAC7D,CAOO,QAAQF,EAAeD,EAA8D,CACxF,KAAK,cAAc,IAAIC,EAAOD,CAAO,EACrCtB,EAAO,IAAI,uCAAuCuB,CAAK,EAAE,CAC7D,CACJ","names":["webhook_exports","__export","WebhookHandler","__toCommonJS","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_BASE_URL","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","LIB_NAME","LOG_LOCAL","LOGGER","Logger","WebhookHandler","config","configuration","importConfig","req","res","mode","token","challenge","body","entry","changes","change","error","value","phoneNumberId","messages","message","messageType","processedMessage","handler","field","event","type"]}
|
package/dist/webhook.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=class{name;debug;constructor(t,i=!1){this.name=t,this.debug=i}log(...t){if(this.debug){let i=`[ ${Date.now()} ]`;this.name&&(i+=` - ${this.name}`),console.log.apply(console,[i,": ",...t])}}error(...t){let i=`[ ${Date.now()} ] - ERROR`;this.name&&(i+=` - ${this.name}`),console.error.apply(console,[i,": ",...t])}warn(...t){let i=`[ ${Date.now()} ] - WARN`;this.name&&(i+=` - ${this.name}`),console.warn.apply(console,[i,": ",...t])}info(...t){let i=`[ ${Date.now()} ] - INFO`;this.name&&(i+=` - ${this.name}`),console.info.apply(console,[i,": ",...t])}};var f="UTILS",D=!1,P=new l(f,process.env.DEBUG==="true"||D),I="graph.facebook.com",N=3e3,b=30,U=2e4,O=s=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!s?.accessToken)throw P.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},S=s=>{O(s);let t={WA_BASE_URL:process.env.WA_BASE_URL||I,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:s?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:s?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:s?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:parseInt(process.env.LISTENER_PORT||"")||N,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||b,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||U,DEBUG:process.env.DEBUG==="true"};return P.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};var h="WEBHOOK",T=!1,A=new l(h,process.env.DEBUG==="true"||T),_=class{config;messageHandlers=new Map;eventHandlers=new Map;constructor(t){let i=S(t);this.config=i,A.log("WebhookHandler instantiated!")}handleVerificationRequest(t,i){let p=t.query["hub.mode"],a=t.query["hub.verify_token"],e=t.query["hub.challenge"];p==="subscribe"&&a===this.config.WEBHOOK_VERIFICATION_TOKEN?(A.log("Webhook verified successfully"),i.status(200).send(e)):(A.log("Webhook verification failed"),i.status(403).end())}async handleWebhookRequest(t,i){let p=t.body;if(p.object!=="whatsapp_business_account"){A.log("Received webhook for non-WhatsApp event"),i.status(404).end();return}for(let a of p.entry)try{let e=a.changes;for(let r of e)r.field==="messages"?await this.processMessages(r.value):await this.processEvent(r.field,r.value)}catch(e){A.log(`Error processing webhook: ${e}`)}i.status(200).end()}handleRequest(t,i){if(t.method==="GET")return this.handleVerificationRequest(t,i);if(t.method==="POST")return this.handleWebhookRequest(t,i);i.status(405).end()}async processMessages(t){let p=t.metadata.phone_number_id,a=t.messages;if(a&&a.length>0)for(let e of a){let r=e.type,o={id:e.id,from:e.from,timestamp:e.timestamp,type:e.type,phoneNumberId:p,originalData:e};switch(e.type){case"text":o.text=e.text;break;case"image":o.image=e.image;break;case"video":o.video=e.video;break;case"audio":o.audio=e.audio;break;case"document":o.document=e.document;break;case"sticker":o.sticker=e.sticker;break;case"location":o.location=e.location;break;case"contacts":o.contacts=e.contacts;break;case"interactive":o.interactive=e.interactive;break;case"button":o.button=e.button;break;case"order":o.order=e.order;break;case"system":o.system=e.system;break;default:break}if(e.context&&(o.context=e.context),e.errors&&(o.errors=e.errors),this.messageHandlers.has(r)){let R=this.messageHandlers.get(r);R&&await Promise.resolve(R(o))}if(this.messageHandlers.has("*")){let R=this.messageHandlers.get("*");R&&await Promise.resolve(R(o))}}t.statuses&&t.statuses.length>0&&await this.processEvent("statuses",t)}async processEvent(t,i){let p={field:t,value:i};if(this.eventHandlers.has(t)){let a=this.eventHandlers.get(t);a&&await Promise.resolve(a(p))}if(this.eventHandlers.has("*")){let a=this.eventHandlers.get("*");a&&await Promise.resolve(a(p))}}onMessage(t,i){this.messageHandlers.set(t,i),A.log(`Registered handler for message type: ${t}`)}onEvent(t,i){this.eventHandlers.set(t,i),A.log(`Registered handler for event field: ${t}`)}};export{_ as default};
|
|
2
2
|
//# sourceMappingURL=webhook.mjs.map
|