meta-cloud-api 3.8.0 → 3.9.1

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.
@@ -0,0 +1,682 @@
1
+ //#region src/utils/buildFieldsQueryString.d.ts
2
+ declare function buildFieldsQueryString(fields?: string[] | string): string;
3
+ //#endregion
4
+ //#region src/utils/rateLimit.d.ts
5
+ /**
6
+ * Usage percentages reported by Meta. Each value is the share (0-100+) of the allowance used in the
7
+ * current rolling window.
8
+ */
9
+ interface RateLimitUsage {
10
+ /** Percentage of calls made (`call_count`). */
11
+ callCount?: number;
12
+ /** Percentage of total CPU time used (`total_cputime`). */
13
+ totalCputime?: number;
14
+ /** Percentage of total time used (`total_time`). */
15
+ totalTime?: number;
16
+ }
17
+ /** One entry of the `X-Business-Use-Case-Usage` header. */
18
+ interface BusinessUseCaseUsage extends RateLimitUsage {
19
+ /** The business object the entry belongs to (for WhatsApp, usually the WABA or phone number ID). */
20
+ businessId: string;
21
+ /** Rate limit type, e.g. `whatsapp_business_management` or `whatsapp`. */
22
+ type?: string;
23
+ /**
24
+ * `estimated_time_to_regain_access`: "Time, in minutes, until calls will no longer be throttled."
25
+ * `0` when not throttled.
26
+ */
27
+ estimatedTimeToRegainAccessMinutes?: number;
28
+ /** `ads_api_access_tier`, only sent for Marketing API use cases. */
29
+ adsApiAccessTier?: string;
30
+ }
31
+ /**
32
+ * Rate limit information parsed from a Graph API response.
33
+ *
34
+ * WhatsApp Cloud API responses carry `x-business-use-case-usage` (types
35
+ * `whatsapp_business_management` and `whatsapp`) and `x-app-usage`; throttled responses may add
36
+ * `Retry-After` (seconds).
37
+ */
38
+ interface RateLimitInfo {
39
+ /** Parsed `X-App-Usage` header (platform rate limits). */
40
+ appUsage?: RateLimitUsage;
41
+ /** Parsed `X-Business-Use-Case-Usage` header, flattened across business IDs. Empty when absent. */
42
+ businessUseCaseUsage: BusinessUseCaseUsage[];
43
+ /** Parsed `Retry-After` header in milliseconds (seconds or HTTP-date form). */
44
+ retryAfterMs?: number;
45
+ /**
46
+ * Highest usage percentage across every parsed metric, handy for alerting before Meta starts
47
+ * throttling (it throttles at 100).
48
+ */
49
+ maxUsagePercent?: number;
50
+ /**
51
+ * How long Meta asks you to wait, in milliseconds: the larger of `retryAfterMs` and the largest
52
+ * `estimatedTimeToRegainAccessMinutes`. Undefined when Meta gave no wait time.
53
+ */
54
+ retryDelayMs?: number;
55
+ }
56
+ /** Headers accepted by {@link parseRateLimitHeaders}. */
57
+ type RateLimitHeadersInput = Headers | Record<string, string | string[] | undefined> | {
58
+ get(name: string): string | null;
59
+ };
60
+ /**
61
+ * Parses a `Retry-After` value (delta-seconds or HTTP-date) into milliseconds.
62
+ * Returns undefined for missing or malformed values.
63
+ */
64
+ declare function parseRetryAfter(value: string | null | undefined, now?: number): number | undefined;
65
+ /**
66
+ * Parses Meta's rate limit headers (`X-App-Usage`, `X-Business-Use-Case-Usage`, `Retry-After`).
67
+ * Header names are matched case-insensitively. Malformed JSON or values are ignored, never thrown.
68
+ *
69
+ * Returns undefined when none of the headers are present.
70
+ *
71
+ * @see {@link https://developers.facebook.com/docs/graph-api/overview/rate-limiting/ | Graph API rate limiting}
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const info = parseRateLimitHeaders(response.headers);
76
+ * if ((info?.maxUsagePercent ?? 0) > 80) slowDown();
77
+ * ```
78
+ */
79
+ declare function parseRateLimitHeaders(headers: RateLimitHeadersInput | null | undefined): RateLimitInfo | undefined;
80
+ //#endregion
81
+ //#region src/types/enums.d.ts
82
+ declare enum WabaConfigEnum {
83
+ AppId = "M4D_APP_ID",
84
+ Port = "WA_PORT",
85
+ AppSecret = "M4D_APP_SECRET",
86
+ PhoneNumberId = "WA_PHONE_NUMBER_ID",
87
+ BusinessAcctId = "WA_BUSINESS_ACCOUNT_ID",
88
+ APIVersion = "CLOUD_API_VERSION",
89
+ AccessToken = "CLOUD_API_ACCESS_TOKEN",
90
+ WebhookEndpoint = "WEBHOOK_ENDPOINT",
91
+ WebhookVerificationToken = "WEBHOOK_VERIFICATION_TOKEN",
92
+ ListenerPort = "LISTENER_PORT",
93
+ MaxRetriesAfterWait = "MAX_RETRIES_AFTER_WAIT",
94
+ RequestTimeout = "REQUEST_TIMEOUT",
95
+ Debug = "DEBUG",
96
+ PrivatePem = "FLOW_API_PRIVATE_PEM",
97
+ Passphrase = "FLOW_API_PASSPHRASE"
98
+ }
99
+ //#endregion
100
+ //#region src/types/config.d.ts
101
+ /**
102
+ * Configuration for automatic retry behavior on throttling errors.
103
+ *
104
+ * When the WhatsApp API returns a rate limit error (WhatsAppThrottlingError),
105
+ * the SDK will automatically retry the request using exponential backoff.
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * const wa = new WhatsApp({
110
+ * accessToken: '...',
111
+ * phoneNumberId: 123,
112
+ * retry: { maxAttempts: 3, backoff: 'exponential', initialDelayMs: 1000 },
113
+ * });
114
+ * ```
115
+ */
116
+ interface RetryConfig {
117
+ /**
118
+ * Maximum number of attempts (including the initial attempt).
119
+ * Defaults to 3.
120
+ */
121
+ maxAttempts?: number;
122
+ /**
123
+ * Backoff strategy.
124
+ * - 'exponential': delay doubles each attempt (1s → 2s → 4s)
125
+ * - 'fixed': constant delay between attempts
126
+ * Defaults to 'exponential'.
127
+ */
128
+ backoff?: 'exponential' | 'fixed';
129
+ /**
130
+ * Initial delay in milliseconds before the first retry.
131
+ * Defaults to 1000 (1 second).
132
+ */
133
+ initialDelayMs?: number;
134
+ /**
135
+ * Wait as long as Meta asks before retrying a throttled request. When a throttling response
136
+ * carries `Retry-After` (seconds) or `X-Business-Use-Case-Usage` with
137
+ * `estimated_time_to_regain_access` (minutes), the retry waits the larger of the backoff delay and
138
+ * that server delay, capped at {@link RetryConfig.maxServerDelayMs}. It never adds attempts.
139
+ * Defaults to `true`; set `false` to use the backoff delay only.
140
+ */
141
+ respectServerDelay?: boolean;
142
+ /**
143
+ * Upper bound in milliseconds for a server-provided wait. A longer wait is shortened to this
144
+ * value, so the retry may still be throttled; inspect `error.rateLimit` to reschedule instead.
145
+ * Defaults to 30000 (30 seconds).
146
+ */
147
+ maxServerDelayMs?: number;
148
+ }
149
+ /** Request details passed to {@link WhatsAppConfig.onRateLimitInfo}. */
150
+ interface RateLimitInfoContext {
151
+ /** HTTP method of the request. */
152
+ method: string;
153
+ /** Endpoint path or absolute URL as passed to the requester. */
154
+ endpoint: string;
155
+ /** HTTP status code of the response. */
156
+ statusCode: number;
157
+ }
158
+ /** Callback receiving rate limit information parsed from every response that carries it. */
159
+ type RateLimitInfoListener = (info: RateLimitInfo, context: RateLimitInfoContext) => void | Promise<void>;
160
+ type WabaConfigType = {
161
+ /**
162
+ * The Meta for Developers business application Id for this registered application.
163
+ */
164
+ [WabaConfigEnum.AppId]: string;
165
+ /**
166
+ * The Meta for Developers business application secret for this registered application.
167
+ */
168
+ [WabaConfigEnum.AppSecret]: string;
169
+ /**
170
+ * The Meta for Developers phone number id used by the registered business.
171
+ */
172
+ [WabaConfigEnum.PhoneNumberId]: number;
173
+ /**
174
+ * The Meta for Developers business id for the registered business.
175
+ */
176
+ [WabaConfigEnum.BusinessAcctId]: string;
177
+ /**
178
+ * The version of the Cloud API being used. Starts with a "v" and follows the major number.
179
+ */
180
+ [WabaConfigEnum.APIVersion]: string;
181
+ /**
182
+ * The access token to make calls on behalf of the signed in Meta for Developers account or business.
183
+ */
184
+ [WabaConfigEnum.AccessToken]: string;
185
+ /**
186
+ * The endpoint path (e.g. if the value here is webhook, the webhook URL would look like http/https://{host}/webhook).
187
+ */
188
+ [WabaConfigEnum.WebhookEndpoint]: string;
189
+ /**
190
+ * The verification token that needs to match what is sent by the Cloud API webhook in order to subscribe.
191
+ */
192
+ [WabaConfigEnum.WebhookVerificationToken]: string;
193
+ /**
194
+ * The listener port for the webhook web server.
195
+ */
196
+ [WabaConfigEnum.ListenerPort]: number;
197
+ /**
198
+ * To turn on global debugging of the logger to print verbose output across the APIs.
199
+ */
200
+ [WabaConfigEnum.Debug]: boolean;
201
+ /**
202
+ * The total number of times a request should be retried after the wait period if it fails.
203
+ */
204
+ [WabaConfigEnum.MaxRetriesAfterWait]: number;
205
+ /**
206
+ * The timeout period for a request to quit and destroy the attempt in ms.
207
+ */
208
+ [WabaConfigEnum.RequestTimeout]: number;
209
+ /**
210
+ * The private key for the Meta for Developers business.
211
+ */
212
+ [WabaConfigEnum.PrivatePem]: string;
213
+ /**
214
+ * The passphrase for the Meta for Developers business.
215
+ */
216
+ [WabaConfigEnum.Passphrase]: string;
217
+ /**
218
+ * Automatic retry configuration for throttling errors.
219
+ * Passed through from WhatsAppConfig.
220
+ */
221
+ retry?: RetryConfig;
222
+ /**
223
+ * Rate limit header listener. Passed through from WhatsAppConfig.
224
+ */
225
+ onRateLimitInfo?: RateLimitInfoListener;
226
+ };
227
+ //#endregion
228
+ //#region src/utils/configTable.d.ts
229
+ /**
230
+ * Formats configuration as a terminal table
231
+ * @param config - The WABA configuration object
232
+ * @param apiName - The name of the API being initialized
233
+ * @returns Formatted table string
234
+ */
235
+ declare function formatConfigTable(config: WabaConfigType): string;
236
+ //#endregion
237
+ //#region src/utils/customerServiceWindow.d.ts
238
+ /**
239
+ * Length of the customer service window: 24 hours.
240
+ *
241
+ * "When a WhatsApp user messages you or calls you, a 24-hour timer called a customer service window
242
+ * starts. If the user messages or calls you again before the timer expires, the timer resets to
243
+ * 24 hours. [...] When the window closes, you can only send pre-approved template messages."
244
+ *
245
+ * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/ | Send messages: customer service windows}
246
+ */
247
+ declare const CUSTOMER_SERVICE_WINDOW_MS: number;
248
+ /**
249
+ * SDK fallback length of a free entry point (FEP) window: 72 hours.
250
+ * Prefer the expiry supplied by Meta; this fallback does not establish billing eligibility.
251
+ *
252
+ * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}
253
+ */
254
+ declare const FREE_ENTRY_POINT_WINDOW_MS: number;
255
+ /**
256
+ * Longest free entry point window Meta documents: up to 7 days for conversations started from an
257
+ * ad that clicks to WhatsApp.
258
+ *
259
+ * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}
260
+ */
261
+ declare const MAX_FREE_ENTRY_POINT_WINDOW_MS: number;
262
+ /**
263
+ * A point in time accepted by the window helpers:
264
+ * - `Date`
265
+ * - `number`: Unix epoch in milliseconds, or in seconds when below `1e11` (before the year 5138 in
266
+ * seconds, before March 1973 in milliseconds), so both `Date.now()` and webhook timestamps work
267
+ * - `string`: a numeric string such as the webhook `messages[].timestamp` (`"1727856000"`, Unix
268
+ * seconds, same rule as numbers), or any string `Date.parse` understands (ISO 8601)
269
+ */
270
+ type WindowTimestamp = Date | number | string;
271
+ /** State of a messaging window at a given instant. */
272
+ interface MessagingWindow {
273
+ /** True while the window is open (`now < expiresAt`). */
274
+ isOpen: boolean;
275
+ /** When the window closes, or `null` when there is no window (no inbound message yet). */
276
+ expiresAt: Date | null;
277
+ /** Milliseconds until the window closes, `0` once closed. Never more than the window length. */
278
+ remainingMs: number;
279
+ }
280
+ interface CustomerServiceWindowOptions {
281
+ /** The instant to evaluate. Defaults to `Date.now()`. */
282
+ now?: WindowTimestamp;
283
+ /**
284
+ * Treat the window as closing this many milliseconds early. Use it to absorb clock drift between
285
+ * your servers and Meta and the time a send spends in flight. Defaults to `0`.
286
+ */
287
+ safetyMarginMs?: number;
288
+ }
289
+ interface FreeEntryPointWindowOptions extends CustomerServiceWindowOptions {
290
+ /**
291
+ * Window length. Defaults to {@link FREE_ENTRY_POINT_WINDOW_MS} (72 hours). Meta may keep a
292
+ * click-to-WhatsApp ad window open for up to {@link MAX_FREE_ENTRY_POINT_WINDOW_MS} (7 days)
293
+ * without saying how long a given window lasts, so prefer `expiresAt` when you have it.
294
+ */
295
+ durationMs?: number;
296
+ /**
297
+ * Exact expiry when known, for example the status webhook's `conversation.expiration_timestamp`
298
+ * (Unix seconds). Overrides `durationMs`.
299
+ */
300
+ expiresAt?: WindowTimestamp;
301
+ }
302
+ /**
303
+ * Returns the state of the 24-hour customer service window opened by the user's last inbound
304
+ * message (or call).
305
+ *
306
+ * Free-form (non-template) messages can only be sent while it is open; outside it only approved
307
+ * template messages are delivered (Meta rejects others with error `131047`). The window is exactly
308
+ * 24 hours from the user's last message: at `lastInboundAt + 24h` it is closed.
309
+ *
310
+ * Pass the webhook message `timestamp` (Unix seconds string) of the latest message from the user.
311
+ * Messages you send do not extend the window. Pass `null`/`undefined` when the user has never
312
+ * messaged you; that returns a closed window with `expiresAt: null`.
313
+ *
314
+ * A free entry point window does not reopen this window: "the customer service window is independent
315
+ * of the FEP window, so if the customer service window closes, you will only be able to send template
316
+ * messages." Use {@link getFreeEntryPointWindow} for the pricing side.
317
+ *
318
+ * @throws WhatsAppValidationError when a timestamp or `safetyMarginMs` is malformed.
319
+ *
320
+ * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/ | Send messages: customer service windows}
321
+ * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing}
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * const { isOpen, expiresAt } = getCustomerServiceWindow(message.timestamp);
326
+ * if (!isOpen) await sendTemplateInstead();
327
+ * ```
328
+ */
329
+ declare function getCustomerServiceWindow(lastInboundAt: WindowTimestamp | null | undefined, options?: CustomerServiceWindowOptions): MessagingWindow;
330
+ /**
331
+ * True when a free-form (non-template) message can be sent: the customer service window opened by
332
+ * the user's last inbound message is still open. See {@link getCustomerServiceWindow}.
333
+ *
334
+ * @throws WhatsAppValidationError when a timestamp or `safetyMarginMs` is malformed.
335
+ */
336
+ declare function canSendFreeformMessage(lastInboundAt: WindowTimestamp | null | undefined, options?: CustomerServiceWindowOptions): boolean;
337
+ /**
338
+ * Returns the state of a free entry point (FEP) window.
339
+ *
340
+ * For eligible click-to-WhatsApp ad traffic, replying within the customer service window opens
341
+ * a billing window from the time of your reply. Pass that first reply time as `openedAt`.
342
+ *
343
+ * Meta documents windows lasting up to 7 days for ads that click to WhatsApp. This helper uses
344
+ * a 72-hour fallback estimate. Pass `expiresAt` (the status webhook's
345
+ * `conversation.expiration_timestamp`) when you have it, or set `durationMs`.
346
+ *
347
+ * This is a billing window only. It does not allow free-form messages after the customer service
348
+ * window closes; check {@link canSendFreeformMessage} for that.
349
+ *
350
+ * @throws WhatsAppValidationError when a timestamp, `durationMs` or `safetyMarginMs` is malformed.
351
+ *
352
+ * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}
353
+ */
354
+ declare function getFreeEntryPointWindow(openedAt: WindowTimestamp | null | undefined, options?: FreeEntryPointWindowOptions): MessagingWindow;
355
+ //#endregion
356
+ //#region src/utils/isMetaError.d.ts
357
+ type MetaErrorData = {
358
+ message: string;
359
+ type: string;
360
+ code: number;
361
+ error_data?: {
362
+ messaging_product?: 'whatsapp';
363
+ details?: string;
364
+ };
365
+ error_subcode?: number;
366
+ fbtrace_id: string;
367
+ };
368
+ interface MetaError extends Error {
369
+ error: MetaErrorData;
370
+ }
371
+ declare const WHATSAPP_ERROR_CODES: readonly [0, 1, 2, 3, 4, 10, 33, 100, 190, 200, 299, 368, 613, 80007, 130429, 130472, 130497, 131000, 131005, 131008, 131009, 131016, 131020, 131021, 131026, 131030, 131031, 131037, 131041, 131042, 131044, 131045, 131047, 131048, 131049, 131050, 131051, 131052, 131053, 131055, 131056, 131057, 131059, 131061, 131062, 131063, 131201, 131202, 131203, 131204, 131207, 131208, 131209, 131210, 131211, 131212, 131213, 131214, 131215, 132000, 132001, 132005, 132007, 132008, 132012, 132015, 132016, 132068, 132069, 133000, 133004, 133005, 133006, 133008, 133009, 133010, 133015, 133016, 134011, 134100, 134101, 134102, 135000, 137000, 138000, 138001, 138002, 138003, 138004, 138005, 138006, 138007, 138009, 138012, 138013, 138018, 139000, 139001, 139002, 139003, 139004, 139100, 139101, 139102, 139103, 147005, 200005, 200006, 200007, 1752041, 2388001, 2388012, 2388019, 2388040, 2388047, 2388072, 2388073, 2388091, 2388093, 2388103, 2388293, 2388299, 2494100, 2494191, 2593079, 2593085, 2593107, 2593108];
372
+ type ApiPermissionErrorCode = number;
373
+ type WhatsAppErrorCode = (typeof WHATSAPP_ERROR_CODES)[number] | ApiPermissionErrorCode;
374
+ declare const AUTHORIZATION_ERROR_CODES: readonly [0, 3, 10, 190];
375
+ declare const THROTTLING_ERROR_CODES: readonly [4, 80007, 130429, 131048, 131056];
376
+ declare const INTEGRITY_ERROR_CODES: readonly [368, 130497, 131031];
377
+ declare const SEND_MESSAGE_ERROR_CODES: readonly [130472, 131000, 131005, 131008, 131009, 131016, 131021, 131026, 131030, 131042, 131044, 131045, 131047, 131050, 131051, 131052, 131053, 131056, 131057, 131048, 131061, 131062, 131063, 132000, 132001, 132005, 132007, 132008, 132012, 132015, 132016, 132068, 132069, 135000, 137000];
378
+ declare const FLOW_ERROR_CODES: readonly [139000, 139001, 139002, 139003, 139004];
379
+ declare const BLOCK_USER_ERROR_CODES: readonly [139100, 139101, 139102, 139103];
380
+ declare const CALLING_ERROR_CODES: readonly [138000, 138001, 138002, 138003, 138004, 138005, 138006, 138007, 138009, 138012, 138013, 138018, 613];
381
+ declare const GROUP_ERROR_CODES: readonly [131020, 131041, 131059, 131201, 131202, 131203, 131204, 131207, 131208, 131209, 131210, 131211, 131212, 131213, 131214, 131215];
382
+ declare function isWhatsAppErrorCode(code: number): code is WhatsAppErrorCode;
383
+ declare function isApiPermissionErrorCode(code: number): code is ApiPermissionErrorCode;
384
+ declare function isAuthorizationErrorCode(code: number): code is ApiPermissionErrorCode | (typeof AUTHORIZATION_ERROR_CODES)[number];
385
+ declare function isThrottlingErrorCode(code: number): code is (typeof THROTTLING_ERROR_CODES)[number];
386
+ declare function isIntegrityErrorCode(code: number): code is (typeof INTEGRITY_ERROR_CODES)[number];
387
+ declare function isSendMessageErrorCode(code: number): code is (typeof SEND_MESSAGE_ERROR_CODES)[number];
388
+ declare function isFlowErrorCode(code: number): code is (typeof FLOW_ERROR_CODES)[number];
389
+ declare function isBlockUserErrorCode(code: number): code is (typeof BLOCK_USER_ERROR_CODES)[number];
390
+ declare function isCallingErrorCode(code: number): code is (typeof CALLING_ERROR_CODES)[number];
391
+ declare function isGroupErrorCode(code: number): code is (typeof GROUP_ERROR_CODES)[number];
392
+ declare class WhatsAppError extends Error {
393
+ constructor(message: string);
394
+ }
395
+ declare class WhatsAppApiError extends WhatsAppError {
396
+ readonly error: MetaErrorData;
397
+ readonly statusCode?: number;
398
+ /**
399
+ * Rate limit headers of the failed response, when it carried any. Set by the SDK's requester;
400
+ * use `rateLimit.retryDelayMs` to reschedule a throttled call.
401
+ */
402
+ rateLimit?: RateLimitInfo;
403
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
404
+ }
405
+ declare class WhatsAppAuthorizationError extends WhatsAppApiError {
406
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
407
+ }
408
+ declare class WhatsAppThrottlingError extends WhatsAppApiError {
409
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
410
+ }
411
+ declare class WhatsAppIntegrityError extends WhatsAppApiError {
412
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
413
+ }
414
+ declare class WhatsAppSendMessageError extends WhatsAppApiError {
415
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
416
+ }
417
+ declare class WhatsAppFlowError extends WhatsAppApiError {
418
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
419
+ }
420
+ declare class WhatsAppBlockUserError extends WhatsAppApiError {
421
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
422
+ }
423
+ declare class WhatsAppCallingError extends WhatsAppApiError {
424
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
425
+ }
426
+ declare class WhatsAppGroupError extends WhatsAppApiError {
427
+ constructor(message: string, error: MetaErrorData, statusCode?: number);
428
+ }
429
+ declare function createWhatsAppApiError(error: MetaErrorData, statusCode?: number): WhatsAppApiError;
430
+ declare class WhatsAppNetworkError extends WhatsAppError {
431
+ readonly cause?: unknown;
432
+ constructor(message: string, cause?: unknown);
433
+ }
434
+ declare class WhatsAppUnknownError extends WhatsAppError {
435
+ readonly cause?: unknown;
436
+ constructor(message: string, cause?: unknown);
437
+ }
438
+ /**
439
+ * Thrown when an API method receives invalid input (e.g., malformed phone number,
440
+ * empty required array). This error is thrown client-side before any API call is made.
441
+ */
442
+ declare class WhatsAppValidationError extends Error {
443
+ constructor(message: string);
444
+ }
445
+ /**
446
+ * Determines if the error is a Meta API error response
447
+ * @param error Any error object to check
448
+ * @returns Type guard indicating if error is a Meta API error
449
+ */
450
+ declare function isMetaError(error: any): error is MetaError;
451
+ declare function isWhatsAppApiErrorResponse(error: any): error is MetaError & {
452
+ error: {
453
+ code: WhatsAppErrorCode;
454
+ };
455
+ };
456
+ declare function isWhatsAppAuthorizationError(error: unknown): error is WhatsAppAuthorizationError;
457
+ declare function isWhatsAppThrottlingError(error: unknown): error is WhatsAppThrottlingError;
458
+ declare function isWhatsAppIntegrityError(error: unknown): error is WhatsAppIntegrityError;
459
+ declare function isWhatsAppSendMessageError(error: unknown): error is WhatsAppSendMessageError;
460
+ declare function isWhatsAppFlowError(error: unknown): error is WhatsAppFlowError;
461
+ declare function isWhatsAppBlockUserError(error: unknown): error is WhatsAppBlockUserError;
462
+ declare function isWhatsAppCallingError(error: unknown): error is WhatsAppCallingError;
463
+ declare function isWhatsAppGroupError(error: unknown): error is WhatsAppGroupError;
464
+ declare function normalizeMetaError(errorData: unknown, statusCode?: number): MetaError;
465
+ //#endregion
466
+ //#region src/types/logger.d.ts
467
+ interface LoggerInterface {
468
+ log(...data: any[]): void;
469
+ error(...data: any[]): void;
470
+ warn(...data: any[]): void;
471
+ info(...data: any[]): void;
472
+ debug(...data: any[]): void;
473
+ }
474
+ //#endregion
475
+ //#region src/utils/logger.d.ts
476
+ declare class Logger implements LoggerInterface {
477
+ private name;
478
+ private debugEnabled;
479
+ constructor(name: string, debug?: boolean);
480
+ private formatData;
481
+ log(...data: any[]): void;
482
+ error(...data: any[]): void;
483
+ warn(...data: any[]): void;
484
+ info(...data: any[]): void;
485
+ debug(...data: any[]): void;
486
+ }
487
+ //#endregion
488
+ //#region src/utils/objectToQueryString.d.ts
489
+ declare const objectToQueryString: (params: Record<string, any>) => string;
490
+ //#endregion
491
+ //#region src/api/flow/types/common.d.ts
492
+ declare enum FlowActionEnum {
493
+ INIT = "INIT",
494
+ BACK = "BACK",
495
+ DATA_EXCHANGE = "data_exchange"
496
+ }
497
+ /**
498
+ * WhatsApp Flow Endpoint - Health Check Request
499
+ * Represents the structure of a health check request
500
+ */
501
+ interface FlowHealthCheckRequest {
502
+ action: 'ping';
503
+ version: '3.0';
504
+ }
505
+ /**
506
+ * WhatsApp Flow Endpoint - Data Exchange Request
507
+ * Represents the structure of a data exchange request
508
+ */
509
+ interface FlowDataExchangeRequest {
510
+ version: '3.0';
511
+ action: FlowActionEnum;
512
+ screen: string;
513
+ flow_token: string;
514
+ data?: Record<string, any> & {
515
+ error_message?: string;
516
+ };
517
+ }
518
+ /**
519
+ * WhatsApp Flow Endpoint - Error Notification Request
520
+ * Represents the structure of an error notification request
521
+ */
522
+ interface FlowErrorNotificationRequest {
523
+ version: '3.0';
524
+ action: Exclude<FlowActionEnum, FlowActionEnum.BACK>;
525
+ screen: string;
526
+ flow_token: string;
527
+ data: {
528
+ error: string;
529
+ error_message: string;
530
+ };
531
+ }
532
+ /**
533
+ * WhatsApp Flow Endpoint - Comprehensive Request Object
534
+ * A combined type that includes all possible fields from different request types
535
+ * with all fields being optional for flexibility
536
+ */
537
+ interface FlowEndpointRequest {
538
+ version?: '3.0';
539
+ action?: 'ping' | FlowActionEnum;
540
+ screen?: string;
541
+ flow_token?: string;
542
+ data?: Record<string, any> & {
543
+ error_key?: string;
544
+ error_message?: string;
545
+ };
546
+ }
547
+ //#endregion
548
+ //#region src/utils/flowEncryptionUtils.d.ts
549
+ /**
550
+ * Environment model for encryption keys
551
+ */
552
+ type EncryptionKeyPair = {
553
+ passphrase: string;
554
+ privateKey: string;
555
+ publicKey: string;
556
+ };
557
+ /**
558
+ * Generates RSA key pair for WhatsApp Business Flow API encryption
559
+ *
560
+ * This function generates a 2048-bit RSA key pair with:
561
+ * - Public key in SPKI format (PEM)
562
+ * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC
563
+ *
564
+ * @param passphrase - Passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from environment
565
+ * @returns Object containing passphrase, privateKey, and publicKey
566
+ * @throws {Error} If passphrase is empty or key generation fails
567
+ * @throws {Error} If not running in Node.js environment
568
+ *
569
+ * @example
570
+ * ```typescript
571
+ * import { WhatsApp } from 'meta-cloud-api';
572
+ *
573
+ * const wa = new WhatsApp();
574
+ *
575
+ * try {
576
+ * // Uses FLOW_API_PASSPHRASE from environment
577
+ * const keys = wa.generateEncryption();
578
+ * console.log('Public Key:', keys.publicKey);
579
+ * console.log('Private Key:', keys.privateKey);
580
+ *
581
+ * // Or provide custom passphrase
582
+ * const customKeys = wa.generateEncryption('my-secret-passphrase');
583
+ * } catch (error) {
584
+ * console.error('Failed to generate keys:', error.message);
585
+ * }
586
+ * ```
587
+ */
588
+ declare function generateEncryption(passphrase?: string): EncryptionKeyPair;
589
+ /**
590
+ * Decrypt a WhatsApp Flow request (Node.js only; see {@link decryptFlowRequestAsync} for every runtime)
591
+ * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector
592
+ * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and FLOW_API_PASSPHRASE
593
+ * @returns Decrypted flow request body, AES key buffer, and initial vector buffer
594
+ * @throws {Error} If required encryption properties are missing or decryption fails
595
+ */
596
+ declare function decryptFlowRequest(body: any, config: WabaConfigType): {
597
+ decryptedBody: FlowEndpointRequest;
598
+ aesKeyBuffer: Buffer;
599
+ initialVectorBuffer: Buffer;
600
+ };
601
+ /**
602
+ * Encrypt a WhatsApp Flow response (Node.js only; see {@link encryptFlowResponseAsync} for every runtime)
603
+ * @param response - Response object to encrypt
604
+ * @param aesKeyBuffer - AES key buffer from the decrypted request
605
+ * @param initialVectorBuffer - Initial vector buffer from the decrypted request
606
+ * @returns Base64-encoded encrypted response
607
+ * @throws {Error} If encryption fails
608
+ */
609
+ declare function encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string;
610
+ /**
611
+ * Result of {@link decryptFlowRequestAsync}. Pass `aesKeyBuffer` and
612
+ * `initialVectorBuffer` to {@link encryptFlowResponseAsync}.
613
+ */
614
+ type DecryptedFlowRequest = {
615
+ decryptedBody: FlowEndpointRequest;
616
+ aesKeyBuffer: Uint8Array<ArrayBuffer>;
617
+ initialVectorBuffer: Uint8Array<ArrayBuffer>;
618
+ };
619
+ /**
620
+ * Decrypt a WhatsApp Flow request with Web Crypto. Works on Node.js, Bun, Deno,
621
+ * Cloudflare Workers and Vercel Edge.
622
+ *
623
+ * On runtimes without `node:crypto` the private key must be an unencrypted
624
+ * PKCS#8 PEM (`-----BEGIN PRIVATE KEY-----`); the passphrase is then ignored.
625
+ *
626
+ * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector
627
+ * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and (for encrypted keys) FLOW_API_PASSPHRASE
628
+ * @throws {Error} If required encryption properties are missing or decryption fails
629
+ */
630
+ declare function decryptFlowRequestAsync(body: any, config: WabaConfigType): Promise<DecryptedFlowRequest>;
631
+ /**
632
+ * Encrypt a WhatsApp Flow response with Web Crypto. Works on every runtime.
633
+ * @param response - Response object to encrypt
634
+ * @param aesKeyBuffer - AES key from {@link decryptFlowRequestAsync} (a Node.js Buffer also works)
635
+ * @param initialVectorBuffer - Initial vector from {@link decryptFlowRequestAsync} (a Node.js Buffer also works)
636
+ * @returns Base64-encoded encrypted response
637
+ */
638
+ declare function encryptFlowResponseAsync(response: any, aesKeyBuffer: Uint8Array, initialVectorBuffer: Uint8Array): Promise<string>;
639
+ //#endregion
640
+ //#region src/utils/flowTypeGuards.d.ts
641
+ declare const DATA_EXCHANGE_ACTIONS: readonly [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK];
642
+ declare const ERROR_ACTIONS: readonly [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT];
643
+ /**
644
+ * Type guard to check if a request is a Data Exchange request
645
+ * Validates the request structure according to the Flow API specifications
646
+ *
647
+ * @param request The Flow endpoint request to check
648
+ * @returns True if the request is a valid Data Exchange request, false otherwise
649
+ */
650
+ declare function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {
651
+ action: (typeof DATA_EXCHANGE_ACTIONS)[number];
652
+ screen?: string;
653
+ flow_token: string;
654
+ data?: Record<string, any>;
655
+ };
656
+ /**
657
+ * Type guard to check if a request is an Error Notification request
658
+ * Validates the request structure according to the Flow API error specifications
659
+ *
660
+ * @param request The Flow endpoint request to check
661
+ * @returns True if the request is a valid Error Notification request, false otherwise
662
+ */
663
+ declare function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {
664
+ action: (typeof ERROR_ACTIONS)[number];
665
+ screen: string;
666
+ flow_token: string;
667
+ data: {
668
+ error: string;
669
+ error_message: string;
670
+ };
671
+ };
672
+ /**
673
+ * Type guard to check if a request is a Ping (health check) request
674
+ * Simple validation for health check endpoints in the Flow API
675
+ *
676
+ * @param request The Flow endpoint request to check
677
+ * @returns True if the request is a Ping request, false otherwise
678
+ */
679
+ declare function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest;
680
+ //#endregion
681
+ export { AUTHORIZATION_ERROR_CODES, type ApiPermissionErrorCode, BLOCK_USER_ERROR_CODES, type BusinessUseCaseUsage, CALLING_ERROR_CODES, CUSTOMER_SERVICE_WINDOW_MS, type CustomerServiceWindowOptions, type DecryptedFlowRequest, type EncryptionKeyPair, FLOW_ERROR_CODES, FREE_ENTRY_POINT_WINDOW_MS, type FreeEntryPointWindowOptions, GROUP_ERROR_CODES, INTEGRITY_ERROR_CODES, Logger, MAX_FREE_ENTRY_POINT_WINDOW_MS, type MessagingWindow, type MetaError, type MetaErrorData, type RateLimitHeadersInput, type RateLimitInfo, type RateLimitUsage, SEND_MESSAGE_ERROR_CODES, THROTTLING_ERROR_CODES, WHATSAPP_ERROR_CODES, WhatsAppApiError, WhatsAppAuthorizationError, WhatsAppBlockUserError, WhatsAppCallingError, WhatsAppError, type WhatsAppErrorCode, WhatsAppFlowError, WhatsAppGroupError, WhatsAppIntegrityError, WhatsAppNetworkError, WhatsAppSendMessageError, WhatsAppThrottlingError, WhatsAppUnknownError, WhatsAppValidationError, type WindowTimestamp, buildFieldsQueryString, canSendFreeformMessage, createWhatsAppApiError, decryptFlowRequest, decryptFlowRequestAsync, encryptFlowResponse, encryptFlowResponseAsync, formatConfigTable, generateEncryption, getCustomerServiceWindow, getFreeEntryPointWindow, isApiPermissionErrorCode, isAuthorizationErrorCode, isBlockUserErrorCode, isCallingErrorCode, isFlowDataExchangeRequest, isFlowErrorCode, isFlowErrorRequest, isFlowPingRequest, isGroupErrorCode, isIntegrityErrorCode, isMetaError, isSendMessageErrorCode, isThrottlingErrorCode, isWhatsAppApiErrorResponse, isWhatsAppAuthorizationError, isWhatsAppBlockUserError, isWhatsAppCallingError, isWhatsAppErrorCode, isWhatsAppFlowError, isWhatsAppGroupError, isWhatsAppIntegrityError, isWhatsAppSendMessageError, isWhatsAppThrottlingError, normalizeMetaError, objectToQueryString, parseRateLimitHeaders, parseRetryAfter };
682
+ //# sourceMappingURL=index.d.ts.map