@wats/graph 0.3.29 → 0.4.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/endpoints/flows/types.d.ts +2 -2
- package/dist/endpoints/media.d.ts +0 -11
- package/dist/endpoints/media.js +0 -17
- package/dist/endpoints/templates/advanced.d.ts +2 -2
- package/dist/errors.js +3 -4
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -6
- package/dist/rateLimiter.d.ts +22 -0
- package/dist/rateLimiter.js +75 -0
- package/dist/reliableTransport.d.ts +20 -0
- package/dist/reliableTransport.js +52 -11
- package/dist/subclients/wabaClient.d.ts +6 -6
- package/package.json +4 -2
|
@@ -78,8 +78,8 @@ export interface GetFlowAssetsInput {
|
|
|
78
78
|
* Canonical Flow metric names mirrored from pywa's `FlowMetricName` enum.
|
|
79
79
|
* Unknown values are preserved as raw strings (see {@link FlowMetric.name}).
|
|
80
80
|
*
|
|
81
|
-
* Reference:
|
|
82
|
-
* deprecated 2026-04-30; whether a replacement exists is
|
|
81
|
+
* Reference: Meta Flow Metrics API docs. The Metrics API is documented as
|
|
82
|
+
* deprecated 2026-04-30; whether a replacement exists is unverified.
|
|
83
83
|
*/
|
|
84
84
|
export declare const KNOWN_FLOW_METRIC_NAMES: readonly ["ENDPOINT_REQUEST_COUNT", "ENDPOINT_REQUEST_ERROR", "ENDPOINT_REQUEST_ERROR_RATE", "ENDPOINT_REQUEST_LATENCY_SECONDS_CEIL", "ENDPOINT_AVAILABILITY"];
|
|
85
85
|
export type FlowMetricName = (typeof KNOWN_FLOW_METRIC_NAMES)[number];
|
|
@@ -1,12 +1,5 @@
|
|
|
1
1
|
import type { GraphClient } from "../client.js";
|
|
2
2
|
export type MediaOperation = "upload" | "download" | "delete" | "download_bytes" | "decrypt_encrypted" | "create_upload_session" | "upload_file_to_session" | "get_upload_session";
|
|
3
|
-
export type MediaNotImplementedCode = "not_implemented";
|
|
4
|
-
export declare class MediaNotImplementedError extends Error {
|
|
5
|
-
readonly code: MediaNotImplementedCode;
|
|
6
|
-
readonly operation: MediaOperation;
|
|
7
|
-
readonly linearIssue: string;
|
|
8
|
-
constructor(operation: MediaOperation, linearIssue: string);
|
|
9
|
-
}
|
|
10
3
|
export type MediaValidationErrorCode = "invalid_client" | "invalid_params" | "invalid_options" | "invalid_url" | "invalid_phone_number_id" | "invalid_media_id" | "invalid_app_id" | "invalid_upload_session_id" | "invalid_upload_body" | "invalid_file" | "invalid_file_name" | "invalid_file_length" | "invalid_media_type" | "invalid_file_type" | "unsupported_media_type" | "invalid_messaging_product" | "upload_too_large" | "download_too_large" | "invalid_file_offset" | "invalid_content_length" | "invalid_response";
|
|
11
4
|
export declare class MediaValidationError extends Error {
|
|
12
5
|
readonly code: MediaValidationErrorCode;
|
|
@@ -107,10 +100,6 @@ export interface GetUploadSessionResponse {
|
|
|
107
100
|
readonly id: string;
|
|
108
101
|
readonly fileOffset: number;
|
|
109
102
|
}
|
|
110
|
-
export declare const MEDIA_LINEAR_ISSUE_UPLOAD = "WATS-37";
|
|
111
|
-
export declare const MEDIA_LINEAR_ISSUE_DOWNLOAD = "WATS-37";
|
|
112
|
-
export declare const MEDIA_LINEAR_ISSUE_DELETE = "WATS-37";
|
|
113
|
-
export declare const MEDIA_LINEAR_ISSUE_DECRYPT = "WATS-37";
|
|
114
103
|
export declare function uploadMedia(client: GraphClient, params: {
|
|
115
104
|
phoneNumberId: string;
|
|
116
105
|
}, body: MediaUploadBody, options?: MediaUploadOptions): Promise<MediaUploadResponse>;
|
package/dist/endpoints/media.js
CHANGED
|
@@ -1,18 +1,5 @@
|
|
|
1
1
|
import { createGraphApiError } from "../errors.js";
|
|
2
2
|
|
|
3
|
-
export class MediaNotImplementedError extends Error {
|
|
4
|
-
code;
|
|
5
|
-
operation;
|
|
6
|
-
linearIssue;
|
|
7
|
-
constructor(operation, linearIssue) {
|
|
8
|
-
super(`Media ${operation} is not implemented. Track implementation via Linear issue ${linearIssue}.`);
|
|
9
|
-
this.name = "MediaNotImplementedError";
|
|
10
|
-
this.code = "not_implemented";
|
|
11
|
-
this.operation = operation;
|
|
12
|
-
this.linearIssue = linearIssue;
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
|
|
16
3
|
export class MediaValidationError extends Error {
|
|
17
4
|
code;
|
|
18
5
|
constructor(code, message, cause) {
|
|
@@ -65,10 +52,6 @@ const TYPED_ARRAY_PROTOTYPE = Object.getPrototypeOf(Uint8Array.prototype);
|
|
|
65
52
|
const TYPED_ARRAY_BUFFER_GETTER = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "buffer")?.get;
|
|
66
53
|
const TYPED_ARRAY_BYTE_LENGTH_GETTER = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "byteLength")?.get;
|
|
67
54
|
const TYPED_ARRAY_BYTE_OFFSET_GETTER = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "byteOffset")?.get;
|
|
68
|
-
export const MEDIA_LINEAR_ISSUE_UPLOAD = "WATS-37";
|
|
69
|
-
export const MEDIA_LINEAR_ISSUE_DOWNLOAD = "WATS-37";
|
|
70
|
-
export const MEDIA_LINEAR_ISSUE_DELETE = "WATS-37";
|
|
71
|
-
export const MEDIA_LINEAR_ISSUE_DECRYPT = "WATS-37";
|
|
72
55
|
const MAX_PATH_DECODE_ROUNDS = 5;
|
|
73
56
|
const SAFE_ID_REGEXP = /^[A-Za-z0-9_-]+$/;
|
|
74
57
|
const PHONE_NUMBER_ID_REGEXP = /^\d+$/;
|
|
@@ -171,7 +171,7 @@ export interface UnarchiveTemplatesResponse {
|
|
|
171
171
|
* {@link ARCHIVE_TEMPLATES_MAX_IDS} message templates on a WABA. Mirrors
|
|
172
172
|
* pywa's `WhatsApp.archive_templates`. Uses `GraphClient.requestRaw` (not
|
|
173
173
|
* `defineEndpoint`) because the endpoint lives on api.facebook.com, not
|
|
174
|
-
* graph.facebook.com. See
|
|
174
|
+
* graph.facebook.com. See maintainers/template-management-reference.md §5.
|
|
175
175
|
*/
|
|
176
176
|
export declare function archiveTemplates(client: GraphClient, params: ArchiveTemplatesInput, _body?: never, opts?: EndpointInvokeOptions): Promise<ArchiveTemplatesResponse>;
|
|
177
177
|
/**
|
|
@@ -180,7 +180,7 @@ export declare function archiveTemplates(client: GraphClient, params: ArchiveTem
|
|
|
180
180
|
* {@link ARCHIVE_TEMPLATES_MAX_IDS} message templates on a WABA. Mirrors
|
|
181
181
|
* pywa's `WhatsApp.unarchive_templates`. Uses `GraphClient.requestRaw` (not
|
|
182
182
|
* `defineEndpoint`) because the endpoint lives on api.facebook.com, not
|
|
183
|
-
* graph.facebook.com. See
|
|
183
|
+
* graph.facebook.com. See maintainers/template-management-reference.md §5.
|
|
184
184
|
*/
|
|
185
185
|
export declare function unarchiveTemplates(client: GraphClient, params: UnarchiveTemplatesInput, _body?: never, opts?: EndpointInvokeOptions): Promise<UnarchiveTemplatesResponse>;
|
|
186
186
|
/** Finite cap on the number of languages per upsert call (defensive bound). */
|
package/dist/errors.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isRecord } from "@wats/internal-utils";
|
|
2
|
+
|
|
1
3
|
export class GraphApiError extends Error {
|
|
2
4
|
status;
|
|
3
5
|
type;
|
|
@@ -112,9 +114,6 @@ export class GraphSerializationError extends GraphApiError {
|
|
|
112
114
|
this.cause = cause;
|
|
113
115
|
}
|
|
114
116
|
}
|
|
115
|
-
function isRecord(value) {
|
|
116
|
-
return typeof value === "object" && value !== null;
|
|
117
|
-
}
|
|
118
117
|
export function isGraphApiErrorPayload(value) {
|
|
119
118
|
if (!isRecord(value) || Array.isArray(value)) {
|
|
120
119
|
return false;
|
|
@@ -178,7 +177,7 @@ function isRateLimitClassification(status, payload) {
|
|
|
178
177
|
}
|
|
179
178
|
return false;
|
|
180
179
|
}
|
|
181
|
-
const BEARER_TOKEN_REGEXP = /
|
|
180
|
+
const BEARER_TOKEN_REGEXP = /Bearer\s+\S+/g;
|
|
182
181
|
function redactString(value) {
|
|
183
182
|
return value.replace(BEARER_TOKEN_REGEXP, "Bearer ***");
|
|
184
183
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -17,9 +17,10 @@ export { WABAClient, validateWABAClientConfig } from "./subclients/wabaClient.js
|
|
|
17
17
|
export type { WABAClientConfig } from "./subclients/wabaClient.js";
|
|
18
18
|
export * from "./transport.js";
|
|
19
19
|
export * from "./reliableTransport.js";
|
|
20
|
+
export * from "./rateLimiter.js";
|
|
20
21
|
export { createFetchTransport } from "./createFetchTransport.js";
|
|
21
22
|
export type { CreateFetchTransportOptions } from "./createFetchTransport.js";
|
|
22
23
|
export { paginate, paginateAll, PaginationError } from "./pagination.js";
|
|
23
24
|
export type { PaginationOptions, PaginatedResult, PaginatedPage, PaginationErrorCode } from "./pagination.js";
|
|
24
|
-
export { uploadMedia, downloadMedia, deleteMedia, downloadMediaBytes, decryptEncryptedMedia, createUploadSession, uploadFileToSession, getUploadSession,
|
|
25
|
-
export type { MediaOperation,
|
|
25
|
+
export { uploadMedia, downloadMedia, deleteMedia, downloadMediaBytes, decryptEncryptedMedia, createUploadSession, uploadFileToSession, getUploadSession, MediaValidationError, MediaCryptoError, MediaIntegrityError, DEFAULT_MAX_MEDIA_UPLOAD_BYTES, MAX_MEDIA_UPLOAD_BYTES, DEFAULT_MAX_MEDIA_DOWNLOAD_BYTES, MAX_MEDIA_DOWNLOAD_BYTES, DEFAULT_MAX_UPLOAD_SESSION_BYTES, MAX_UPLOAD_SESSION_BYTES } from "./endpoints/media.js";
|
|
26
|
+
export type { MediaOperation, MediaValidationErrorCode, MediaCryptoErrorCode, MediaIntegrityErrorCode, MediaUploadBody, MediaUploadOptions, MediaUploadResponse, MediaDownloadOptions, MediaDownloadResponse, MediaDeleteOptions, MediaDeleteResponse, MediaDownloadBytesOptions, MediaDownloadBytesResponse, EncryptedMediaBundle, CreateUploadSessionParams, UploadSessionOptions, CreateUploadSessionResponse, UploadFileToSessionParams, UploadFileToSessionResponse, GetUploadSessionParams, GetUploadSessionResponse } from "./endpoints/media.js";
|
package/dist/index.js
CHANGED
|
@@ -23,6 +23,7 @@ export {
|
|
|
23
23
|
} from "./subclients/wabaClient.js";
|
|
24
24
|
export * from "./transport.js";
|
|
25
25
|
export * from "./reliableTransport.js";
|
|
26
|
+
export * from "./rateLimiter.js";
|
|
26
27
|
export { createFetchTransport } from "./createFetchTransport.js";
|
|
27
28
|
export {
|
|
28
29
|
paginate,
|
|
@@ -38,7 +39,6 @@ export {
|
|
|
38
39
|
createUploadSession,
|
|
39
40
|
uploadFileToSession,
|
|
40
41
|
getUploadSession,
|
|
41
|
-
MediaNotImplementedError,
|
|
42
42
|
MediaValidationError,
|
|
43
43
|
MediaCryptoError,
|
|
44
44
|
MediaIntegrityError,
|
|
@@ -47,9 +47,5 @@ export {
|
|
|
47
47
|
DEFAULT_MAX_MEDIA_DOWNLOAD_BYTES,
|
|
48
48
|
MAX_MEDIA_DOWNLOAD_BYTES,
|
|
49
49
|
DEFAULT_MAX_UPLOAD_SESSION_BYTES,
|
|
50
|
-
MAX_UPLOAD_SESSION_BYTES
|
|
51
|
-
MEDIA_LINEAR_ISSUE_UPLOAD,
|
|
52
|
-
MEDIA_LINEAR_ISSUE_DOWNLOAD,
|
|
53
|
-
MEDIA_LINEAR_ISSUE_DELETE,
|
|
54
|
-
MEDIA_LINEAR_ISSUE_DECRYPT
|
|
50
|
+
MAX_UPLOAD_SESSION_BYTES
|
|
55
51
|
} from "./endpoints/media.js";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface RateLimiter {
|
|
2
|
+
/**
|
|
3
|
+
* Wait until `cost` tokens are available, then deduct them. Resolves once
|
|
4
|
+
* the request is admitted; never rejects unless the injected sleep does.
|
|
5
|
+
*/
|
|
6
|
+
acquire(cost?: number): Promise<void>;
|
|
7
|
+
/**
|
|
8
|
+
* Non-blocking admission check. Refills the bucket to the current virtual
|
|
9
|
+
* time, then if `cost` tokens are available deducts them and returns true;
|
|
10
|
+
* otherwise returns false without deducting.
|
|
11
|
+
*/
|
|
12
|
+
tryAcquire(cost?: number): boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface CreateTokenBucketRateLimiterOptions {
|
|
15
|
+
readonly capacity: number;
|
|
16
|
+
readonly refillPerSecond: number;
|
|
17
|
+
/** Injectable clock returning epoch milliseconds. Defaults to Date.now. */
|
|
18
|
+
readonly now?: () => number;
|
|
19
|
+
/** Injectable sleep for the wait path. Defaults to setTimeout-based sleep. */
|
|
20
|
+
readonly sleep?: (delayMs: number) => Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
export declare function createTokenBucketRateLimiter(options: CreateTokenBucketRateLimiterOptions): RateLimiter;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
const MAX_CAPACITY = 1e4;
|
|
2
|
+
function defaultSleep(delayMs) {
|
|
3
|
+
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
4
|
+
}
|
|
5
|
+
function assertCapacity(value) {
|
|
6
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 1e4) {
|
|
7
|
+
throw new Error("CreateTokenBucketRateLimiterOptions: capacity must be an integer in [1, 10000].");
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
function assertRefillPerSecond(value) {
|
|
12
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
13
|
+
throw new Error("CreateTokenBucketRateLimiterOptions: refillPerSecond must be a finite number > 0.");
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
export function createTokenBucketRateLimiter(options) {
|
|
18
|
+
if (options === null || typeof options !== "object") {
|
|
19
|
+
throw new Error("CreateTokenBucketRateLimiterOptions: options must be an object.");
|
|
20
|
+
}
|
|
21
|
+
const capacity = assertCapacity(options.capacity);
|
|
22
|
+
const refillPerSecond = assertRefillPerSecond(options.refillPerSecond);
|
|
23
|
+
if (options.now !== undefined && typeof options.now !== "function") {
|
|
24
|
+
throw new Error("CreateTokenBucketRateLimiterOptions: now must be a function.");
|
|
25
|
+
}
|
|
26
|
+
if (options.sleep !== undefined && typeof options.sleep !== "function") {
|
|
27
|
+
throw new Error("CreateTokenBucketRateLimiterOptions: sleep must be a function.");
|
|
28
|
+
}
|
|
29
|
+
const now = options.now ?? (() => Date.now());
|
|
30
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
31
|
+
let tokens = capacity;
|
|
32
|
+
let lastRefillMs = now();
|
|
33
|
+
function assertCost(cost) {
|
|
34
|
+
const c = cost ?? 1;
|
|
35
|
+
if (typeof c !== "number" || !Number.isInteger(c) || c < 1 || c > capacity) {
|
|
36
|
+
throw new Error(`RateLimiter: cost must be an integer in [1, ${capacity}] (the bucket capacity).`);
|
|
37
|
+
}
|
|
38
|
+
return c;
|
|
39
|
+
}
|
|
40
|
+
function refill() {
|
|
41
|
+
const currentMs = now();
|
|
42
|
+
const elapsedMs = currentMs - lastRefillMs;
|
|
43
|
+
if (elapsedMs > 0) {
|
|
44
|
+
const added = elapsedMs / 1000 * refillPerSecond;
|
|
45
|
+
tokens = Math.min(capacity, tokens + added);
|
|
46
|
+
lastRefillMs = currentMs;
|
|
47
|
+
} else if (elapsedMs < 0) {
|
|
48
|
+
lastRefillMs = currentMs;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
async acquire(cost) {
|
|
53
|
+
const c = assertCost(cost);
|
|
54
|
+
for (;; ) {
|
|
55
|
+
refill();
|
|
56
|
+
if (tokens >= c) {
|
|
57
|
+
tokens -= c;
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const deficit = c - tokens;
|
|
61
|
+
const waitMs = deficit / refillPerSecond * 1000;
|
|
62
|
+
await sleep(Math.max(0, waitMs));
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
tryAcquire(cost) {
|
|
66
|
+
const c = assertCost(cost);
|
|
67
|
+
refill();
|
|
68
|
+
if (tokens >= c) {
|
|
69
|
+
tokens -= c;
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import type { Transport, TransportRequest, TransportResponse, TransportRetryPolicy } from "./transport.js";
|
|
2
|
+
import type { RateLimiter } from "./rateLimiter.js";
|
|
2
3
|
export interface ReliableTransportRetryContext {
|
|
3
4
|
readonly attempt: number;
|
|
4
5
|
readonly request: TransportRequest;
|
|
5
6
|
readonly response?: TransportResponse;
|
|
6
7
|
readonly error?: unknown;
|
|
7
8
|
}
|
|
9
|
+
export type RetryPostMode = "never" | "network-only" | "always";
|
|
8
10
|
export interface ReliableTransportOptions extends Partial<TransportRetryPolicy> {
|
|
9
11
|
readonly timeoutMs?: number;
|
|
10
12
|
readonly retryOn?: (ctx: ReliableTransportRetryContext) => boolean;
|
|
@@ -13,5 +15,23 @@ export interface ReliableTransportOptions extends Partial<TransportRetryPolicy>
|
|
|
13
15
|
}) => void | Promise<void>;
|
|
14
16
|
readonly sleep?: (delayMs: number) => Promise<void>;
|
|
15
17
|
readonly random?: () => number;
|
|
18
|
+
/**
|
|
19
|
+
* Controls retry of non-idempotent POST requests. Default "never" preserves
|
|
20
|
+
* the historical behavior: POST is retried only on 429 (the rate-limit
|
|
21
|
+
* exception), never on 5xx or network errors.
|
|
22
|
+
*
|
|
23
|
+
* - "network-only": additionally retry a POST whose request threw a
|
|
24
|
+
* GraphNetworkError BEFORE any response arrived, but only when the request
|
|
25
|
+
* carries an Idempotency-Key header (case-insensitive). A pre-response
|
|
26
|
+
* network failure is the one POST failure shape that cannot have been
|
|
27
|
+
* processed by the server, so an idempotency key makes the retry safe.
|
|
28
|
+
* POST 5xx is still not retried — the server may have side-effected.
|
|
29
|
+
* - "always": additionally retry POST on 5xx. Requires server-side
|
|
30
|
+
* idempotency for the endpoint; a 5xx after the server began processing
|
|
31
|
+
* can otherwise duplicate a send. Use only for endpoints you have
|
|
32
|
+
* verified are idempotent or dedupe by Idempotency-Key.
|
|
33
|
+
*/
|
|
34
|
+
readonly retryPosts?: RetryPostMode;
|
|
35
|
+
readonly rateLimiter?: RateLimiter;
|
|
16
36
|
}
|
|
17
37
|
export declare function createReliableTransport(inner: Transport, options?: ReliableTransportOptions): Transport;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { GraphNetworkError } from "./errors.js";
|
|
2
2
|
import { DEFAULT_TRANSPORT_RETRY_POLICY } from "./transport.js";
|
|
3
|
+
const VALID_RETRY_POST_MODES = ["never", "network-only", "always"];
|
|
3
4
|
function assertFiniteNumber(value, name, min) {
|
|
4
5
|
if (typeof value !== "number" || !Number.isFinite(value) || value < min) {
|
|
5
6
|
throw new Error(`ReliableTransportOptions: ${name} must be a finite number >= ${min}.`);
|
|
@@ -33,6 +34,16 @@ function resolvePolicy(options) {
|
|
|
33
34
|
throw new Error("ReliableTransportOptions: sleep must be a function.");
|
|
34
35
|
if (options?.random !== undefined && typeof options.random !== "function")
|
|
35
36
|
throw new Error("ReliableTransportOptions: random must be a function.");
|
|
37
|
+
const retryPosts = resolveRetryPostMode(options?.retryPosts);
|
|
38
|
+
if (options?.rateLimiter !== undefined) {
|
|
39
|
+
const rl = options.rateLimiter;
|
|
40
|
+
if (rl === null || typeof rl !== "object" || typeof rl.acquire !== "function") {
|
|
41
|
+
throw new Error("ReliableTransportOptions: rateLimiter must be an object with an acquire(cost?) => Promise<void> method.");
|
|
42
|
+
}
|
|
43
|
+
if (typeof rl.tryAcquire !== "function") {
|
|
44
|
+
throw new Error("ReliableTransportOptions: rateLimiter must also implement tryAcquire(cost?) => boolean.");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
36
47
|
return {
|
|
37
48
|
retries,
|
|
38
49
|
baseDelayMs,
|
|
@@ -42,21 +53,47 @@ function resolvePolicy(options) {
|
|
|
42
53
|
...options?.retryOn !== undefined ? { retryOn: options.retryOn } : {},
|
|
43
54
|
...options?.onRetry !== undefined ? { onRetry: options.onRetry } : {},
|
|
44
55
|
sleep: options?.sleep ?? defaultSleep,
|
|
45
|
-
random: options?.random ?? Math.random
|
|
56
|
+
random: options?.random ?? Math.random,
|
|
57
|
+
retryPosts,
|
|
58
|
+
...options?.rateLimiter !== undefined ? { rateLimiter: options.rateLimiter } : {}
|
|
46
59
|
};
|
|
47
60
|
}
|
|
61
|
+
function resolveRetryPostMode(value) {
|
|
62
|
+
if (value === undefined)
|
|
63
|
+
return "never";
|
|
64
|
+
if (typeof value !== "string" || !VALID_RETRY_POST_MODES.includes(value)) {
|
|
65
|
+
throw new Error(`ReliableTransportOptions: retryPosts must be one of ${VALID_RETRY_POST_MODES.map((m) => `"${m}"`).join(", ")} (got ${value === undefined ? "undefined" : JSON.stringify(value)}).`);
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
48
69
|
function isRetryableMethod(method) {
|
|
49
70
|
return method === "GET" || method === "DELETE";
|
|
50
71
|
}
|
|
51
|
-
function
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
72
|
+
function hasIdempotencyKey(req) {
|
|
73
|
+
return req.headers.has("idempotency-key");
|
|
74
|
+
}
|
|
75
|
+
function makeDefaultRetryOn(retryPosts) {
|
|
76
|
+
return (ctx) => {
|
|
77
|
+
const status = ctx.response?.status;
|
|
78
|
+
if (status === 429)
|
|
79
|
+
return true;
|
|
80
|
+
const method = ctx.request.method;
|
|
81
|
+
const retryableMethod = isRetryableMethod(method);
|
|
82
|
+
const is5xx = typeof status === "number" && status >= 500 && status < 600;
|
|
83
|
+
if (ctx.error instanceof GraphNetworkError) {
|
|
84
|
+
if (retryableMethod)
|
|
85
|
+
return true;
|
|
86
|
+
if (method === "POST" && retryPosts !== "never") {
|
|
87
|
+
return hasIdempotencyKey(ctx.request);
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
if (retryableMethod)
|
|
92
|
+
return is5xx;
|
|
93
|
+
if (method === "POST" && retryPosts === "always")
|
|
94
|
+
return is5xx;
|
|
56
95
|
return false;
|
|
57
|
-
|
|
58
|
-
return true;
|
|
59
|
-
return typeof status === "number" && status >= 500 && status < 600;
|
|
96
|
+
};
|
|
60
97
|
}
|
|
61
98
|
function parseRetryAfterMs(header, nowMs) {
|
|
62
99
|
if (header === null)
|
|
@@ -140,16 +177,20 @@ export function createReliableTransport(inner, options) {
|
|
|
140
177
|
return {
|
|
141
178
|
async request(req, opts) {
|
|
142
179
|
const policy = resolvePolicy(options);
|
|
180
|
+
const retryOn = policy.retryOn ?? makeDefaultRetryOn(policy.retryPosts);
|
|
143
181
|
let attempt = 0;
|
|
144
182
|
for (;; ) {
|
|
145
183
|
throwIfAborted(opts?.signal);
|
|
184
|
+
if (policy.rateLimiter !== undefined) {
|
|
185
|
+
await policy.rateLimiter.acquire();
|
|
186
|
+
}
|
|
146
187
|
attempt += 1;
|
|
147
188
|
const composedSignal = composeSignal(opts?.signal, policy.timeoutMs);
|
|
148
189
|
const attemptOpts = composedSignal !== undefined ? { signal: composedSignal } : undefined;
|
|
149
190
|
try {
|
|
150
191
|
const response = await inner.request(req, attemptOpts);
|
|
151
192
|
const ctx = { attempt, request: req, response };
|
|
152
|
-
const shouldRetry =
|
|
193
|
+
const shouldRetry = retryOn(ctx);
|
|
153
194
|
if (!shouldRetry || attempt > policy.retries)
|
|
154
195
|
return response;
|
|
155
196
|
await cancelRetryResponseBody(response);
|
|
@@ -161,7 +202,7 @@ export function createReliableTransport(inner, options) {
|
|
|
161
202
|
if (opts?.signal?.aborted)
|
|
162
203
|
throw error;
|
|
163
204
|
const ctx = { attempt, request: req, error };
|
|
164
|
-
const shouldRetry =
|
|
205
|
+
const shouldRetry = retryOn(ctx);
|
|
165
206
|
if (!shouldRetry || attempt > policy.retries)
|
|
166
207
|
throw error;
|
|
167
208
|
throwIfAborted(opts?.signal);
|
|
@@ -73,7 +73,7 @@ export declare class WABAClient {
|
|
|
73
73
|
* Graph `POST /{templateId}/unpause` (WATS-153). Template-id scoped edge
|
|
74
74
|
* that unpauses a paused template. Delegates to the endpoint-registry
|
|
75
75
|
* callable; the bound wabaId is not used (mirrors getMessageTemplate).
|
|
76
|
-
* The endpoint/response shape is UNVERIFIED — see
|
|
76
|
+
* The endpoint/response shape is UNVERIFIED — see maintainers/template-management-reference.md.
|
|
77
77
|
*/
|
|
78
78
|
unpauseTemplate(params: UnpauseTemplateInput, opts?: EndpointInvokeOptions): Promise<TemplateUnpauseResult>;
|
|
79
79
|
/**
|
|
@@ -82,7 +82,7 @@ export declare class WABAClient {
|
|
|
82
82
|
* into the bound destination WABA. Mirrors pywa's
|
|
83
83
|
* `WhatsApp.migrate_templates`. The bound wabaId is used as the
|
|
84
84
|
* destination and wins over any caller-supplied `destinationWabaId`
|
|
85
|
-
* (mirrors `migrateFlows`).
|
|
85
|
+
* (mirrors `migrateFlows`).
|
|
86
86
|
*/
|
|
87
87
|
migrateTemplates(params: Omit<MigrateTemplatesInput, "destinationWabaId">, opts?: EndpointInvokeOptions): Promise<MigrateTemplatesResponse>;
|
|
88
88
|
/**
|
|
@@ -92,7 +92,7 @@ export declare class WABAClient {
|
|
|
92
92
|
* `GraphClient.requestRaw` (not `defineEndpoint`) because the endpoint
|
|
93
93
|
* lives on api.facebook.com, not graph.facebook.com. The bound wabaId is
|
|
94
94
|
* used in the path and wins over any caller-supplied `wabaId` (mirrors
|
|
95
|
-
* `migrateTemplates`). See
|
|
95
|
+
* `migrateTemplates`). See maintainers/template-management-reference.md §5.
|
|
96
96
|
*/
|
|
97
97
|
archiveTemplates(params: Omit<ArchiveTemplatesInput, "wabaId">, opts?: EndpointInvokeOptions): Promise<ArchiveTemplatesResponse>;
|
|
98
98
|
/**
|
|
@@ -102,7 +102,7 @@ export declare class WABAClient {
|
|
|
102
102
|
* `GraphClient.requestRaw` (not `defineEndpoint`) because the endpoint
|
|
103
103
|
* lives on api.facebook.com, not graph.facebook.com. The bound wabaId is
|
|
104
104
|
* used in the path and wins over any caller-supplied `wabaId` (mirrors
|
|
105
|
-
* `migrateTemplates`). See
|
|
105
|
+
* `migrateTemplates`). See maintainers/template-management-reference.md §5.
|
|
106
106
|
*/
|
|
107
107
|
unarchiveTemplates(params: Omit<UnarchiveTemplatesInput, "wabaId">, opts?: EndpointInvokeOptions): Promise<UnarchiveTemplatesResponse>;
|
|
108
108
|
/**
|
|
@@ -147,14 +147,14 @@ export declare class WABAClient {
|
|
|
147
147
|
* Graph `GET /{flowId}?fields=metric.name(...).granularity(...)...`
|
|
148
148
|
* (WATS-154). Flow-id scoped edge that returns Flow metrics; the bound
|
|
149
149
|
* wabaId is not used because the path is flow-id scoped (mirrors
|
|
150
|
-
* getFlow / getFlowAssets).
|
|
150
|
+
* getFlow / getFlowAssets).
|
|
151
151
|
*/
|
|
152
152
|
getFlowMetrics(params: GetFlowMetricsInput, opts?: EndpointInvokeOptions): Promise<FlowMetric>;
|
|
153
153
|
/**
|
|
154
154
|
* Graph `POST /{wabaId}/migrate_flows?source_waba_id=...&source_flow_names=...`
|
|
155
155
|
* (WATS-154). Copies (not moves) Flows from a source WABA into the bound
|
|
156
156
|
* destination WABA. Mirrors pywa's `WhatsApp.migrate_flows`. The bound
|
|
157
|
-
* wabaId is used as the destination
|
|
157
|
+
* wabaId is used as the destination.
|
|
158
158
|
*/
|
|
159
159
|
migrateFlows(params: Omit<MigrateFlowsInput, "destinationWabaId">, opts?: EndpointInvokeOptions): Promise<MigrateFlowsResponse>;
|
|
160
160
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wats/graph",
|
|
3
|
-
"
|
|
3
|
+
"description": "Graph client, transport, endpoints, errors, pagination.",
|
|
4
|
+
"version": "0.4.0-beta.0",
|
|
4
5
|
"private": false,
|
|
5
6
|
"license": "MIT",
|
|
6
7
|
"type": "module",
|
|
@@ -85,6 +86,7 @@
|
|
|
85
86
|
"wats"
|
|
86
87
|
],
|
|
87
88
|
"dependencies": {
|
|
88
|
-
"@wats/crypto": "^0.
|
|
89
|
+
"@wats/crypto": "^0.4.0-beta.0",
|
|
90
|
+
"@wats/internal-utils": "^0.4.0-beta.0"
|
|
89
91
|
}
|
|
90
92
|
}
|