meta-cloud-api 0.0.13 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/businessProfile.d.mts +2 -2
- package/dist/api/businessProfile.d.ts +2 -2
- package/dist/api/businessProfile.js +1 -1
- package/dist/api/businessProfile.js.map +1 -1
- package/dist/api/businessProfile.mjs +1 -1
- package/dist/api/businessProfile.mjs.map +1 -1
- package/dist/api/index.js.map +1 -1
- package/dist/api/index.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- 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/types/businessProfile.d.mts +5 -2
- package/dist/types/businessProfile.d.ts +5 -2
- package/dist/types/businessProfile.js.map +1 -1
- package/dist/types/index.d.mts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/utils/importConfig.js +1 -1
- package/dist/utils/importConfig.js.map +1 -1
- package/dist/utils/importConfig.mjs +1 -1
- package/dist/utils/importConfig.mjs.map +1 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +1 -1
- package/dist/utils/index.mjs.map +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
|
@@ -103,6 +103,9 @@ interface UploadSession {
|
|
|
103
103
|
interface UploadSessionResponse {
|
|
104
104
|
id: string;
|
|
105
105
|
}
|
|
106
|
+
interface UploadBusinessProfileResponse {
|
|
107
|
+
h: string;
|
|
108
|
+
}
|
|
106
109
|
interface UploadHandle {
|
|
107
110
|
handle: string;
|
|
108
111
|
file_size: number;
|
|
@@ -135,7 +138,7 @@ interface BusinessProfileClass {
|
|
|
135
138
|
* @param uploadId The ID of the upload session.
|
|
136
139
|
* @param file The binary data of the file.
|
|
137
140
|
*/
|
|
138
|
-
uploadMedia(uploadId: string, file: Buffer): Promise<RequesterResponseInterface<
|
|
141
|
+
uploadMedia(uploadId: string, file: Buffer): Promise<RequesterResponseInterface<UploadBusinessProfileResponse>>;
|
|
139
142
|
/**
|
|
140
143
|
* Get the upload handle information.
|
|
141
144
|
* @param uploadId The ID of the upload session.
|
|
@@ -143,4 +146,4 @@ interface BusinessProfileClass {
|
|
|
143
146
|
getUploadHandle(uploadId: string): Promise<RequesterResponseInterface<UploadHandle>>;
|
|
144
147
|
}
|
|
145
148
|
|
|
146
|
-
export type { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadHandle, UploadSession, UploadSessionResponse };
|
|
149
|
+
export type { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse };
|
|
@@ -103,6 +103,9 @@ interface UploadSession {
|
|
|
103
103
|
interface UploadSessionResponse {
|
|
104
104
|
id: string;
|
|
105
105
|
}
|
|
106
|
+
interface UploadBusinessProfileResponse {
|
|
107
|
+
h: string;
|
|
108
|
+
}
|
|
106
109
|
interface UploadHandle {
|
|
107
110
|
handle: string;
|
|
108
111
|
file_size: number;
|
|
@@ -135,7 +138,7 @@ interface BusinessProfileClass {
|
|
|
135
138
|
* @param uploadId The ID of the upload session.
|
|
136
139
|
* @param file The binary data of the file.
|
|
137
140
|
*/
|
|
138
|
-
uploadMedia(uploadId: string, file: Buffer): Promise<RequesterResponseInterface<
|
|
141
|
+
uploadMedia(uploadId: string, file: Buffer): Promise<RequesterResponseInterface<UploadBusinessProfileResponse>>;
|
|
139
142
|
/**
|
|
140
143
|
* Get the upload handle information.
|
|
141
144
|
* @param uploadId The ID of the upload session.
|
|
@@ -143,4 +146,4 @@ interface BusinessProfileClass {
|
|
|
143
146
|
getUploadHandle(uploadId: string): Promise<RequesterResponseInterface<UploadHandle>>;
|
|
144
147
|
}
|
|
145
148
|
|
|
146
|
-
export type { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadHandle, UploadSession, UploadSessionResponse };
|
|
149
|
+
export type { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/businessProfile.ts"],"sourcesContent":["import { BusinessVerticalEnum } from './enums';\nimport { RequesterResponseInterface, ResponseSuccess } from './request';\n\nexport interface BusinessProfileData {\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n */\n messaging_product: string;\n /**\n * Profile picture URL.\n */\n profile_picture_url?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n}\n\nexport interface BusinessProfileResponse {\n data: BusinessProfileData[];\n}\n\nexport interface UpdateBusinessProfileRequest {\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n * @required\n */\n messaging_product: string;\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Handle of the profile picture. This handle is generated when you upload the binary file\n * for the profile picture to Meta using the Resumable Upload API.\n */\n profile_picture_handle?: string;\n}\n\nexport interface UploadSession {\n id: string;\n video?: boolean;\n}\n\nexport interface UploadSessionResponse {\n id: string;\n}\n\nexport interface UploadHandle {\n handle: string;\n file_size: number;\n upload_result: {\n handle_type: string;\n name: string;\n };\n}\n\nexport interface BusinessProfileClass {\n /**\n * Get your business profile.\n * @param fields Fields to be returned in the response. If not specified, all fields will be returned.\n * Possible values: about, address, description, email, profile_picture_url, websites, vertical\n */\n getBusinessProfile(fields?: string): Promise<RequesterResponseInterface<BusinessProfileResponse>>;\n\n /**\n * Update your business profile.\n * @param updateRequest The request object containing the fields to update.\n */\n updateBusinessProfile(\n updateRequest: UpdateBusinessProfileRequest,\n ): Promise<RequesterResponseInterface<ResponseSuccess>>;\n\n /**\n * Create an upload session for profile picture.\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file.\n */\n createUploadSession(\n fileLength: number,\n fileType: string,\n fileName: string,\n ): Promise<RequesterResponseInterface<UploadSessionResponse>>;\n\n /**\n * Upload media file to the upload session.\n * @param uploadId The ID of the upload session.\n * @param file The binary data of the file.\n */\n uploadMedia(uploadId: string, file: Buffer): Promise<RequesterResponseInterface<
|
|
1
|
+
{"version":3,"sources":["../../src/types/businessProfile.ts"],"sourcesContent":["import { BusinessVerticalEnum } from './enums';\nimport { RequesterResponseInterface, ResponseSuccess } from './request';\n\nexport interface BusinessProfileData {\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n */\n messaging_product: string;\n /**\n * Profile picture URL.\n */\n profile_picture_url?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n}\n\nexport interface BusinessProfileResponse {\n data: BusinessProfileData[];\n}\n\nexport interface UpdateBusinessProfileRequest {\n /**\n * The messaging service used for the request. Always set it to \"whatsapp\" if you are using\n * the WhatsApp Business API.\n * @required\n */\n messaging_product: string;\n /**\n * The business's About text. This text appears in the business's profile, beneath its profile image,\n * phone number, and contact buttons.\n * - String cannot be empty\n * - Strings must be between 1 and 139 characters\n * - Rendered emojis are supported however their unicode values are not.\n * Emoji unicode values must be Java- or JavaScript-escape encoded\n * - Hyperlinks can be included but will not render as clickable links\n * - Markdown is not supported\n */\n about?: string;\n /**\n * Address of the business. Character limit 256.\n */\n address?: string;\n /**\n * Description of the business. Character limit 512.\n */\n description?: string;\n /**\n * Business category. This can be either an empty string or one of the predefined business categories.\n * @see BusinessVerticalEnum for all available options\n */\n vertical?: BusinessVerticalEnum | string;\n /**\n * The contact email address (in valid email format) of the business. Character limit 128.\n */\n email?: string;\n /**\n * The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n * - You must include the http:// or https:// portion of the URL\n * - There is a maximum of 2 websites with a maximum of 256 characters each\n */\n websites?: string[];\n /**\n * Handle of the profile picture. This handle is generated when you upload the binary file\n * for the profile picture to Meta using the Resumable Upload API.\n */\n profile_picture_handle?: string;\n}\n\nexport interface UploadSession {\n id: string;\n video?: boolean;\n}\n\nexport interface UploadSessionResponse {\n id: string;\n}\n\nexport interface UploadBusinessProfileResponse {\n h: string;\n}\n\nexport interface UploadHandle {\n handle: string;\n file_size: number;\n upload_result: {\n handle_type: string;\n name: string;\n };\n}\n\nexport interface BusinessProfileClass {\n /**\n * Get your business profile.\n * @param fields Fields to be returned in the response. If not specified, all fields will be returned.\n * Possible values: about, address, description, email, profile_picture_url, websites, vertical\n */\n getBusinessProfile(fields?: string): Promise<RequesterResponseInterface<BusinessProfileResponse>>;\n\n /**\n * Update your business profile.\n * @param updateRequest The request object containing the fields to update.\n */\n updateBusinessProfile(\n updateRequest: UpdateBusinessProfileRequest,\n ): Promise<RequesterResponseInterface<ResponseSuccess>>;\n\n /**\n * Create an upload session for profile picture.\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file.\n */\n createUploadSession(\n fileLength: number,\n fileType: string,\n fileName: string,\n ): Promise<RequesterResponseInterface<UploadSessionResponse>>;\n\n /**\n * Upload media file to the upload session.\n * @param uploadId The ID of the upload session.\n * @param file The binary data of the file.\n */\n uploadMedia(uploadId: string, file: Buffer): Promise<RequesterResponseInterface<UploadBusinessProfileResponse>>;\n\n /**\n * Get the upload handle information.\n * @param uploadId The ID of the upload session.\n */\n getUploadHandle(uploadId: string): Promise<RequesterResponseInterface<UploadHandle>>;\n}\n"],"mappings":"+WAAA,IAAAA,EAAA,kBAAAC,EAAAD","names":["businessProfile_exports","__toCommonJS"]}
|
package/dist/types/index.d.mts
CHANGED
|
@@ -15,4 +15,4 @@ export { EncryptionClass, EncryptionPublicKeyResponse } from './encryption.mjs';
|
|
|
15
15
|
export { WABAClass, WabaSubscription, WabaSubscriptions } from './waba.mjs';
|
|
16
16
|
export { MediaClass, MediaResponse, MediasResponse, UploadMediaResponse } from './media.mjs';
|
|
17
17
|
export { Flow, FlowAsset, FlowAssetsResponse, FlowCategoryEnum, FlowClass, FlowMigrationFailure, FlowMigrationResponse, FlowMigrationResult, FlowPreview, FlowPreviewResponse, FlowStatusEnum, FlowValidationError, FlowValidationErrorPointer, FlowsListResponse, Pagination, PaginationCursors } from './flow.mjs';
|
|
18
|
-
export { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.mjs';
|
|
18
|
+
export { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.mjs';
|
package/dist/types/index.d.ts
CHANGED
|
@@ -15,4 +15,4 @@ export { EncryptionClass, EncryptionPublicKeyResponse } from './encryption.js';
|
|
|
15
15
|
export { WABAClass, WabaSubscription, WabaSubscriptions } from './waba.js';
|
|
16
16
|
export { MediaClass, MediaResponse, MediasResponse, UploadMediaResponse } from './media.js';
|
|
17
17
|
export { Flow, FlowAsset, FlowAssetsResponse, FlowCategoryEnum, FlowClass, FlowMigrationFailure, FlowMigrationResponse, FlowMigrationResult, FlowPreview, FlowPreviewResponse, FlowStatusEnum, FlowValidationError, FlowValidationErrorPointer, FlowsListResponse, Pagination, PaginationCursors } from './flow.js';
|
|
18
|
-
export { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.js';
|
|
18
|
+
export { BusinessProfileClass, BusinessProfileData, BusinessProfileResponse, UpdateBusinessProfileRequest, UploadBusinessProfileResponse, UploadHandle, UploadSession, UploadSessionResponse } from './businessProfile.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var N=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var G=(S,A)=>{for(var R in A)N(S,R,{get:A[R],enumerable:!0})},T=(S,A,R,t)=>{if(A&&typeof A=="object"||typeof A=="function")for(let D of O(A))!B.call(S,D)&&D!==R&&N(S,D,{get:()=>A[D],enumerable:!(t=I(A,D))||t.enumerable});return S};var _=S=>T(N({},"__esModule",{value:!0}),S);var Y={};G(Y,{importConfig:()=>X});module.exports=_(Y);var P=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,U=new P(K,process.env.DEBUG==="true"||M),i="graph.facebook.com",p=3e3,F=30,H=2e4,L=S=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!S?.accessToken)throw U.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||parseInt(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||"")||p,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||F,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||H,DEBUG:process.env.DEBUG==="true"};return U.log(`Configuration loaded for App Id ${A.M4D_APP_ID}`),A};0&&(module.exports={importConfig});
|
|
2
2
|
//# sourceMappingURL=importConfig.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/importConfig.ts","../../src/utils/logger.ts"],"sourcesContent":["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.
|
|
1
|
+
{"version":3,"sources":["../../src/utils/importConfig.ts","../../src/utils/logger.ts"],"sourcesContent":["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 || parseInt(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};\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,kBAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAqBI,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAAa,CAChB,GAAI,KAAK,MAAO,CACZ,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,KACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,IAAI,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CACJ,EDxCA,IAAME,EAAW,QACXC,EAAY,GACZC,EAAS,IAAIC,EAAOH,EAAU,QAAQ,IAAI,QAAU,QAAUC,CAAS,EACvEG,EAAmB,qBACnBC,EAAwB,IACxBC,EAAiC,GACjCC,EAA0B,IAE1BC,EAAsBC,GAAuC,CAC/D,GAAI,CAAC,QAAQ,IAAI,wBAA+B,CAACA,GAAQ,YACrD,MAAAP,EAAO,IAAI,2FAA2F,EAChG,IAAI,MAAM,gCAAgC,CAExD,EAEaQ,EAAgBC,GAAiC,CAC1DH,EAAmBG,CAAW,EAE9B,IAAMC,EAA6B,CAC9B,YAAyB,QAAQ,IAAI,aAAeR,EACpD,WAAuB,QAAQ,IAAI,YAAc,GACjD,eAA2B,QAAQ,IAAI,gBAAkB,GACzD,mBAA+BO,GAAa,eAAiB,SAAS,QAAQ,IAAI,oBAAsB,EAAE,EAC1G,uBAAgCA,GAAa,gBAAkB,QAAQ,IAAI,wBAA0B,GACrG,kBAA4B,QAAQ,IAAI,mBAAqB,GAC7D,uBAA6BA,GAAa,aAAe,QAAQ,IAAI,wBAA0B,GAC/F,iBAAiC,QAAQ,IAAI,kBAAoB,GACjE,2BAA0C,QAAQ,IAAI,4BAA8B,GACpF,cAA8B,SAAS,QAAQ,IAAI,eAAiB,EAAE,GAAKN,EAC3E,uBACG,SAAS,QAAQ,IAAI,wBAA0B,EAAE,GAAKC,EACzD,gBAAgC,SAAS,QAAQ,IAAI,iBAAmB,EAAE,GAAKC,EAC/E,MAAuB,QAAQ,IAAI,QAAU,MAClD,EAEA,OAAAL,EAAO,IAAI,mCAAmCU,EAAW,UAAqB,EAAE,EAEzEA,CACX","names":["importConfig_exports","__export","importConfig","__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"]}
|
|
@@ -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
|
|
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 N="UTILS",t=!1,P=new D(N,process.env.DEBUG==="true"||t),U="graph.facebook.com",I=3e3,O=30,B=2e4,G=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.")},p=S=>{G(S);let R={WA_BASE_URL:process.env.WA_BASE_URL||U,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:S?.phoneNumberId||parseInt(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||"")||I,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||O,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||B,DEBUG:process.env.DEBUG==="true"};return P.log(`Configuration loaded for App Id ${R.M4D_APP_ID}`),R};export{p as importConfig};
|
|
2
2
|
//# sourceMappingURL=importConfig.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/logger.ts","../../src/utils/importConfig.ts"],"sourcesContent":["// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","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.
|
|
1
|
+
{"version":3,"sources":["../../src/utils/logger.ts","../../src/utils/importConfig.ts"],"sourcesContent":["// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","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 || parseInt(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};\n"],"mappings":"AAGA,IAAqBA,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAAa,CAChB,GAAI,KAAK,MAAO,CACZ,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,KACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,IAAI,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CACJ,ECxCA,IAAME,EAAW,QACXC,EAAY,GACZC,EAAS,IAAIC,EAAOH,EAAU,QAAQ,IAAI,QAAU,QAAUC,CAAS,EACvEG,EAAmB,qBACnBC,EAAwB,IACxBC,EAAiC,GACjCC,EAA0B,IAE1BC,EAAsBC,GAAuC,CAC/D,GAAI,CAAC,QAAQ,IAAI,wBAA+B,CAACA,GAAQ,YACrD,MAAAP,EAAO,IAAI,2FAA2F,EAChG,IAAI,MAAM,gCAAgC,CAExD,EAEaQ,EAAgBC,GAAiC,CAC1DH,EAAmBG,CAAW,EAE9B,IAAMC,EAA6B,CAC9B,YAAyB,QAAQ,IAAI,aAAeR,EACpD,WAAuB,QAAQ,IAAI,YAAc,GACjD,eAA2B,QAAQ,IAAI,gBAAkB,GACzD,mBAA+BO,GAAa,eAAiB,SAAS,QAAQ,IAAI,oBAAsB,EAAE,EAC1G,uBAAgCA,GAAa,gBAAkB,QAAQ,IAAI,wBAA0B,GACrG,kBAA4B,QAAQ,IAAI,mBAAqB,GAC7D,uBAA6BA,GAAa,aAAe,QAAQ,IAAI,wBAA0B,GAC/F,iBAAiC,QAAQ,IAAI,kBAAoB,GACjE,2BAA0C,QAAQ,IAAI,4BAA8B,GACpF,cAA8B,SAAS,QAAQ,IAAI,eAAiB,EAAE,GAAKN,EAC3E,uBACG,SAAS,QAAQ,IAAI,wBAA0B,EAAE,GAAKC,EACzD,gBAAgC,SAAS,QAAQ,IAAI,iBAAmB,EAAE,GAAKC,EAC/E,MAAuB,QAAQ,IAAI,QAAU,MAClD,EAEA,OAAAL,EAAO,IAAI,mCAAmCU,EAAW,UAAqB,EAAE,EAEzEA,CACX","names":["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"]}
|
package/dist/utils/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var i=Object.create;var N=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var B=Object.getPrototypeOf,G=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 T(A))!G.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(B(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||parseInt(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.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/index.ts","../../src/utils/generateXHub256Sig.ts","../../src/utils/logger.ts","../../src/utils/importConfig.ts","../../src/utils/isMetaError.ts","../../src/utils/objectToQueryString.ts"],"sourcesContent":["export * from './generateXHub256Sig';\nexport * from './importConfig';\nexport * from './isMetaError';\nexport * from './logger';\nexport * from './objectToQueryString';\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","// @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.
|
|
1
|
+
{"version":3,"sources":["../../src/utils/index.ts","../../src/utils/generateXHub256Sig.ts","../../src/utils/logger.ts","../../src/utils/importConfig.ts","../../src/utils/isMetaError.ts","../../src/utils/objectToQueryString.ts"],"sourcesContent":["export * from './generateXHub256Sig';\nexport * from './importConfig';\nexport * from './isMetaError';\nexport * from './logger';\nexport * from './objectToQueryString';\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","// @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 || parseInt(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};\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n searchParams.append(key, String(value));\n }\n }\n\n const queryString = searchParams.toString();\n return queryString ? `?${queryString}` : '';\n};\n"],"mappings":"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","names":["utils_exports","__export","generateXHub256Sig","importConfig","isMetaError","objectToQueryString","__toCommonJS","crypto","generateXHub256Sig","body","appSecret","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","isMetaError","error","objectToQueryString","params","searchParams","key","value","queryString"]}
|
package/dist/utils/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as
|
|
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,T=30,B=2e4,G=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=>{G(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||parseInt(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||"")||T,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||B,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/utils/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/generateXHub256Sig.ts","../../src/utils/logger.ts","../../src/utils/importConfig.ts","../../src/utils/isMetaError.ts","../../src/utils/objectToQueryString.ts"],"sourcesContent":["import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","// @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.
|
|
1
|
+
{"version":3,"sources":["../../src/utils/generateXHub256Sig.ts","../../src/utils/logger.ts","../../src/utils/importConfig.ts","../../src/utils/isMetaError.ts","../../src/utils/objectToQueryString.ts"],"sourcesContent":["import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","// @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 || parseInt(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};\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n searchParams.append(key, String(value));\n }\n }\n\n const queryString = searchParams.toString();\n return queryString ? `?${queryString}` : '';\n};\n"],"mappings":"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","names":["crypto","generateXHub256Sig","body","appSecret","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","isMetaError","error","objectToQueryString","params","searchParams","key","value","queryString"]}
|
package/dist/whatsapp.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var L=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var J=(r,t)=>{for(var s in t)L(r,s,{get:t[s],enumerable:!0})},Ie=(r,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ge(t))!Pe.call(r,n)&&n!==s&&L(r,n,{get:()=>t[n],enumerable:!(i=he(t,n))||i.enumerable});return r};var Ae=r=>Ie(L({},"__esModule",{value:!0}),r);var $e={};J($e,{default:()=>W});module.exports=Ae($e);var H={};J(H,{AudioMediaTypesEnum:()=>te,BusinessVerticalEnum:()=>Re,ButtonPositionEnum:()=>Z,ButtonTypesEnum:()=>V,CategoryEnum:()=>k,ComponentTypesEnum:()=>Q,ConversationTypesEnum:()=>y,CurrencyCodesEnum:()=>ae,DataLocalizationRegionEnum:()=>pe,DocumentMediaTypesEnum:()=>ee,HttpMethodsEnum:()=>I,ImageMediaTypesEnum:()=>C,InteractiveTypesEnum:()=>j,LanguagesEnum:()=>ne,MessageTypesEnum:()=>K,ParametersTypesEnum:()=>Y,ReferralSourceTypesEnum:()=>oe,RequestCodeMethodsEnum:()=>re,StatusEnum:()=>z,StickerMediaTypesEnum:()=>E,SystemChangeTypesEnum:()=>ie,TemplateStatusEnum:()=>X,VideoMediaTypesEnum:()=>u,WabaConfigEnum:()=>g,WebhookTypesEnum:()=>se});var k=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(k||{}),X=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(X||{}),I=(n=>(n.Get="GET",n.Post="POST",n.Put="PUT",n.Delete="DELETE",n))(I||{}),K=(l=>(l.Audio="audio",l.Contacts="contacts",l.Document="document",l.Image="image",l.Interactive="interactive",l.Location="location",l.Reaction="sticker",l.Sticker="sticker",l.Template="template",l.Text="text",l.Video="video",l))(K||{}),Y=(c=>(c.Currency="currency",c.DateTime="date_time",c.Document="document",c.Image="image",c.Text="text",c.Video="video",c.Payload="payload",c))(Y||{}),j=(R=>(R.Button="button",R.List="list",R.Product="product",R.ProductList="product_list",R.CtaUrl="cta_url",R.LocationRequest="location_request_message",R.AddressMessage="address_message",R.Flow="flow",R))(j||{}),V=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(V||{}),Z=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(Z||{}),Q=(n=>(n.Header="HEADER",n.Body="BODY",n.Button="BUTTON",n.Footer="FOOTER",n))(Q||{}),g=(a=>(a.BaseURL="WA_BASE_URL",a.AppId="M4D_APP_ID",a.Port="WA_PORT",a.AppSecret="M4D_APP_SECRET",a.PhoneNumberId="WA_PHONE_NUMBER_ID",a.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",a.APIVersion="CLOUD_API_VERSION",a.AccessToken="CLOUD_API_ACCESS_TOKEN",a.WebhookEndpoint="WEBHOOK_ENDPOINT",a.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",a.ListenerPort="LISTENER_PORT",a.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",a.RequestTimeout="REQUEST_TIMEOUT",a.Debug="DEBUG",a))(g||{}),y=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(y||{}),z=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(z||{}),u=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(u||{}),E=(t=>(t.Webp="image/webp",t))(E||{}),C=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(C||{}),ee=(R=>(R.Text="text/plain",R.Pdf="application/pdf",R.Ppt="application/vnd.ms-powerpoint",R.Word="application/msword",R.Excel="application/vnd.ms-excel",R.OpenDoc="application/vnd.openxmlformats-officedocument.wordprocessingml.document",R.OpenPres="application/vnd.openxmlformats-officedocument.presentationml.presentation",R.OpenSheet="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",R))(ee||{}),te=(h=>(h.Aac="audio/aac",h.Mp4="audio/mp4",h.Mpeg="audio/mpeg",h.Amr="audio/amr",h.Ogg="audio/ogg",h))(te||{}),se=(l=>(l.Audio="audio",l.Button="button",l.Document="document",l.Text="text",l.Image="image",l.Interactive="interactive",l.Order="order",l.Sticker="sticker",l.System="system",l.Unknown="unknown",l.Video="video",l))(se||{}),ie=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(ie||{}),oe=(s=>(s.Ad="ad",s.Post="post",s))(oe||{}),re=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(re||{}),ne=(o=>(o.Afrikaans="af",o.Albanian="sq",o.Arabic="ar",o.Azerbaijani="az",o.Bengali="bn",o.Bulgarian="bg",o.Catalan="ca",o.Chinese_CHN="zh_CN",o.Chinese_HKG="zh_HK",o.Chinese_TAI="zh_TW",o.Croatian="hr",o.Czech="cs",o.Danish="da",o.Dutch="nl",o.English="en",o.English_UK="en_GB",o.English_US="en_US",o.Estonian="et",o.Filipino="fil",o.Finnish="fi",o.French="fr",o.Georgian="ka",o.German="de",o.Greek="el",o.Gujarati="gu",o.Hausa="ha",o.Hebrew="he",o.Hindi="hi",o.Hungarian="hu",o.Indonesian="id",o.Irish="ga",o.Italian="it",o.Japanese="ja",o.Kannada="kn",o.Kazakh="kk",o.Kinyarwanda="rw_RW",o.Korean="ko",o.Kyrgyz_Kyrgyzstan="ky_KG",o.Lao="lo",o.Latvian="lv",o.Lithuanian="lt",o.Macedonian="mk",o.Malay="ms",o.Malayalam="ml",o.Marathi="mr",o.Norwegian="nb",o.Persian="fa",o.Polish="pl",o.Portuguese_BR="pt_BR",o.Portuguese_POR="pt_PT",o.Punjabi="pa",o.Romanian="ro",o.Russian="ru",o.Serbian="sr",o.Slovak="sk",o.Slovenian="sl",o.Spanish="es",o.Spanish_ARG="es_AR",o.Spanish_SPA="es_ES",o.Spanish_MEX="es_MX",o.Swahili="sw",o.Swedish="sv",o.Tamil="ta",o.Telugu="te",o.Thai="th",o.Turkish="tr",o.Ukrainian="uk",o.Urdu="ur",o.Uzbek="uz",o.Vietnamese="vi",o.Zulu="zu",o))(ne||{}),ae=(e=>(e.AFN="AFN",e.EUR="EUR",e.ALL="ALL",e.DZD="DZD",e.USD="USD",e.AOA="AOA",e.XCD="XCD",e.ARS="ARS",e.AMD="AMD",e.AWG="AWG",e.AUD="AUD",e.AZN="AZN",e.BSD="BSD",e.BHD="BHD",e.BDT="BDT",e.BBD="BBD",e.BYN="BYN",e.BZD="BZD",e.XOF="XOF",e.BMD="BMD",e.INR="INR",e.BTN="BTN",e.BOB="BOB",e.BOV="BOV",e.BAM="BAM",e.BWP="BWP",e.NOK="NOK",e.BRL="BRL",e.BND="BND",e.BGN="BGN",e.BIF="BIF",e.CVE="CVE",e.KHR="KHR",e.XAF="XAF",e.CAD="CAD",e.KYD="KYD",e.CLP="CLP",e.CLF="CLF",e.CNY="CNY",e.COP="COP",e.COU="COU",e.KMF="KMF",e.CDF="CDF",e.NZD="NZD",e.CRC="CRC",e.HRK="HRK",e.CUP="CUP",e.CUC="CUC",e.ANG="ANG",e.CZK="CZK",e.DKK="DKK",e.DJF="DJF",e.DOP="DOP",e.EGP="EGP",e.SVC="SVC",e.ERN="ERN",e.SZL="SZL",e.ETB="ETB",e.FKP="FKP",e.FJD="FJD",e.XPF="XPF",e.GMD="GMD",e.GEL="GEL",e.GHS="GHS",e.GIP="GIP",e.GTQ="GTQ",e.GBP="GBP",e.GNF="GNF",e.GYD="GYD",e.HTG="HTG",e.HNL="HNL",e.HKD="HKD",e.HUF="HUF",e.ISK="ISK",e.IDR="IDR",e.XDR="XDR",e.IRR="IRR",e.IQD="IQD",e.ILS="ILS",e.JMD="JMD",e.JPY="JPY",e.JOD="JOD",e.KZT="KZT",e.KES="KES",e.KPW="KPW",e.KRW="KRW",e.KWD="KWD",e.KGS="KGS",e.LAK="LAK",e.LBP="LBP",e.LSL="LSL",e.ZAR="ZAR",e.LRD="LRD",e.LYD="LYD",e.CHF="CHF",e.MOP="MOP",e.MKD="MKD",e.MGA="MGA",e.MWK="MWK",e.MYR="MYR",e.MVR="MVR",e.MRU="MRU",e.MUR="MUR",e.XUA="XUA",e.MXN="MXN",e.MXV="MXV",e.MDL="MDL",e.MNT="MNT",e.MAD="MAD",e.MZN="MZN",e.MMK="MMK",e.NAD="NAD",e.NPR="NPR",e.NIO="NIO",e.NGN="NGN",e.OMR="OMR",e.PKR="PKR",e.PAB="PAB",e.PGK="PGK",e.PYG="PYG",e.PEN="PEN",e.PHP="PHP",e.PLN="PLN",e.QAR="QAR",e.RON="RON",e.RUB="RUB",e.RWF="RWF",e.SHP="SHP",e.WST="WST",e.STN="STN",e.SAR="SAR",e.RSD="RSD",e.SCR="SCR",e.SLL="SLL",e.SGD="SGD",e.XSU="XSU",e.SBD="SBD",e.SOS="SOS",e.SSP="SSP",e.LKR="LKR",e.SDG="SDG",e.SRD="SRD",e.SEK="SEK",e.CHE="CHE",e.CHW="CHW",e.SYP="SYP",e.TWD="TWD",e.TJS="TJS",e.TZS="TZS",e.THB="THB",e.TOP="TOP",e.TTD="TTD",e.TND="TND",e.TRY="TRY",e.TMT="TMT",e.UGX="UGX",e.UAH="UAH",e.AED="AED",e.USN="USN",e.UYU="UYU",e.UYI="UYI",e.UYW="UYW",e.UZS="UZS",e.VUV="VUV",e.VES="VES",e.VND="VND",e.YER="YER",e.ZMW="ZMW",e.ZWL="ZWL",e.XBA="XBA",e.XBB="XBB",e.XBC="XBC",e.XBD="XBD",e.XTS="XTS",e.XXX="XXX",e.XAU="XAU",e.XPD="XPD",e.XPT="XPT",e.XAG="XAG",e.AFA="AFA",e.FIM="FIM",e.ALK="ALK",e.ADP="ADP",e.ESP="ESP",e.FRF="FRF",e.AOK="AOK",e.AON="AON",e.AOR="AOR",e.ARA="ARA",e.ARP="ARP",e.ARY="ARY",e.RUR="RUR",e.ATS="ATS",e.AYM="AYM",e.AZM="AZM",e.BYB="BYB",e.BYR="BYR",e.BEC="BEC",e.BEF="BEF",e.BEL="BEL",e.BOP="BOP",e.BAD="BAD",e.BRB="BRB",e.BRC="BRC",e.BRE="BRE",e.BRN="BRN",e.BRR="BRR",e.BGJ="BGJ",e.BGK="BGK",e.BGL="BGL",e.BUK="BUK",e.HRD="HRD",e.CYP="CYP",e.CSJ="CSJ",e.CSK="CSK",e.ECS="ECS",e.ECV="ECV",e.GQE="GQE",e.EEK="EEK",e.XEU="XEU",e.GEK="GEK",e.DDM="DDM",e.DEM="DEM",e.GHC="GHC",e.GHP="GHP",e.GRD="GRD",e.GNE="GNE",e.GNS="GNS",e.GWE="GWE",e.GWP="GWP",e.ITL="ITL",e.ISJ="ISJ",e.IEP="IEP",e.ILP="ILP",e.ILR="ILR",e.LAJ="LAJ",e.LVL="LVL",e.LVR="LVR",e.LSM="LSM",e.ZAL="ZAL",e.LTL="LTL",e.LTT="LTT",e.LUC="LUC",e.LUF="LUF",e.LUL="LUL",e.MGF="MGF",e.MVQ="MVQ",e.MLF="MLF",e.MTL="MTL",e.MTP="MTP",e.MRO="MRO",e.MXP="MXP",e.MZE="MZE",e.MZM="MZM",e.NLG="NLG",e.NIC="NIC",e.PEH="PEH",e.PEI="PEI",e.PES="PES",e.PLZ="PLZ",e.PTE="PTE",e.ROK="ROK",e.ROL="ROL",e.STD="STD",e.CSD="CSD",e.SKK="SKK",e.SIT="SIT",e.RHD="RHD",e.ESA="ESA",e.ESB="ESB",e.SDD="SDD",e.SDP="SDP",e.SRG="SRG",e.CHC="CHC",e.TJR="TJR",e.TPE="TPE",e.TRL="TRL",e.TMM="TMM",e.UGS="UGS",e.UGW="UGW",e.UAK="UAK",e.SUR="SUR",e.USS="USS",e.UYN="UYN",e.UYP="UYP",e.VEB="VEB",e.VEF="VEF",e.VNC="VNC",e.YDD="YDD",e.YUD="YUD",e.YUM="YUM",e.YUN="YUN",e.ZRN="ZRN",e.ZRZ="ZRZ",e.ZMK="ZMK",e.ZWC="ZWC",e.ZWD="ZWD",e.ZWN="ZWN",e.ZWR="ZWR",e.XFO="XFO",e.XRE="XRE",e.XFU="XFU",e))(ae||{}),pe=(a=>(a.AU="AU",a.ID="ID",a.IN="IN",a.JP="JP",a.SG="SG",a.KR="KR",a.DE="DE",a.CH="CH",a.GB="GB",a.BR="BR",a.BH="BH",a.ZA="ZA",a.AE="AE",a.CA="CA",a))(pe||{}),Re=(f=>(f.ALCOHOL="ALCOHOL",f.APPAREL="APPAREL",f.AUTO="AUTO",f.BEAUTY="BEAUTY",f.EDU="EDU",f.ENTERTAIN="ENTERTAIN",f.EVENT_PLAN="EVENT_PLAN",f.FINANCE="FINANCE",f.GOVT="GOVT",f.GROCERY="GROCERY",f.HEALTH="HEALTH",f.HOTEL="HOTEL",f.NONPROFIT="NONPROFIT",f.ONLINE_GAMBLING="ONLINE_GAMBLING",f.OTC_DRUGS="OTC_DRUGS",f.OTHER="OTHER",f.PHYSICAL_GAMBLING="PHYSICAL_GAMBLING",f.PROF_SERVICES="PROF_SERVICES",f.RESTAURANT="RESTAURANT",f.RETAIL="RETAIL",f.TRAVEL="TRAVEL",f))(Re||{});var P=class{name;debug;constructor(t,s=!1){this.name=t,this.debug=s}log(...t){if(this.debug){let s=`[ ${Date.now()} ]`;this.name&&(s+=` - ${this.name}`),console.log.apply(console,[s,": ",...t])}}error(...t){let s=`[ ${Date.now()} ] - ERROR`;this.name&&(s+=` - ${this.name}`),console.error.apply(console,[s,": ",...t])}warn(...t){let s=`[ ${Date.now()} ] - WARN`;this.name&&(s+=` - ${this.name}`),console.warn.apply(console,[s,": ",...t])}info(...t){let s=`[ ${Date.now()} ] - INFO`;this.name&&(s+=` - ${this.name}`),console.info.apply(console,[s,": ",...t])}};var Se="BaseAPI",Te=!1,de=new P(Se,process.env.DEBUG==="true"||Te),p=class{config;client;constructor(t,s){this.config=t,this.client=s,de.log("Initialized with HTTPSClient")}};var A=r=>{if(!r||Object.keys(r).length===0)return"";let t=new URLSearchParams;for(let[i,n]of Object.entries(r))n!==void 0&&t.append(i,String(n));let s=t.toString();return s?`?${s}`:""};var S=class extends p{endpoint="whatsapp_business_profile";constructor(t,s){super(t,s)}async getBusinessProfile(t){let s=t?A({fields:t}):"";return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${s}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async createUploadSession(t,s,i){let n=A({file_length:t,file_type:s,file_name:i});return this.client.sendRequest("POST",`app/uploads/${n}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s){return this.client.sendRequest("POST",`${t}`,this.config.REQUEST_TIMEOUT,s)}async getUploadHandle(t){return this.client.sendRequest("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}};var T=class extends p{endpoint="whatsapp_business_encryption";constructor(t,s){super(t,s)}async getEncryptionPublicKey(){return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(t){let s=new FormData;return s.append("business_public_key",t),this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}};var be="FlowAPI",qe=!1,me=new P(be,process.env.DEBUG==="true"||qe),d=class extends p{constructor(t,s){super(t,s),me.log("FlowAPI initialized")}async listFlows(t){return this.client.sendRequest("GET",`/${t}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(t,s){let i=new FormData;return s.name&&i.append("name",s.name),s.categories&&i.append("categories",JSON.stringify(s.categories)),s.endpoint_uri&&i.append("endpoint_uri",s.endpoint_uri),s.clone_flow_id&&i.append("clone_flow_id",s.clone_flow_id),s.flow_json&&i.append("flow_json",s.flow_json),s.publish!==void 0&&i.append("publish",String(s.publish)),this.client.sendRequest("POST",`/${t}/flows`,this.config.REQUEST_TIMEOUT,i)}async getFlow(t,s,i){let n=new URLSearchParams;s&&n.append("fields",s),i&&n.append("date_format",i);let h=n.toString()?`?${n.toString()}`:"";return this.client.sendRequest("GET",`/${t}${h}`,this.config.REQUEST_TIMEOUT,null)}async updateFlowMetadata(t,s){let i=new FormData;return s.name&&i.append("name",s.name),s.categories&&i.append("categories",JSON.stringify(s.categories)),s.endpoint_uri&&i.append("endpoint_uri",s.endpoint_uri),s.application_id&&i.append("application_id",s.application_id),this.client.sendRequest("POST",`/${t}`,this.config.REQUEST_TIMEOUT,i)}async deleteFlow(t){return this.client.sendRequest("DELETE",`/${t}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(t){return this.client.sendRequest("GET",`/${t}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(t,s){let i=new FormData;return i.append("asset_type",s.asset_type),i.append("file",s.file),i.append("name",s.name),this.client.sendRequest("POST",`/${t}/assets`,this.config.REQUEST_TIMEOUT,i)}async publishFlow(t){return this.client.sendRequest("POST",`/${t}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(t){return this.client.sendRequest("POST",`/${t}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(t,s){let i=new FormData;return i.append("source_waba_id",s.source_waba_id),s.source_flow_names&&i.append("source_flow_names",JSON.stringify(s.source_flow_names)),this.client.sendRequest("POST",`/${t}/migrate_flows`,this.config.REQUEST_TIMEOUT,i)}};var b=class extends p{endpoint="media";constructor(t,s){super(t,s)}async getMediaById(t){return this.client.sendRequest("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s="whatsapp"){let i=new FormData;return i.append("file",t),i.append("messaging_product",s),i.append("type",t.type),this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,i)}async deleteMedia(t){return this.client.sendRequest("DELETE",`${t}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(t){return this.client.sendRequest("GET",t,this.config.REQUEST_TIMEOUT,null)}};var q=class extends p{commonMethod="POST";commonEndpoint="messages";constructor(t,s){super(t,s)}bodyBuilder(t,s,i,n){let h={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:t,[t]:s};return n&&(h.context={message_id:n}),h}send(t){return this.client.sendRequest(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,t)}async audio(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("audio",t,s.toString(),i)))}async contacts(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("contacts",t,s.toString(),i)))}async document(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("document",t,s.toString(),i)))}async image(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("image",t,s.toString(),i)))}async interactive(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async location(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("location",t,s.toString(),i)))}async sticker(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("sticker",t,s.toString(),i)))}async template(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("template",t,s.toString(),i)))}async text(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("text",t,s.toString(),i)))}async video(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("video",t,s.toString(),i)))}async status(t){let s={messaging_product:"whatsapp",...t};return this.send(JSON.stringify(s))}async markAsRead(t){return this.status({status:"read",message_id:t})}async showTypingIndicator(t){return this.status({status:"read",message_id:t,typing_indicator:{type:"text"}})}async interactiveList(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveCtaUrl(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveLocationRequest(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveAddressMessage(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveReplyButtons(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveFlow(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async reaction(t,s,i){let n={messaging_product:"whatsapp",recipient_type:"individual",to:i.toString(),type:"reaction",reaction:{message_id:t,emoji:s}};return this.send(JSON.stringify(n))}};var m=class extends p{endpoint="phone_numbers";constructor(t,s){super(t,s)}async getPhoneNumberById(t){let s=t?A({fields:t}):"";return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.client.sendRequest("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var N=class extends p{endpoint="message_qrdls";constructor(t,s){super(t,s)}async createQrCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getQrCodes(){return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(t){return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteQrCode(t){return this.client.sendRequest("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}};var _=class extends p{constructor(t,s){super(t,s)}async register(t,s){let i={messaging_product:"whatsapp",pin:t,...s&&{data_localization_region:s}};return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deregister(){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var O=class extends p{endpoint="message_templates";constructor(t,s){super(t,s)}async getTemplate(t){return this.client.sendRequest("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(t,s){return this.client.sendRequest("POST",`${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(t){return this.client.sendRequest("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${A(t)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(t){return this.client.sendRequest("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteTemplate(t){return this.client.sendRequest("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${A(t)}`,this.config.REQUEST_TIMEOUT,null)}};var D=class extends p{constructor(t,s){super(t,s)}async setTwoStepVerificationCode(t){let s={pin:t};return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var B=class extends p{constructor(t,s){super(t,s)}async getAllWabaSubscriptions(){return this.client.sendRequest("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async subscribeToWaba(){return this.client.sendRequest("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async unsubscribeFromWaba(){return this.client.sendRequest("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async overrideWabaWebhook(t,s){let i={url:t,verify_token:s};return this.client.sendRequest("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/webhooks`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}};var le=require("https");var Ne="HttpsClient",_e=!1,Oe=new P(Ne,process.env.DEBUG==="true"||_e),U=class{agent;constructor(){this.agent=new le.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,n,h,M){let c=`https://${t}/${s}`,R=new AbortController,fe=setTimeout(()=>R.abort(),h);try{let F=await fetch(c,{method:i,headers:n,body:M,signal:R.signal});return Oe.log(`${i} : ${c} - ${JSON.stringify(F)}`),clearTimeout(fe),new x(F)}catch(F){throw F}}},x=class{res;respStatusCode;respHeaders;constructor(t){this.res=t,this.respStatusCode=t.status,this.respHeaders=Object.fromEntries(t.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(t){throw new Error("Failed to parse response body to JSON: "+t.message)}}};function v(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var De="REQUESTER",Be=!1,Me=new P(De,process.env.DEBUG==="true"||Be),w=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,n,h,M){this.client=new U,this.host=t||"graph.facebook.com",this.apiVersion=s||"22",this.phoneNumberId=i,this.accessToken=n,this.businessAcctId=h,this.userAgent=M}buildHeader(t){return{"Content-Type":t,Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent}}buildCAPIPath(t){return`v${this.apiVersion}.0/${t}`}async sendRequest(t,s,i,n){let h="application/json",M=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;Me.log(`${t} : ${M}`);try{let c=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(h),i,t==="POST"||t==="PUT"?n:void 0);if(!c.rawResponse().ok){let R=await c.json();throw v(R)?R:{name:"MetaError",message:"Unknown error occurred",error:{message:R.message||"Unknown error occurred",type:"UnknownError",code:c.statusCode(),fbtrace_id:""}}}return c}catch(c){throw v(c)?c:{name:"MetaError",message:c instanceof Error?c.message:"Network error occurred",error:{message:c instanceof Error?c.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}};var Ue="UTILS",we=!1,$=new P(Ue,process.env.DEBUG==="true"||we),Ge="graph.facebook.com",Fe=3e3,We=30,Le=2e4,Ke=r=>{if(!process.env.WA_PHONE_NUMBER_ID&&!r?.phoneNumberId)throw $.log("Environmental variable: WA_PHONE_NUMBER_ID and/or sender phone number id argument is undefined."),new Error("Missing WhatsApp sender phone number Id.");if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw $.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},ce=r=>{Ke(r);let t={WA_BASE_URL:process.env.WA_BASE_URL||Ge,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:r?.phoneNumberId||parseInt(process.env.WA_PHONE_NUMBER_ID||""),WA_BUSINESS_ACCOUNT_ID:process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.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||"")||Fe,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||We,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||Le,DEBUG:process.env.DEBUG==="true"};return $.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};var He="WHATSAPP",xe=!1,G=new P(He,process.env.DEBUG==="true"||xe),ve="WA_SDK",W=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=H;constructor(t){this.config=ce(t),this.requester=new w(this.config.WA_BASE_URL,this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID||t?.phoneNumberId||0,this.config.CLOUD_API_ACCESS_TOKEN||t?.accessToken||"",this.config.WA_BUSINESS_ACCOUNT_ID||t?.businessAcctId||"",this.userAgent()),this.messages=new q(this.config,this.requester),this.templates=new O(this.config,this.requester),this.phoneNumber=new m(this.config,this.requester),this.qrCode=new N(this.config,this.requester),this.encryption=new T(this.config,this.requester),this.twoStepVerification=new D(this.config,this.requester),this.registration=new _(this.config,this.requester),this.media=new b(this.config,this.requester),this.waba=new B(this.config,this.requester),this.flow=new d(this.config,this.requester),this.businessProfile=new S(this.config,this.requester),G.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${ve}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,G.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,G.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,G.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,G.log(`Updated business account id to ${t}`),!0}};
|
|
1
|
+
"use strict";var W=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var $=(r,t)=>{for(var s in t)W(r,s,{get:t[s],enumerable:!0})},Ie=(r,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ge(t))!Pe.call(r,n)&&n!==s&&W(r,n,{get:()=>t[n],enumerable:!(i=he(t,n))||i.enumerable});return r};var Ae=r=>Ie(W({},"__esModule",{value:!0}),r);var $e={};$($e,{default:()=>L});module.exports=Ae($e);var H={};$(H,{AudioMediaTypesEnum:()=>ee,BusinessVerticalEnum:()=>pe,ButtonPositionEnum:()=>V,ButtonTypesEnum:()=>j,CategoryEnum:()=>J,ComponentTypesEnum:()=>Z,ConversationTypesEnum:()=>Q,CurrencyCodesEnum:()=>ne,DataLocalizationRegionEnum:()=>ae,DocumentMediaTypesEnum:()=>C,HttpMethodsEnum:()=>I,ImageMediaTypesEnum:()=>E,InteractiveTypesEnum:()=>Y,LanguagesEnum:()=>re,MessageTypesEnum:()=>K,ParametersTypesEnum:()=>k,ReferralSourceTypesEnum:()=>ie,RequestCodeMethodsEnum:()=>oe,StatusEnum:()=>y,StickerMediaTypesEnum:()=>u,SystemChangeTypesEnum:()=>se,TemplateStatusEnum:()=>X,VideoMediaTypesEnum:()=>z,WabaConfigEnum:()=>g,WebhookTypesEnum:()=>te});var J=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(J||{}),X=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(X||{}),I=(n=>(n.Get="GET",n.Post="POST",n.Put="PUT",n.Delete="DELETE",n))(I||{}),K=(l=>(l.Audio="audio",l.Contacts="contacts",l.Document="document",l.Image="image",l.Interactive="interactive",l.Location="location",l.Reaction="sticker",l.Sticker="sticker",l.Template="template",l.Text="text",l.Video="video",l))(K||{}),k=(f=>(f.Currency="currency",f.DateTime="date_time",f.Document="document",f.Image="image",f.Text="text",f.Video="video",f.Payload="payload",f))(k||{}),Y=(R=>(R.Button="button",R.List="list",R.Product="product",R.ProductList="product_list",R.CtaUrl="cta_url",R.LocationRequest="location_request_message",R.AddressMessage="address_message",R.Flow="flow",R))(Y||{}),j=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(j||{}),V=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(V||{}),Z=(n=>(n.Header="HEADER",n.Body="BODY",n.Button="BUTTON",n.Footer="FOOTER",n))(Z||{}),g=(a=>(a.BaseURL="WA_BASE_URL",a.AppId="M4D_APP_ID",a.Port="WA_PORT",a.AppSecret="M4D_APP_SECRET",a.PhoneNumberId="WA_PHONE_NUMBER_ID",a.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",a.APIVersion="CLOUD_API_VERSION",a.AccessToken="CLOUD_API_ACCESS_TOKEN",a.WebhookEndpoint="WEBHOOK_ENDPOINT",a.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",a.ListenerPort="LISTENER_PORT",a.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",a.RequestTimeout="REQUEST_TIMEOUT",a.Debug="DEBUG",a))(g||{}),Q=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(Q||{}),y=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(y||{}),z=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(z||{}),u=(t=>(t.Webp="image/webp",t))(u||{}),E=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(E||{}),C=(R=>(R.Text="text/plain",R.Pdf="application/pdf",R.Ppt="application/vnd.ms-powerpoint",R.Word="application/msword",R.Excel="application/vnd.ms-excel",R.OpenDoc="application/vnd.openxmlformats-officedocument.wordprocessingml.document",R.OpenPres="application/vnd.openxmlformats-officedocument.presentationml.presentation",R.OpenSheet="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",R))(C||{}),ee=(h=>(h.Aac="audio/aac",h.Mp4="audio/mp4",h.Mpeg="audio/mpeg",h.Amr="audio/amr",h.Ogg="audio/ogg",h))(ee||{}),te=(l=>(l.Audio="audio",l.Button="button",l.Document="document",l.Text="text",l.Image="image",l.Interactive="interactive",l.Order="order",l.Sticker="sticker",l.System="system",l.Unknown="unknown",l.Video="video",l))(te||{}),se=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(se||{}),ie=(s=>(s.Ad="ad",s.Post="post",s))(ie||{}),oe=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(oe||{}),re=(o=>(o.Afrikaans="af",o.Albanian="sq",o.Arabic="ar",o.Azerbaijani="az",o.Bengali="bn",o.Bulgarian="bg",o.Catalan="ca",o.Chinese_CHN="zh_CN",o.Chinese_HKG="zh_HK",o.Chinese_TAI="zh_TW",o.Croatian="hr",o.Czech="cs",o.Danish="da",o.Dutch="nl",o.English="en",o.English_UK="en_GB",o.English_US="en_US",o.Estonian="et",o.Filipino="fil",o.Finnish="fi",o.French="fr",o.Georgian="ka",o.German="de",o.Greek="el",o.Gujarati="gu",o.Hausa="ha",o.Hebrew="he",o.Hindi="hi",o.Hungarian="hu",o.Indonesian="id",o.Irish="ga",o.Italian="it",o.Japanese="ja",o.Kannada="kn",o.Kazakh="kk",o.Kinyarwanda="rw_RW",o.Korean="ko",o.Kyrgyz_Kyrgyzstan="ky_KG",o.Lao="lo",o.Latvian="lv",o.Lithuanian="lt",o.Macedonian="mk",o.Malay="ms",o.Malayalam="ml",o.Marathi="mr",o.Norwegian="nb",o.Persian="fa",o.Polish="pl",o.Portuguese_BR="pt_BR",o.Portuguese_POR="pt_PT",o.Punjabi="pa",o.Romanian="ro",o.Russian="ru",o.Serbian="sr",o.Slovak="sk",o.Slovenian="sl",o.Spanish="es",o.Spanish_ARG="es_AR",o.Spanish_SPA="es_ES",o.Spanish_MEX="es_MX",o.Swahili="sw",o.Swedish="sv",o.Tamil="ta",o.Telugu="te",o.Thai="th",o.Turkish="tr",o.Ukrainian="uk",o.Urdu="ur",o.Uzbek="uz",o.Vietnamese="vi",o.Zulu="zu",o))(re||{}),ne=(e=>(e.AFN="AFN",e.EUR="EUR",e.ALL="ALL",e.DZD="DZD",e.USD="USD",e.AOA="AOA",e.XCD="XCD",e.ARS="ARS",e.AMD="AMD",e.AWG="AWG",e.AUD="AUD",e.AZN="AZN",e.BSD="BSD",e.BHD="BHD",e.BDT="BDT",e.BBD="BBD",e.BYN="BYN",e.BZD="BZD",e.XOF="XOF",e.BMD="BMD",e.INR="INR",e.BTN="BTN",e.BOB="BOB",e.BOV="BOV",e.BAM="BAM",e.BWP="BWP",e.NOK="NOK",e.BRL="BRL",e.BND="BND",e.BGN="BGN",e.BIF="BIF",e.CVE="CVE",e.KHR="KHR",e.XAF="XAF",e.CAD="CAD",e.KYD="KYD",e.CLP="CLP",e.CLF="CLF",e.CNY="CNY",e.COP="COP",e.COU="COU",e.KMF="KMF",e.CDF="CDF",e.NZD="NZD",e.CRC="CRC",e.HRK="HRK",e.CUP="CUP",e.CUC="CUC",e.ANG="ANG",e.CZK="CZK",e.DKK="DKK",e.DJF="DJF",e.DOP="DOP",e.EGP="EGP",e.SVC="SVC",e.ERN="ERN",e.SZL="SZL",e.ETB="ETB",e.FKP="FKP",e.FJD="FJD",e.XPF="XPF",e.GMD="GMD",e.GEL="GEL",e.GHS="GHS",e.GIP="GIP",e.GTQ="GTQ",e.GBP="GBP",e.GNF="GNF",e.GYD="GYD",e.HTG="HTG",e.HNL="HNL",e.HKD="HKD",e.HUF="HUF",e.ISK="ISK",e.IDR="IDR",e.XDR="XDR",e.IRR="IRR",e.IQD="IQD",e.ILS="ILS",e.JMD="JMD",e.JPY="JPY",e.JOD="JOD",e.KZT="KZT",e.KES="KES",e.KPW="KPW",e.KRW="KRW",e.KWD="KWD",e.KGS="KGS",e.LAK="LAK",e.LBP="LBP",e.LSL="LSL",e.ZAR="ZAR",e.LRD="LRD",e.LYD="LYD",e.CHF="CHF",e.MOP="MOP",e.MKD="MKD",e.MGA="MGA",e.MWK="MWK",e.MYR="MYR",e.MVR="MVR",e.MRU="MRU",e.MUR="MUR",e.XUA="XUA",e.MXN="MXN",e.MXV="MXV",e.MDL="MDL",e.MNT="MNT",e.MAD="MAD",e.MZN="MZN",e.MMK="MMK",e.NAD="NAD",e.NPR="NPR",e.NIO="NIO",e.NGN="NGN",e.OMR="OMR",e.PKR="PKR",e.PAB="PAB",e.PGK="PGK",e.PYG="PYG",e.PEN="PEN",e.PHP="PHP",e.PLN="PLN",e.QAR="QAR",e.RON="RON",e.RUB="RUB",e.RWF="RWF",e.SHP="SHP",e.WST="WST",e.STN="STN",e.SAR="SAR",e.RSD="RSD",e.SCR="SCR",e.SLL="SLL",e.SGD="SGD",e.XSU="XSU",e.SBD="SBD",e.SOS="SOS",e.SSP="SSP",e.LKR="LKR",e.SDG="SDG",e.SRD="SRD",e.SEK="SEK",e.CHE="CHE",e.CHW="CHW",e.SYP="SYP",e.TWD="TWD",e.TJS="TJS",e.TZS="TZS",e.THB="THB",e.TOP="TOP",e.TTD="TTD",e.TND="TND",e.TRY="TRY",e.TMT="TMT",e.UGX="UGX",e.UAH="UAH",e.AED="AED",e.USN="USN",e.UYU="UYU",e.UYI="UYI",e.UYW="UYW",e.UZS="UZS",e.VUV="VUV",e.VES="VES",e.VND="VND",e.YER="YER",e.ZMW="ZMW",e.ZWL="ZWL",e.XBA="XBA",e.XBB="XBB",e.XBC="XBC",e.XBD="XBD",e.XTS="XTS",e.XXX="XXX",e.XAU="XAU",e.XPD="XPD",e.XPT="XPT",e.XAG="XAG",e.AFA="AFA",e.FIM="FIM",e.ALK="ALK",e.ADP="ADP",e.ESP="ESP",e.FRF="FRF",e.AOK="AOK",e.AON="AON",e.AOR="AOR",e.ARA="ARA",e.ARP="ARP",e.ARY="ARY",e.RUR="RUR",e.ATS="ATS",e.AYM="AYM",e.AZM="AZM",e.BYB="BYB",e.BYR="BYR",e.BEC="BEC",e.BEF="BEF",e.BEL="BEL",e.BOP="BOP",e.BAD="BAD",e.BRB="BRB",e.BRC="BRC",e.BRE="BRE",e.BRN="BRN",e.BRR="BRR",e.BGJ="BGJ",e.BGK="BGK",e.BGL="BGL",e.BUK="BUK",e.HRD="HRD",e.CYP="CYP",e.CSJ="CSJ",e.CSK="CSK",e.ECS="ECS",e.ECV="ECV",e.GQE="GQE",e.EEK="EEK",e.XEU="XEU",e.GEK="GEK",e.DDM="DDM",e.DEM="DEM",e.GHC="GHC",e.GHP="GHP",e.GRD="GRD",e.GNE="GNE",e.GNS="GNS",e.GWE="GWE",e.GWP="GWP",e.ITL="ITL",e.ISJ="ISJ",e.IEP="IEP",e.ILP="ILP",e.ILR="ILR",e.LAJ="LAJ",e.LVL="LVL",e.LVR="LVR",e.LSM="LSM",e.ZAL="ZAL",e.LTL="LTL",e.LTT="LTT",e.LUC="LUC",e.LUF="LUF",e.LUL="LUL",e.MGF="MGF",e.MVQ="MVQ",e.MLF="MLF",e.MTL="MTL",e.MTP="MTP",e.MRO="MRO",e.MXP="MXP",e.MZE="MZE",e.MZM="MZM",e.NLG="NLG",e.NIC="NIC",e.PEH="PEH",e.PEI="PEI",e.PES="PES",e.PLZ="PLZ",e.PTE="PTE",e.ROK="ROK",e.ROL="ROL",e.STD="STD",e.CSD="CSD",e.SKK="SKK",e.SIT="SIT",e.RHD="RHD",e.ESA="ESA",e.ESB="ESB",e.SDD="SDD",e.SDP="SDP",e.SRG="SRG",e.CHC="CHC",e.TJR="TJR",e.TPE="TPE",e.TRL="TRL",e.TMM="TMM",e.UGS="UGS",e.UGW="UGW",e.UAK="UAK",e.SUR="SUR",e.USS="USS",e.UYN="UYN",e.UYP="UYP",e.VEB="VEB",e.VEF="VEF",e.VNC="VNC",e.YDD="YDD",e.YUD="YUD",e.YUM="YUM",e.YUN="YUN",e.ZRN="ZRN",e.ZRZ="ZRZ",e.ZMK="ZMK",e.ZWC="ZWC",e.ZWD="ZWD",e.ZWN="ZWN",e.ZWR="ZWR",e.XFO="XFO",e.XRE="XRE",e.XFU="XFU",e))(ne||{}),ae=(a=>(a.AU="AU",a.ID="ID",a.IN="IN",a.JP="JP",a.SG="SG",a.KR="KR",a.DE="DE",a.CH="CH",a.GB="GB",a.BR="BR",a.BH="BH",a.ZA="ZA",a.AE="AE",a.CA="CA",a))(ae||{}),pe=(c=>(c.ALCOHOL="ALCOHOL",c.APPAREL="APPAREL",c.AUTO="AUTO",c.BEAUTY="BEAUTY",c.EDU="EDU",c.ENTERTAIN="ENTERTAIN",c.EVENT_PLAN="EVENT_PLAN",c.FINANCE="FINANCE",c.GOVT="GOVT",c.GROCERY="GROCERY",c.HEALTH="HEALTH",c.HOTEL="HOTEL",c.NONPROFIT="NONPROFIT",c.ONLINE_GAMBLING="ONLINE_GAMBLING",c.OTC_DRUGS="OTC_DRUGS",c.OTHER="OTHER",c.PHYSICAL_GAMBLING="PHYSICAL_GAMBLING",c.PROF_SERVICES="PROF_SERVICES",c.RESTAURANT="RESTAURANT",c.RETAIL="RETAIL",c.TRAVEL="TRAVEL",c))(pe||{});var P=class{name;debug;constructor(t,s=!1){this.name=t,this.debug=s}log(...t){if(this.debug){let s=`[ ${Date.now()} ]`;this.name&&(s+=` - ${this.name}`),console.log.apply(console,[s,": ",...t])}}error(...t){let s=`[ ${Date.now()} ] - ERROR`;this.name&&(s+=` - ${this.name}`),console.error.apply(console,[s,": ",...t])}warn(...t){let s=`[ ${Date.now()} ] - WARN`;this.name&&(s+=` - ${this.name}`),console.warn.apply(console,[s,": ",...t])}info(...t){let s=`[ ${Date.now()} ] - INFO`;this.name&&(s+=` - ${this.name}`),console.info.apply(console,[s,": ",...t])}};var Se="BaseAPI",Te=!1,de=new P(Se,process.env.DEBUG==="true"||Te),p=class{config;client;constructor(t,s){this.config=t,this.client=s,de.log("Initialized with HTTPSClient")}};var A=r=>{if(!r||Object.keys(r).length===0)return"";let t=new URLSearchParams;for(let[i,n]of Object.entries(r))n!==void 0&&t.append(i,String(n));let s=t.toString();return s?`?${s}`:""};var S=class extends p{endpoint="whatsapp_business_profile";constructor(t,s){super(t,s)}async getBusinessProfile(t){let s=t?A({fields:t}):"";return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${s}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async createUploadSession(t,s,i){let n=A({file_length:t,file_type:s,file_name:i});return this.client.sendRequest("POST",`app/uploads/${n}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s){return this.client.sendRequest("POST",`${t}`,this.config.REQUEST_TIMEOUT,s)}async getUploadHandle(t){return this.client.sendRequest("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}};var T=class extends p{endpoint="whatsapp_business_encryption";constructor(t,s){super(t,s)}async getEncryptionPublicKey(){return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(t){let s=new FormData;return s.append("business_public_key",t),this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}};var be="FlowAPI",qe=!1,me=new P(be,process.env.DEBUG==="true"||qe),d=class extends p{constructor(t,s){super(t,s),me.log("FlowAPI initialized")}async listFlows(t){return this.client.sendRequest("GET",`/${t}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(t,s){let i=new FormData;return s.name&&i.append("name",s.name),s.categories&&i.append("categories",JSON.stringify(s.categories)),s.endpoint_uri&&i.append("endpoint_uri",s.endpoint_uri),s.clone_flow_id&&i.append("clone_flow_id",s.clone_flow_id),s.flow_json&&i.append("flow_json",s.flow_json),s.publish!==void 0&&i.append("publish",String(s.publish)),this.client.sendRequest("POST",`/${t}/flows`,this.config.REQUEST_TIMEOUT,i)}async getFlow(t,s,i){let n=new URLSearchParams;s&&n.append("fields",s),i&&n.append("date_format",i);let h=n.toString()?`?${n.toString()}`:"";return this.client.sendRequest("GET",`/${t}${h}`,this.config.REQUEST_TIMEOUT,null)}async updateFlowMetadata(t,s){let i=new FormData;return s.name&&i.append("name",s.name),s.categories&&i.append("categories",JSON.stringify(s.categories)),s.endpoint_uri&&i.append("endpoint_uri",s.endpoint_uri),s.application_id&&i.append("application_id",s.application_id),this.client.sendRequest("POST",`/${t}`,this.config.REQUEST_TIMEOUT,i)}async deleteFlow(t){return this.client.sendRequest("DELETE",`/${t}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(t){return this.client.sendRequest("GET",`/${t}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(t,s){let i=new FormData;return i.append("asset_type",s.asset_type),i.append("file",s.file),i.append("name",s.name),this.client.sendRequest("POST",`/${t}/assets`,this.config.REQUEST_TIMEOUT,i)}async publishFlow(t){return this.client.sendRequest("POST",`/${t}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(t){return this.client.sendRequest("POST",`/${t}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(t,s){let i=new FormData;return i.append("source_waba_id",s.source_waba_id),s.source_flow_names&&i.append("source_flow_names",JSON.stringify(s.source_flow_names)),this.client.sendRequest("POST",`/${t}/migrate_flows`,this.config.REQUEST_TIMEOUT,i)}};var b=class extends p{endpoint="media";constructor(t,s){super(t,s)}async getMediaById(t){return this.client.sendRequest("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s="whatsapp"){let i=new FormData;return i.append("file",t),i.append("messaging_product",s),i.append("type",t.type),this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,i)}async deleteMedia(t){return this.client.sendRequest("DELETE",`${t}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(t){return this.client.sendRequest("GET",t,this.config.REQUEST_TIMEOUT,null)}};var q=class extends p{commonMethod="POST";commonEndpoint="messages";constructor(t,s){super(t,s)}bodyBuilder(t,s,i,n){let h={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:t,[t]:s};return n&&(h.context={message_id:n}),h}send(t){return this.client.sendRequest(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,t)}async audio(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("audio",t,s.toString(),i)))}async contacts(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("contacts",t,s.toString(),i)))}async document(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("document",t,s.toString(),i)))}async image(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("image",t,s.toString(),i)))}async interactive(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async location(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("location",t,s.toString(),i)))}async sticker(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("sticker",t,s.toString(),i)))}async template(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("template",t,s.toString(),i)))}async text(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("text",t,s.toString(),i)))}async video(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("video",t,s.toString(),i)))}async status(t){let s={messaging_product:"whatsapp",...t};return this.send(JSON.stringify(s))}async markAsRead(t){return this.status({status:"read",message_id:t})}async showTypingIndicator(t){return this.status({status:"read",message_id:t,typing_indicator:{type:"text"}})}async interactiveList(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveCtaUrl(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveLocationRequest(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveAddressMessage(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveReplyButtons(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async interactiveFlow(t,s,i){return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s.toString(),i)))}async reaction(t,s,i){let n={messaging_product:"whatsapp",recipient_type:"individual",to:i.toString(),type:"reaction",reaction:{message_id:t,emoji:s}};return this.send(JSON.stringify(n))}};var m=class extends p{endpoint="phone_numbers";constructor(t,s){super(t,s)}async getPhoneNumberById(t){let s=t?A({fields:t}):"";return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.client.sendRequest("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var N=class extends p{endpoint="message_qrdls";constructor(t,s){super(t,s)}async createQrCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getQrCodes(){return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(t){return this.client.sendRequest("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(t){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteQrCode(t){return this.client.sendRequest("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}};var _=class extends p{constructor(t,s){super(t,s)}async register(t,s){let i={messaging_product:"whatsapp",pin:t,...s&&{data_localization_region:s}};return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deregister(){return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var O=class extends p{endpoint="message_templates";constructor(t,s){super(t,s)}async getTemplate(t){return this.client.sendRequest("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(t,s){return this.client.sendRequest("POST",`${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(t){return this.client.sendRequest("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${A(t)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(t){return this.client.sendRequest("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteTemplate(t){return this.client.sendRequest("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${A(t)}`,this.config.REQUEST_TIMEOUT,null)}};var D=class extends p{constructor(t,s){super(t,s)}async setTwoStepVerificationCode(t){let s={pin:t};return this.client.sendRequest("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var B=class extends p{constructor(t,s){super(t,s)}async getAllWabaSubscriptions(){return this.client.sendRequest("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async subscribeToWaba(){return this.client.sendRequest("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async unsubscribeFromWaba(){return this.client.sendRequest("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async overrideWabaWebhook(t,s){let i={url:t,verify_token:s};return this.client.sendRequest("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/webhooks`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}};var Re=require("https");var Ne="HttpsClient",_e=!1,Oe=new P(Ne,process.env.DEBUG==="true"||_e),U=class{agent;constructor(){this.agent=new Re.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,n,h,M){let f=`https://${t}/${s}`,R=new AbortController,ce=setTimeout(()=>R.abort(),h);try{let F=await fetch(f,{method:i,headers:n,body:M,signal:R.signal});return Oe.log(`${i} : ${f} - ${JSON.stringify(F)}`),clearTimeout(ce),new x(F)}catch(F){throw F}}},x=class{res;respStatusCode;respHeaders;constructor(t){this.res=t,this.respStatusCode=t.status,this.respHeaders=Object.fromEntries(t.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(t){throw new Error("Failed to parse response body to JSON: "+t.message)}}};function v(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var De="REQUESTER",Be=!1,Me=new P(De,process.env.DEBUG==="true"||Be),G=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,n,h,M){this.client=new U,this.host=t||"graph.facebook.com",this.apiVersion=s||"22",this.phoneNumberId=i,this.accessToken=n,this.businessAcctId=h,this.userAgent=M}buildHeader(t){return{"Content-Type":t,Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent}}buildCAPIPath(t){return`v${this.apiVersion}.0/${t}`}async sendRequest(t,s,i,n){let h="application/json",M=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;Me.log(`${t} : ${M}`);try{let f=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(h),i,t==="POST"||t==="PUT"?n:void 0);if(!f.rawResponse().ok){let R=await f.json();throw v(R)?R:{name:"MetaError",message:"Unknown error occurred",error:{message:R.message||"Unknown error occurred",type:"UnknownError",code:f.statusCode(),fbtrace_id:""}}}return f}catch(f){throw v(f)?f:{name:"MetaError",message:f instanceof Error?f.message:"Network error occurred",error:{message:f instanceof Error?f.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}};var Ue="UTILS",Ge=!1,le=new P(Ue,process.env.DEBUG==="true"||Ge),we="graph.facebook.com",Fe=3e3,Le=30,We=2e4,Ke=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw le.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},fe=r=>{Ke(r);let t={WA_BASE_URL:process.env.WA_BASE_URL||we,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET:process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:r?.phoneNumberId||parseInt(process.env.WA_PHONE_NUMBER_ID||""),WA_BUSINESS_ACCOUNT_ID:r?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.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||"")||Fe,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||Le,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||We,DEBUG:process.env.DEBUG==="true"};return le.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};var He="WHATSAPP",xe=!1,w=new P(He,process.env.DEBUG==="true"||xe),ve="WA_SDK",L=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=H;constructor(t){this.config=fe(t),this.requester=new G(this.config.WA_BASE_URL,this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new q(this.config,this.requester),this.templates=new O(this.config,this.requester),this.phoneNumber=new m(this.config,this.requester),this.qrCode=new N(this.config,this.requester),this.encryption=new T(this.config,this.requester),this.twoStepVerification=new D(this.config,this.requester),this.registration=new _(this.config,this.requester),this.media=new b(this.config,this.requester),this.waba=new B(this.config,this.requester),this.flow=new d(this.config,this.requester),this.businessProfile=new S(this.config,this.requester),w.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${ve}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,w.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,w.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,w.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,w.log(`Updated business account id to ${t}`),!0}};
|
|
2
2
|
//# sourceMappingURL=whatsapp.js.map
|