meta-cloud-api 3.7.1 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -4
- package/dist/index.d.mts +777 -224
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -5
- package/dist/index.mjs.map +1 -1
- package/dist/node/chunk.mjs +1 -0
- package/dist/node/index.d.mts +10393 -0
- package/dist/node/index.d.mts.map +1 -0
- package/dist/node/index.mjs +23 -0
- package/dist/node/index.mjs.map +1 -0
- package/dist/testing/index.d.ts +377 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +4 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/node/index.js +3 -0
- package/dist/types/index.d.ts +283 -7
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/index.d.ts +264 -4
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +6 -4
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/node/index.d.ts +682 -0
- package/dist/utils/node/index.d.ts.map +1 -0
- package/dist/utils/node/index.js +16 -0
- package/dist/utils/node/index.js.map +1 -0
- package/package.json +31 -6
package/dist/utils/index.d.ts
CHANGED
|
@@ -1,6 +1,83 @@
|
|
|
1
1
|
//#region src/utils/buildFieldsQueryString.d.ts
|
|
2
2
|
declare function buildFieldsQueryString(fields?: string[] | string): string;
|
|
3
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
|
|
4
81
|
//#region src/types/enums.d.ts
|
|
5
82
|
declare enum WabaConfigEnum {
|
|
6
83
|
AppId = "M4D_APP_ID",
|
|
@@ -54,7 +131,32 @@ interface RetryConfig {
|
|
|
54
131
|
* Defaults to 1000 (1 second).
|
|
55
132
|
*/
|
|
56
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;
|
|
57
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>;
|
|
58
160
|
type WabaConfigType = {
|
|
59
161
|
/**
|
|
60
162
|
* The Meta for Developers business application Id for this registered application.
|
|
@@ -117,6 +219,10 @@ type WabaConfigType = {
|
|
|
117
219
|
* Passed through from WhatsAppConfig.
|
|
118
220
|
*/
|
|
119
221
|
retry?: RetryConfig;
|
|
222
|
+
/**
|
|
223
|
+
* Rate limit header listener. Passed through from WhatsAppConfig.
|
|
224
|
+
*/
|
|
225
|
+
onRateLimitInfo?: RateLimitInfoListener;
|
|
120
226
|
};
|
|
121
227
|
//#endregion
|
|
122
228
|
//#region src/utils/configTable.d.ts
|
|
@@ -128,6 +234,125 @@ type WabaConfigType = {
|
|
|
128
234
|
*/
|
|
129
235
|
declare function formatConfigTable(config: WabaConfigType): string;
|
|
130
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
|
|
131
356
|
//#region src/utils/isMetaError.d.ts
|
|
132
357
|
type MetaErrorData = {
|
|
133
358
|
message: string;
|
|
@@ -170,6 +395,11 @@ declare class WhatsAppError extends Error {
|
|
|
170
395
|
declare class WhatsAppApiError extends WhatsAppError {
|
|
171
396
|
readonly error: MetaErrorData;
|
|
172
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;
|
|
173
403
|
constructor(message: string, error: MetaErrorData, statusCode?: number);
|
|
174
404
|
}
|
|
175
405
|
declare class WhatsAppAuthorizationError extends WhatsAppApiError {
|
|
@@ -245,13 +475,14 @@ interface LoggerInterface {
|
|
|
245
475
|
//#region src/utils/logger.d.ts
|
|
246
476
|
declare class Logger implements LoggerInterface {
|
|
247
477
|
private name;
|
|
248
|
-
private
|
|
478
|
+
private debugEnabled;
|
|
249
479
|
constructor(name: string, debug?: boolean);
|
|
250
480
|
private formatData;
|
|
251
481
|
log(...data: any[]): void;
|
|
252
482
|
error(...data: any[]): void;
|
|
253
483
|
warn(...data: any[]): void;
|
|
254
484
|
info(...data: any[]): void;
|
|
485
|
+
debug(...data: any[]): void;
|
|
255
486
|
}
|
|
256
487
|
//#endregion
|
|
257
488
|
//#region src/utils/objectToQueryString.d.ts
|
|
@@ -356,7 +587,7 @@ type EncryptionKeyPair = {
|
|
|
356
587
|
*/
|
|
357
588
|
declare function generateEncryption(passphrase?: string): EncryptionKeyPair;
|
|
358
589
|
/**
|
|
359
|
-
* Decrypt a WhatsApp Flow request
|
|
590
|
+
* Decrypt a WhatsApp Flow request (Node.js only; see {@link decryptFlowRequestAsync} for every runtime)
|
|
360
591
|
* @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector
|
|
361
592
|
* @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and FLOW_API_PASSPHRASE
|
|
362
593
|
* @returns Decrypted flow request body, AES key buffer, and initial vector buffer
|
|
@@ -368,7 +599,7 @@ declare function decryptFlowRequest(body: any, config: WabaConfigType): {
|
|
|
368
599
|
initialVectorBuffer: Buffer;
|
|
369
600
|
};
|
|
370
601
|
/**
|
|
371
|
-
* Encrypt a WhatsApp Flow response
|
|
602
|
+
* Encrypt a WhatsApp Flow response (Node.js only; see {@link encryptFlowResponseAsync} for every runtime)
|
|
372
603
|
* @param response - Response object to encrypt
|
|
373
604
|
* @param aesKeyBuffer - AES key buffer from the decrypted request
|
|
374
605
|
* @param initialVectorBuffer - Initial vector buffer from the decrypted request
|
|
@@ -376,6 +607,35 @@ declare function decryptFlowRequest(body: any, config: WabaConfigType): {
|
|
|
376
607
|
* @throws {Error} If encryption fails
|
|
377
608
|
*/
|
|
378
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>;
|
|
379
639
|
//#endregion
|
|
380
640
|
//#region src/utils/flowTypeGuards.d.ts
|
|
381
641
|
declare const DATA_EXCHANGE_ACTIONS: readonly [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK];
|
|
@@ -418,5 +678,5 @@ declare function isFlowErrorRequest(request: FlowEndpointRequest): request is Fl
|
|
|
418
678
|
*/
|
|
419
679
|
declare function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest;
|
|
420
680
|
//#endregion
|
|
421
|
-
export { AUTHORIZATION_ERROR_CODES, type ApiPermissionErrorCode, BLOCK_USER_ERROR_CODES, CALLING_ERROR_CODES, type EncryptionKeyPair, FLOW_ERROR_CODES, GROUP_ERROR_CODES, INTEGRITY_ERROR_CODES, Logger, type MetaError, type MetaErrorData, 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, buildFieldsQueryString, createWhatsAppApiError, decryptFlowRequest, encryptFlowResponse, formatConfigTable, generateEncryption, 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 };
|
|
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 };
|
|
422
682
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/utils/buildFieldsQueryString.ts","../../src/types/enums.ts","../../src/types/config.ts","../../src/utils/configTable.ts","../../src/utils/isMetaError.ts","../../src/types/logger.ts","../../src/utils/logger.ts","../../src/utils/objectToQueryString.ts","../../src/api/flow/types/common.ts","../../src/utils/flowEncryptionUtils.ts","../../src/utils/flowTypeGuards.ts"],"mappings":";iBAAgB,sBAAA,CAAuB,MAA0B;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/utils/buildFieldsQueryString.ts","../../src/utils/rateLimit.ts","../../src/types/enums.ts","../../src/types/config.ts","../../src/utils/configTable.ts","../../src/utils/customerServiceWindow.ts","../../src/utils/isMetaError.ts","../../src/types/logger.ts","../../src/utils/logger.ts","../../src/utils/objectToQueryString.ts","../../src/api/flow/types/common.ts","../../src/utils/flowEncryptionUtils.ts","../../src/utils/flowTypeGuards.ts"],"mappings":";iBAAgB,sBAAA,CAAuB,MAA0B;;;;AAAjE;;;UCMiB,cAAA;EDNgD;ECQ7D,SAAA;;EAEA,YAAA;EAJa;EAMb,SAAA;AAAA;;UAIa,oBAAA,SAA6B,cAAc;EANxD;EAQA,UAAA;EANS;EAQT,IAAA;EAJa;;;;EASb,kCAAA;EAPA;EASA,gBAAA;AAAA;;;AAAgB;AAUpB;;;;UAAiB,aAAA;EAEF;EAAX,QAAA,GAAW,cAAA;EAEW;EAAtB,oBAAA,EAAsB,oBAAoB;EAO1C;EALA,YAAA;EAUY;AAAA;AAIhB;;EATI,eAAA;EAWQ;;;;EANR,YAAA;AAAA;AAOoB;AAAA,KAHZ,qBAAA,GACN,OAAA,GACA,MAAM;EACJ,GAAA,CAAI,IAAA;AAAA;;AAwE8E;AA0B1F;;iBA1BgB,eAAA,CAAgB,KAAA,6BAAkC,GAAwB;;;;;;AA0Ba;;;;ACnCvG;;;;;iBDmCgB,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AmCQ,iBAAA,CAAkB,OAAA,EAAS,mBAAA,GAAsB,OAAA,IAAW,sBAAsB"}
|
package/dist/utils/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
`)}const i=[0,1,2,3,4,10,33,100,190,200,299,368,613,80007,130429,130472,130497,131e3,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,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,133e3,133004,133005,133006,133008,133009,133010,133015,133016,134011,134100,134101,134102,135e3,137e3,138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,139e3,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],a=new Set(i),o=[0,3,10,190],s=[4,80007,130429,131048,131056],c=[368,130497,131031],l=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,131061,131062,131063,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],u=[139e3,139001,139002,139003,139004],d=[139100,139101,139102,139103],f=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,613],p=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],m=new Set(o),h=new Set(s),g=new Set(c),_=new Set(l),ee=new Set(u),te=new Set(d),ne=new Set(f),v=new Set(p);function y(e){return b(e)?!0:a.has(e)}function b(e){return e>=200&&e<300}function x(e){return b(e)||m.has(e)}function S(e){return h.has(e)}function C(e){return g.has(e)}function w(e){return _.has(e)}function T(e){return ee.has(e)}function E(e){return te.has(e)}function D(e){return ne.has(e)}function O(e){return v.has(e)}var k=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},A=class extends k{error;statusCode;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},j=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},M=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},N=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},P=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},F=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},I=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},L=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},R=class extends A{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function z(e,t){let n=e.code;return x(n)?new j(e.message,e,t):S(n)?new M(e.message,e,t):C(n)?new N(e.message,e,t):w(n)?new P(e.message,e,t):T(n)?new F(e.message,e,t):E(n)?new I(e.message,e,t):D(n)?new L(e.message,e,t):O(n)?new R(e.message,e,t):new A(e.message,e,t)}var re=class extends k{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},B=class extends k{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},V=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function H(e){if(typeof e!=`object`||!e||!(`error`in e)||typeof e.error!=`object`||e.error==null)return!1;let t=e.error;if(typeof t.message!=`string`||typeof t.type!=`string`||typeof t.code!=`number`||typeof t.fbtrace_id!=`string`)return!1;if(`error_data`in t&&t.error_data!=null){if(typeof t.error_data!=`object`)return!1;let e=t.error_data;if(`messaging_product`in e&&e.messaging_product!==`whatsapp`||`details`in e&&typeof e.details!=`string`)return!1}return!(`error_subcode`in t&&typeof t.error_subcode!=`number`)}function U(e){return H(e)&&y(e.error.code)}function W(e){return e instanceof j}function G(e){return e instanceof M}function K(e){return e instanceof N}function q(e){return e instanceof P}function J(e){return e instanceof F}function Y(e){return e instanceof I}function ie(e){return e instanceof L}function ae(e){return e instanceof R}function oe(e,t){if(H(e))return e;let n=`Unknown error occurred`;if(e&&typeof e==`object`&&`message`in e){let t=e.message;typeof t==`string`&&(n=t)}return{name:`MetaError`,message:n,error:{message:n,type:`UnknownError`,code:typeof t==`number`?t:500,fbtrace_id:``}}}var X=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(t){return t.map(t=>typeof t==`object`?e(t,{depth:null,colors:!0}):t).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const se=e=>{if(!e||Object.keys(e).length===0)return``;let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){let e=encodeURIComponent(n),i=encodeURIComponent(String(r));t.push(`${e}=${i}`)}return t.length>0?`?${t.join(`&`)}`:``},Z=new X(`FLOW_ENCRYPTION_UTILS`,process.env.DEBUG===`true`);function ce(){if(!t||typeof t.generateKeyPairSync!=`function`){let e=Error(`This utility requires Node.js environment with crypto module. It cannot be used in browser or edge runtime environments.`);throw Z.error(`Environment validation failed:`,e),e}if(typeof window<`u`){let e=Error(`This utility cannot run in a browser environment. Please use it in a Node.js server environment only.`);throw Z.error(`Browser environment detected:`,e),e}if(process.versions?.node){let e=process.versions.node.split(`.`).map(Number),t=e[0]??0,n=e[1]??0;if(t<10||t===10&&n<12){let e=Error(`Node.js version ${process.versions.node} is not supported. Please upgrade to Node.js 10.12.0 or higher.`);throw Z.error(`Node.js version check failed:`,e),e}}}function le(e){Z.info(`[generateEncryption] Starting key pair generation`),ce();let n=e||process.env.FLOW_API_PASSPHRASE;if(!n||n.trim().length===0){let e=Error(`Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.`);throw Z.error(`[generateEncryption] Passphrase validation failed:`,e),e}n.length<8&&Z.warn(`[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.`);try{Z.info(`[generateEncryption] Generating 2048-bit RSA key pair`);let e=t.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:n}});return Z.info(`[generateEncryption] Key pair generated successfully`),{passphrase:n,privateKey:e.privateKey,publicKey:e.publicKey}}catch(e){let t=e instanceof Error?e.message:String(e),n=Error(`Failed to generate key pair: ${t}`);throw Z.error(`[generateEncryption] Key generation failed:`,n),n}}function ue(e,n){if(Z.info(`[decryptFlowRequest] Starting Flow request decryption`),!n.FLOW_API_PRIVATE_PEM||n.FLOW_API_PRIVATE_PEM.trim()===``){let e=Error(`Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.`);throw Z.error(`[decryptFlowRequest] Configuration error:`,e),e}if(!n.FLOW_API_PASSPHRASE||n.FLOW_API_PASSPHRASE.trim()===``){let e=Error(`Missing FLOW_API_PASSPHRASE. Please set the FLOW_API_PASSPHRASE environment variable or pass passphrase via config.`);throw Z.error(`[decryptFlowRequest] Configuration error:`,e),e}Z.info(`[decryptFlowRequest] Configuration validated`);let{encrypted_aes_key:r,encrypted_flow_data:i,initial_vector:a}=e;if(!r||!i||!a)throw Z.error(`[decryptFlowRequest] Missing required encryption properties in request body`),Error(`Missing required encryption properties`);Z.info(`[decryptFlowRequest] Request body validated`);let o=n.FLOW_API_PRIVATE_PEM;o.includes(`\\n`)&&(o=o.replace(/\\n/g,`
|
|
3
|
-
`));let s=
|
|
1
|
+
function e(e){if(!e)return``;let t=``;return t=Array.isArray(e)?e.join(`,`):typeof e==`string`?e:Object.entries(e).filter(([e,t])=>t).map(([e])=>e).join(`,`),t?`?fields=${t}`:``}function t(e){let t=[[`App ID`,e.M4D_APP_ID||`Not Set`],[`Phone Number ID`,e.WA_PHONE_NUMBER_ID?.toString()||`Not Set`],[`Business Account ID`,e.WA_BUSINESS_ACCOUNT_ID||`Not Set`],[`API Version`,e.CLOUD_API_VERSION||`Not Set`],[`Access Token`,e.CLOUD_API_ACCESS_TOKEN?`${e.CLOUD_API_ACCESS_TOKEN.substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e.WEBHOOK_ENDPOINT||`Not Set`],[`Webhook Verification Token`,e.WEBHOOK_VERIFICATION_TOKEN?`${e.WEBHOOK_VERIFICATION_TOKEN.substring(0,10)}...`:`Not Set`],[`Listener Port`,e.LISTENER_PORT?.toString()||`Not Set`],[`Debug Mode`,e.DEBUG?`Enabled`:`Disabled`],[`Max Retries`,e.MAX_RETRIES_AFTER_WAIT?.toString()||`Not Set`],[`Request Timeout`,e.REQUEST_TIMEOUT?`${e.REQUEST_TIMEOUT}ms`:`Not Set`],[`Private PEM`,e.FLOW_API_PRIVATE_PEM?`Configured`:`Not Set`],[`Passphrase`,e.FLOW_API_PASSPHRASE?`Configured`:`Not Set`]],n=Math.max(...t.map(([e])=>e?.length||0)),r=Math.max(...t.map(([,e])=>e?.length||0)),i=Math.max(n,20),a=Math.max(r,30),o=`┌${`─`.repeat(i+2)}┬${`─`.repeat(a+2)}┐`,s=`├${`─`.repeat(i+2)}┼${`─`.repeat(a+2)}┤`,c=`└${`─`.repeat(i+2)}┴${`─`.repeat(a+2)}┘`;return[o,`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,s,...t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`),c].join(`
|
|
2
|
+
`)}const n=[0,1,2,3,4,10,33,100,190,200,299,368,613,80007,130429,130472,130497,131e3,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,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,133e3,133004,133005,133006,133008,133009,133010,133015,133016,134011,134100,134101,134102,135e3,137e3,138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,139e3,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],r=new Set(n),i=[0,3,10,190],a=[4,80007,130429,131048,131056],o=[368,130497,131031],s=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,131061,131062,131063,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],c=[139e3,139001,139002,139003,139004],l=[139100,139101,139102,139103],u=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,613],d=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],f=new Set(i),p=new Set(a),m=new Set(o),ee=new Set(s),h=new Set(c),g=new Set(l),te=new Set(u),ne=new Set(d);function re(e){return _(e)?!0:r.has(e)}function _(e){return e>=200&&e<300}function ie(e){return _(e)||f.has(e)}function ae(e){return p.has(e)}function oe(e){return m.has(e)}function se(e){return ee.has(e)}function v(e){return h.has(e)}function y(e){return g.has(e)}function b(e){return te.has(e)}function x(e){return ne.has(e)}var S=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},C=class extends S{error;statusCode;rateLimit;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},w=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},T=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},E=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},D=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},O=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},k=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},A=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},j=class extends C{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function ce(e,t){let n=e.code;return ie(n)?new w(e.message,e,t):ae(n)?new T(e.message,e,t):oe(n)?new E(e.message,e,t):se(n)?new D(e.message,e,t):v(n)?new O(e.message,e,t):y(n)?new k(e.message,e,t):b(n)?new A(e.message,e,t):x(n)?new j(e.message,e,t):new C(e.message,e,t)}var le=class extends S{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},ue=class extends S{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},M=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function N(e){if(typeof e!=`object`||!e||!(`error`in e)||typeof e.error!=`object`||e.error==null)return!1;let t=e.error;if(typeof t.message!=`string`||typeof t.type!=`string`||typeof t.code!=`number`||typeof t.fbtrace_id!=`string`)return!1;if(`error_data`in t&&t.error_data!=null){if(typeof t.error_data!=`object`)return!1;let e=t.error_data;if(`messaging_product`in e&&e.messaging_product!==`whatsapp`||`details`in e&&typeof e.details!=`string`)return!1}return!(`error_subcode`in t&&typeof t.error_subcode!=`number`)}function de(e){return N(e)&&re(e.error.code)}function fe(e){return e instanceof w}function pe(e){return e instanceof T}function me(e){return e instanceof E}function he(e){return e instanceof D}function ge(e){return e instanceof O}function _e(e){return e instanceof k}function ve(e){return e instanceof A}function ye(e){return e instanceof j}function be(e,t){if(N(e))return e;let n=`Unknown error occurred`;if(e&&typeof e==`object`&&`message`in e){let t=e.message;typeof t==`string`&&(n=t)}return{name:`MetaError`,message:n,error:{message:n,type:`UnknownError`,code:typeof t==`number`?t:500,fbtrace_id:``}}}const P=3600*1e3,F=24*P,I=72*P,xe=168*P,L=1e11;function R(e,t){let n;if(e instanceof Date)n=e.getTime();else if(typeof e==`number`)n=Math.abs(e)<L?e*1e3:e;else if(typeof e==`string`){let t=e.trim();if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);n=e<L?e*1e3:e}else n=t===``?NaN:Date.parse(t)}else n=NaN;if(!Number.isFinite(n)||!Number.isFinite(new Date(n).getTime()))throw new M(`${t} is not a valid timestamp: ${String(e)}`);return n}function z(e,t,n){if(e===void 0)return n;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw new M(`${t} must be a non-negative number of milliseconds`);return e}function B(e,t,n,r){if(!Number.isFinite(new Date(t).getTime()))throw new M(`Window expiry is outside the supported timestamp range`);let i=Math.max(0,t-e),a=t-r,o=Math.min(Math.max(0,a-n),i);return{isOpen:o>0,expiresAt:new Date(t),remainingMs:o}}const V=Object.freeze({isOpen:!1,expiresAt:null,remainingMs:0});function H(e,t={}){let n=z(t.safetyMarginMs,`safetyMarginMs`,0),r=t.now===void 0?Date.now():R(t.now,`now`);if(e==null)return{...V};let i=R(e,`lastInboundAt`);return B(i,i+F,r,n)}function Se(e,t={}){return H(e,t).isOpen}function Ce(e,t={}){let n=z(t.safetyMarginMs,`safetyMarginMs`,0),r=z(t.durationMs,`durationMs`,I),i=t.now===void 0?Date.now():R(t.now,`now`);if(e==null)return{...V};let a=R(e,`openedAt`);return B(a,t.expiresAt===void 0?a+r:R(t.expiresAt,`expiresAt`),i,n)}var U=class{name;debugEnabled;constructor(e,t=!1){this.name=e,this.debugEnabled=t}formatData(e){return e.map(e=>typeof e==`object`&&e?we(e):e).join(` `)}log(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}debug(...e){if(this.debugEnabled){let t=`[ ${Date.now()} ] - DEBUG`;this.name&&(t+=` - ${this.name}`),console.debug(t,`: `,this.formatData(e))}}};function we(e){if(e instanceof Error)return e.stack||`${e.name}: ${e.message}`;let t=new WeakSet;try{return JSON.stringify(e,(e,n)=>{if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(typeof n==`bigint`)return n.toString();if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n},2)}catch{return String(e)}}const Te=e=>{if(!e||Object.keys(e).length===0)return``;let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){let e=encodeURIComponent(n),i=encodeURIComponent(String(r));t.push(`${e}=${i}`)}return t.length>0?`?${t.join(`&`)}`:``};function W(e,t){if(typeof e.get==`function`)return e.get(t)??void 0;let n=e,r=Object.keys(n).find(e=>e.toLowerCase()===t);if(r===void 0)return;let i=n[r];return Array.isArray(i)?i[0]:i}function Ee(e){if(!(e===void 0||e.trim()===``))try{return JSON.parse(e)}catch{return}}function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``&&Number.isFinite(Number(e)))return Number(e)}function De(e){return typeof e==`string`?e:void 0}function Oe(e){let t={},n=K(e.call_count),r=K(e.total_cputime),i=K(e.total_time);return n!==void 0&&(t.callCount=n),r!==void 0&&(t.totalCputime=r),i!==void 0&&(t.totalTime=i),t}function ke(e){if(!G(e))return[];let t=[];for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r){if(!G(e))continue;let r={businessId:n,...Oe(e)},i=De(e.type),a=K(e.estimated_time_to_regain_access),o=De(e.ads_api_access_tier);i!==void 0&&(r.type=i),a!==void 0&&(r.estimatedTimeToRegainAccessMinutes=a),o!==void 0&&(r.adsApiAccessTier=o),t.push(r)}return t}function Ae(e,t=Date.now()){if(e==null)return;let n=e.trim();if(n===``)return;if(/^\d+(\.\d+)?$/.test(n))return Math.round(Number(n)*1e3);if(!/[a-z]/i.test(n))return;let r=Date.parse(n);if(Number.isFinite(r))return Math.max(0,r-t)}function je(e){if(!e)return;let t=W(e,`x-app-usage`),n=W(e,`x-business-use-case-usage`),r=W(e,`retry-after`);if(t===void 0&&n===void 0&&r===void 0)return;let i={businessUseCaseUsage:[]},a=Ee(t);G(a)&&(i.appUsage=Oe(a)),i.businessUseCaseUsage=ke(Ee(n));let o=Ae(r);o!==void 0&&(i.retryAfterMs=o);let s=[...i.appUsage?[i.appUsage]:[],...i.businessUseCaseUsage].flatMap(e=>[e.callCount,e.totalCputime,e.totalTime].filter(e=>e!==void 0));s.length>0&&(i.maxUsagePercent=Math.max(...s));let c=[...o===void 0?[]:[o],...i.businessUseCaseUsage.map(e=>e.estimatedTimeToRegainAccessMinutes).filter(e=>e!==void 0&&e>0).map(e=>e*6e4)];return c.length>0&&(i.retryDelayMs=Math.max(...c)),i}function q(){let e=globalThis.process;return typeof e==`object`&&e?e:void 0}function Me(e){return q()?.env?.[e]}function Ne(){return Me(`DEBUG`)===`true`}function J(){let e=q()?.getBuiltinModule;if(typeof e!=`function`)return q(),void 0;try{return e(`node:crypto`)}catch{return}}function Pe(e){let t=J();if(!t)throw Error(`${e} needs the node:crypto module, which is not available in this runtime. Use the async Web Crypto variant instead, or run on Node.js >= 20.12, Bun or Deno.`);return t}function Y(){let e=globalThis.crypto?.subtle;if(!e)throw Error(`Web Crypto (globalThis.crypto.subtle) is not available in this runtime.`);return e}const Fe=new TextEncoder,Ie=new TextDecoder;function Le(e){return Fe.encode(e)}function Re(e){return Ie.decode(e)}function X(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ze(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}const Z=new U(`FLOW_ENCRYPTION_UTILS`,Ne());function Be(){let e=J();if(!e||typeof e.generateKeyPairSync!=`function`){let e=Error(`This utility requires Node.js environment with crypto module. It cannot be used in browser or edge runtime environments.`);throw Z.error(`Environment validation failed:`,e),e}if(typeof window<`u`){let e=Error(`This utility cannot run in a browser environment. Please use it in a Node.js server environment only.`);throw Z.error(`Browser environment detected:`,e),e}let t=globalThis.process?.versions?.node;if(t){let e=t.split(`.`).map(Number),n=e[0]??0,r=e[1]??0;if(n<10||n===10&&r<12){let e=Error(`Node.js version ${t} is not supported. Please upgrade to Node.js 10.12.0 or higher.`);throw Z.error(`Node.js version check failed:`,e),e}}return e}function Ve(e){Z.info(`[generateEncryption] Starting key pair generation`);let t=Be(),n=e||Me(`FLOW_API_PASSPHRASE`);if(!n||n.trim().length===0){let e=Error(`Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.`);throw Z.error(`[generateEncryption] Passphrase validation failed:`,e),e}n.length<8&&Z.warn(`[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.`);try{Z.info(`[generateEncryption] Generating 2048-bit RSA key pair`);let e=t.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:n}});return Z.info(`[generateEncryption] Key pair generated successfully`),{passphrase:n,privateKey:e.privateKey,publicKey:e.publicKey}}catch(e){let t=e instanceof Error?e.message:String(e),n=Error(`Failed to generate key pair: ${t}`);throw Z.error(`[generateEncryption] Key generation failed:`,n),n}}function He(e,t){Z.info(`[decryptFlowRequest] Starting Flow request decryption`);let n=Pe(`decryptFlowRequest`);if(!t.FLOW_API_PRIVATE_PEM||t.FLOW_API_PRIVATE_PEM.trim()===``){let e=Error(`Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.`);throw Z.error(`[decryptFlowRequest] Configuration error:`,e),e}if(!t.FLOW_API_PASSPHRASE||t.FLOW_API_PASSPHRASE.trim()===``){let e=Error(`Missing FLOW_API_PASSPHRASE. Please set the FLOW_API_PASSPHRASE environment variable or pass passphrase via config.`);throw Z.error(`[decryptFlowRequest] Configuration error:`,e),e}Z.info(`[decryptFlowRequest] Configuration validated`);let{encrypted_aes_key:r,encrypted_flow_data:i,initial_vector:a}=e;if(!r||!i||!a)throw Z.error(`[decryptFlowRequest] Missing required encryption properties in request body`),Error(`Missing required encryption properties`);Z.info(`[decryptFlowRequest] Request body validated`);let o=t.FLOW_API_PRIVATE_PEM;o.includes(`\\n`)&&(o=o.replace(/\\n/g,`
|
|
3
|
+
`));let s=t.FLOW_API_PASSPHRASE,c=o.includes(`-----BEGIN RSA PRIVATE KEY-----`),l=o.includes(`-----BEGIN PRIVATE KEY-----`)||o.includes(`-----BEGIN ENCRYPTED PRIVATE KEY-----`);Z.info(`[decryptFlowRequest] Loading private key`,{format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`});let u;try{u=s?n.createPrivateKey({key:o,format:`pem`,passphrase:s}):n.createPrivateKey(o),Z.info(`[decryptFlowRequest] Private key loaded successfully`)}catch(e){if(Z.error(`[decryptFlowRequest] Failed to load private key (first attempt):`,{error:e instanceof Error?e.message:e,hasPassphrase:!!s,format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`}),c&&s)try{Z.info(`[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format`);let e=n.createPrivateKey({key:o,format:`pem`,passphrase:s}).export({type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:s});u=n.createPrivateKey({key:e,format:`pem`,passphrase:s}),Z.info(`[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key`)}catch(t){Z.error(`[decryptFlowRequest] Failed to convert PKCS#1 to PKCS#8:`,{error:t instanceof Error?t.message:t});let n=`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`;throw n+=`
|
|
4
4
|
|
|
5
5
|
Your key is in PKCS#1 format with unsupported encryption (DES-EDE3-CBC).`,n+=`
|
|
6
6
|
Please convert it to PKCS#8 format using:`,n+=`
|
|
@@ -10,5 +10,7 @@ Your key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).`,t+=`
|
|
|
10
10
|
Please convert it to PKCS#8 format using:`,t+=`
|
|
11
11
|
openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem`):l||(t+=`
|
|
12
12
|
|
|
13
|
-
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}}let d;try{Z.info(`[decryptFlowRequest] Decrypting AES key with RSA private key`),d=
|
|
13
|
+
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}}let d;try{Z.info(`[decryptFlowRequest] Decrypting AES key with RSA private key`),d=n.privateDecrypt({key:u,padding:n.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(r,`base64`)),Z.info(`[decryptFlowRequest] AES key decrypted successfully`)}catch(e){throw Z.error(`[decryptFlowRequest] Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let f=Buffer.from(i,`base64`),p=Buffer.from(a,`base64`),m=f.subarray(0,-16),ee=f.subarray(-16);Z.info(`[decryptFlowRequest] Decrypting flow data with AES-128-GCM`);let h=n.createDecipheriv(`aes-128-gcm`,d,p);h.setAuthTag(ee);let g=Buffer.concat([h.update(m),h.final()]).toString(`utf-8`);return Z.info(`[decryptFlowRequest] Flow request decrypted successfully`),{decryptedBody:JSON.parse(g),aesKeyBuffer:d,initialVectorBuffer:p}}function Ue(e,t,n){Z.info(`[encryptFlowResponse] Starting Flow response encryption`);let r=Pe(`encryptFlowResponse`),i=[];for(let e of Array.from(n.entries()))i.push(~e[1]);try{Z.info(`[encryptFlowResponse] Encrypting response with AES-128-GCM`);let n=r.createCipheriv(`aes-128-gcm`,t,Buffer.from(i)),a=Buffer.concat([n.update(JSON.stringify(e||{}),`utf-8`),n.final(),n.getAuthTag()]).toString(`base64`);return Z.info(`[encryptFlowResponse] Flow response encrypted successfully`),a}catch(e){throw Z.error(`[encryptFlowResponse] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}const We=/-----BEGIN ([A-Z ]+)-----([\s\S]*?)-----END \1-----/;let Q;function Ge(e,t){let n=We.exec(e);if(!n)throw Error(`Failed to parse private key. Expected a PEM encoded PKCS#8 private key.`);let r=n[1];if(r===`PRIVATE KEY`)return X((n[2]??``).replace(/\s+/g,``));let i=J();if(!i)throw Error(`Failed to parse private key. "${r}" keys need node:crypto, which this runtime lacks. Convert the key to an unencrypted PKCS#8 key and keep it in a secret store:
|
|
14
|
+
openssl pkcs8 -topk8 -nocrypt -in private.pem -out private-pkcs8.pem`);try{let n=i.createPrivateKey({key:e,format:`pem`,passphrase:t||void 0}).export({type:`pkcs8`,format:`der`});return new Uint8Array(n)}catch(e){throw Error(`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`)}}function Ke(e,t){if(Q&&Q.pem===e&&Q.passphrase===t)return Q.key;let n=(async()=>Y().importKey(`pkcs8`,Ge(e,t),{name:`RSA-OAEP`,hash:`SHA-256`},!1,[`decrypt`]))();return Q={pem:e,passphrase:t,key:n},n.catch(()=>{Q?.key===n&&(Q=void 0)}),n}async function qe(e,t){if(!t.FLOW_API_PRIVATE_PEM||t.FLOW_API_PRIVATE_PEM.trim()===``)throw Error(`Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.`);let{encrypted_aes_key:n,encrypted_flow_data:r,initial_vector:i}=e??{};if(!n||!r||!i)throw Error(`Missing required encryption properties`);let a=t.FLOW_API_PRIVATE_PEM;a.includes(`\\n`)&&(a=a.replace(/\\n/g,`
|
|
15
|
+
`));let o=Y(),s=await Ke(a,t.FLOW_API_PASSPHRASE||``),c;try{c=new Uint8Array(await o.decrypt({name:`RSA-OAEP`},s,X(n)))}catch(e){throw Z.error(`[decryptFlowRequestAsync] Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let l=X(i),u=await o.importKey(`raw`,c,{name:`AES-GCM`},!1,[`decrypt`]),d=await o.decrypt({name:`AES-GCM`,iv:l,tagLength:128},u,X(r));return{decryptedBody:JSON.parse(Re(new Uint8Array(d))),aesKeyBuffer:c,initialVectorBuffer:l}}async function Je(e,t,n){let r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=~(n[e]??0)&255;try{let n=Y(),i=await n.importKey(`raw`,new Uint8Array(t),{name:`AES-GCM`},!1,[`encrypt`]),a=await n.encrypt({name:`AES-GCM`,iv:r,tagLength:128},i,Le(JSON.stringify(e||{})));return ze(new Uint8Array(a))}catch(e){throw Z.error(`[encryptFlowResponseAsync] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}function Ye(e){return typeof e==`object`&&!!e}function $(e){return typeof e==`string`}const Xe=[`data_exchange`,`INIT`,`BACK`],Ze=[`data_exchange`,`INIT`];function Qe(e){if(!(`flow_token`in e&&$(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=Xe.includes(t),s=r===void 0||$(r)&&r!==`SUCCESS`,c=t===`data_exchange`||Ye(i);return a&&o&&s&&c}function $e(e){if(!(`flow_token`in e&&$(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=Ze.includes(t),a=$(n),o=Ye(r)&&`error_key`in r&&$(r.error)&&`error_message`in r&&$(r.error_message);return i&&a&&o}function et(e){return`action`in e&&e.action===`ping`}export{i as AUTHORIZATION_ERROR_CODES,l as BLOCK_USER_ERROR_CODES,u as CALLING_ERROR_CODES,F as CUSTOMER_SERVICE_WINDOW_MS,c as FLOW_ERROR_CODES,I as FREE_ENTRY_POINT_WINDOW_MS,d as GROUP_ERROR_CODES,o as INTEGRITY_ERROR_CODES,U as Logger,xe as MAX_FREE_ENTRY_POINT_WINDOW_MS,s as SEND_MESSAGE_ERROR_CODES,a as THROTTLING_ERROR_CODES,n as WHATSAPP_ERROR_CODES,C as WhatsAppApiError,w as WhatsAppAuthorizationError,k as WhatsAppBlockUserError,A as WhatsAppCallingError,S as WhatsAppError,O as WhatsAppFlowError,j as WhatsAppGroupError,E as WhatsAppIntegrityError,le as WhatsAppNetworkError,D as WhatsAppSendMessageError,T as WhatsAppThrottlingError,ue as WhatsAppUnknownError,M as WhatsAppValidationError,e as buildFieldsQueryString,Se as canSendFreeformMessage,ce as createWhatsAppApiError,He as decryptFlowRequest,qe as decryptFlowRequestAsync,Ue as encryptFlowResponse,Je as encryptFlowResponseAsync,t as formatConfigTable,Ve as generateEncryption,H as getCustomerServiceWindow,Ce as getFreeEntryPointWindow,_ as isApiPermissionErrorCode,ie as isAuthorizationErrorCode,y as isBlockUserErrorCode,b as isCallingErrorCode,Qe as isFlowDataExchangeRequest,v as isFlowErrorCode,$e as isFlowErrorRequest,et as isFlowPingRequest,x as isGroupErrorCode,oe as isIntegrityErrorCode,N as isMetaError,se as isSendMessageErrorCode,ae as isThrottlingErrorCode,de as isWhatsAppApiErrorResponse,fe as isWhatsAppAuthorizationError,_e as isWhatsAppBlockUserError,ve as isWhatsAppCallingError,re as isWhatsAppErrorCode,ge as isWhatsAppFlowError,ye as isWhatsAppGroupError,me as isWhatsAppIntegrityError,he as isWhatsAppSendMessageError,pe as isWhatsAppThrottlingError,be as normalizeMetaError,Te as objectToQueryString,je as parseRateLimitHeaders,Ae as parseRetryAfter};
|
|
14
16
|
//# sourceMappingURL=index.js.map
|