@theokit/gateway-whatsapp 0.2.0 → 0.3.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/index.d.cts CHANGED
@@ -52,30 +52,56 @@ interface WhatsAppStatusReceipt {
52
52
  /** Receipt timestamp. */
53
53
  readonly timestamp: number;
54
54
  }
55
+ /**
56
+ * What went wrong, in the vocabulary a caller can branch on.
57
+ *
58
+ * Extracted from `WhatsAppSendResult` rather than copied beside it: a credential check and a
59
+ * send fail for the same reasons, and two declarations of one vocabulary drift the moment
60
+ * somebody adds a code to one of them.
61
+ */
62
+ interface WhatsAppError {
63
+ readonly code: "auth_failed" | "rate_limit" | "invalid_request"
64
+ /**
65
+ * More than 24 hours since the recipient last replied. The payload was
66
+ * fine and the credential is fine; WhatsApp policy refuses free-form text
67
+ * outside that window. The remedy is specific and different from every
68
+ * other error here — resend as an approved template — which is why it is
69
+ * its own code rather than one more `invalid_request`.
70
+ */
71
+ | "session_window_expired"
72
+ /**
73
+ * The recipient was never registered against this phone number. The payload
74
+ * is fine and the credential is fine; the number simply may not message this
75
+ * person yet. Its own code because the remedy is a console step rather than
76
+ * anything in the request — and because every Cloud API app starts on a test
77
+ * number, it is the error most integrations meet first.
78
+ */
79
+ | "recipient_not_allowlisted"
80
+ /**
81
+ * `send()` was called without a successful `connect()`, or after `disconnect()`.
82
+ *
83
+ * Its own code because all three backends reach this state and used to describe it three
84
+ * different ways — `server_error` from web and Baileys, nothing at all from Cloud, which
85
+ * sent regardless. A caller cannot branch on prose, and a conformance test cannot assert on
86
+ * it either: one code is what makes "the implementations agree" a checkable claim rather
87
+ * than a hope.
88
+ */
89
+ | "not_connected"
90
+ /**
91
+ * The recipient cannot receive this message, and no retry changes that:
92
+ * no WhatsApp account, terms not accepted, an outdated client, or the
93
+ * business having blocked them. Terminal by nature; the cause is in the
94
+ * message.
95
+ */
96
+ | "undeliverable" | "server_error" | "timeout" | "unknown";
97
+ readonly message: string;
98
+ }
55
99
  /** Per-message send result returned by `WhatsAppBackend.send`. */
56
100
  interface WhatsAppSendResult {
57
101
  readonly ok: boolean;
58
102
  /** Set when ok=true. The wamid Meta / web assigned to the outbound message. */
59
103
  readonly wamid?: string;
60
- readonly error?: {
61
- readonly code: "auth_failed" | "rate_limit" | "invalid_request"
62
- /**
63
- * More than 24 hours since the recipient last replied. The payload was
64
- * fine and the credential is fine; WhatsApp policy refuses free-form text
65
- * outside that window. The remedy is specific and different from every
66
- * other error here — resend as an approved template — which is why it is
67
- * its own code rather than one more `invalid_request`.
68
- */
69
- | "session_window_expired"
70
- /**
71
- * The recipient cannot receive this message, and no retry changes that:
72
- * no WhatsApp account, terms not accepted, an outdated client, or the
73
- * business having blocked them. Terminal by nature; the cause is in the
74
- * message.
75
- */
76
- | "undeliverable" | "server_error" | "timeout" | "unknown";
77
- readonly message: string;
78
- };
104
+ readonly error?: WhatsAppError;
79
105
  }
80
106
  /**
81
107
  * Backend contract — every backend (cloud, web, future) implements this shape.
@@ -83,8 +109,43 @@ interface WhatsAppSendResult {
83
109
  */
84
110
  interface WhatsAppBackend {
85
111
  readonly kind: "cloud" | "web" | "baileys";
112
+ /**
113
+ * Make the backend usable, and report whether it is.
114
+ *
115
+ * Idempotent: a second call while connected returns `true` without repeating the work.
116
+ *
117
+ * **Operational failure returns `false`; misconfiguration throws.** A rejected credential, an
118
+ * unreachable server, a session that never opens — those are conditions a supervisor can retry
119
+ * or report, so they come back as `false` with the reason written where a human can read it. A
120
+ * missing peer dependency or an absent browser is not: no retry fixes it, and answering `false`
121
+ * would bury a setup error under a runtime one.
122
+ *
123
+ * The line was drawn after the conformance suite asserted the absolute version and two of three
124
+ * implementations "failed" it — correctly. They throw `ConfigurationError` and
125
+ * `WhatsAppBridgeError` for exactly the case that should not be swallowed.
126
+ */
86
127
  connect(): Promise<boolean>;
128
+ /** Release whatever `connect()` took. Idempotent, and safe on a backend that never connected. */
87
129
  disconnect(): Promise<void>;
130
+ /**
131
+ * Send one message.
132
+ *
133
+ * **Requires a successful `connect()` first, and refuses without one** — with
134
+ * `ok: false, error.code === "not_connected"`, never a throw, and without touching the
135
+ * transport. One code across every implementation, because a caller branches on the code and
136
+ * a conformance test can only assert on one.
137
+ *
138
+ * That sentence is here because its absence cost something. The interface used to declare bare
139
+ * signatures, each implementation answered the unasked question its own way, and they diverged:
140
+ * web and Baileys refused, Cloud posted regardless. A consumer swapping backends — the single
141
+ * thing this seam exists to allow — found unconnected sends leaving the process, which for
142
+ * Cloud meant a real request carrying a credential nothing had verified, or one `connect()`
143
+ * had already rejected.
144
+ *
145
+ * Enforced by `tests/backend-conformance.test.ts` against every implementation at once. A
146
+ * per-backend test proves one of them does something; only a shared one proves they agree, and
147
+ * the agreement is the product.
148
+ */
88
149
  send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
89
150
  /** Subscribe to normalized inbound events. Returns unsubscribe. */
90
151
  onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
@@ -589,10 +650,16 @@ interface MetaTemplateComponent {
589
650
  /**
590
651
  * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).
591
652
  *
592
- * `connect()` / `disconnect()` are no-ops (HTTP push via webhook is the only
593
- * inbound channel). Outbound delegates to `WhatsAppCloudClient`. Inbound
594
- * dispatch is driven by the user calling `handleWebhookPayload(rawBody, sig)`
595
- * from inside their HTTP route.
653
+ * `connect()` verifies the credential against Meta and caches the result; `disconnect()` clears
654
+ * it. This header used to say both were no-ops, which is what the code did and what the first
655
+ * live run of the WhatsApp suite refuted (#58): a wrong or revoked token reported success at
656
+ * startup and surfaced as messages that silently never arrived.
657
+ *
658
+ * There is still no session to open — HTTP push via webhook is the only inbound channel, and
659
+ * outbound is a stateless POST. What `connect()` buys is the startup answer to "can this
660
+ * credential act as this number?", which is the question every sibling adapter answers and this
661
+ * one did not. Outbound delegates to `WhatsAppCloudClient`. Inbound dispatch is driven by the
662
+ * user calling `handleWebhookPayload(rawBody, sig)` from inside their HTTP route.
596
663
  *
597
664
  * @public
598
665
  */
@@ -616,10 +683,48 @@ interface WhatsAppCloudBackendOptions {
616
683
  declare class WhatsAppCloudBackend implements WhatsAppBackend {
617
684
  readonly kind: "cloud";
618
685
  private readonly client;
686
+ /** Verified once by `connect()`; cleared by `disconnect()`. */
687
+ private connected;
688
+ /**
689
+ * The verification currently in flight, shared by every caller that arrives during it.
690
+ *
691
+ * A flag alone only guards callers that arrive AFTER one finished — two simultaneous
692
+ * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a
693
+ * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it
694
+ * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay
695
+ * distinguishable from a revoked token.
696
+ */
697
+ private connecting?;
698
+ /**
699
+ * Which connection attempt is current.
700
+ *
701
+ * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in
702
+ * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every
703
+ * later `connect()` would short-circuit on a flag no live check stands behind — the field's own
704
+ * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend
705
+ * carries, for the same reason.
706
+ */
707
+ private generation;
619
708
  private readonly appSecret;
620
709
  private inboundHandler?;
621
710
  private statusHandler?;
622
711
  constructor(opts: WhatsAppCloudBackendOptions);
712
+ /**
713
+ * Confirm with Meta that this credential can act as this phone number.
714
+ *
715
+ * This used to be `return true`. A consumer with a wrong, expired or revoked token got success
716
+ * at startup and found out from messages that silently never arrived — no error, no log,
717
+ * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the
718
+ * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.
719
+ *
720
+ * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would
721
+ * turn a supervisor's health check into a rate-limit source against Meta.
722
+ *
723
+ * Returns false rather than throwing — the contract each sibling adapter is tested against,
724
+ * because a throw at startup takes the whole runner down with it. The reason goes to stderr
725
+ * first: told only "false", a supervisor cannot tell a revoked token, which needs a human,
726
+ * from a rate limit, which needs a wait.
727
+ */
623
728
  connect(): Promise<boolean>;
624
729
  disconnect(): Promise<void>;
625
730
  send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
package/dist/index.d.ts CHANGED
@@ -52,30 +52,56 @@ interface WhatsAppStatusReceipt {
52
52
  /** Receipt timestamp. */
53
53
  readonly timestamp: number;
54
54
  }
55
+ /**
56
+ * What went wrong, in the vocabulary a caller can branch on.
57
+ *
58
+ * Extracted from `WhatsAppSendResult` rather than copied beside it: a credential check and a
59
+ * send fail for the same reasons, and two declarations of one vocabulary drift the moment
60
+ * somebody adds a code to one of them.
61
+ */
62
+ interface WhatsAppError {
63
+ readonly code: "auth_failed" | "rate_limit" | "invalid_request"
64
+ /**
65
+ * More than 24 hours since the recipient last replied. The payload was
66
+ * fine and the credential is fine; WhatsApp policy refuses free-form text
67
+ * outside that window. The remedy is specific and different from every
68
+ * other error here — resend as an approved template — which is why it is
69
+ * its own code rather than one more `invalid_request`.
70
+ */
71
+ | "session_window_expired"
72
+ /**
73
+ * The recipient was never registered against this phone number. The payload
74
+ * is fine and the credential is fine; the number simply may not message this
75
+ * person yet. Its own code because the remedy is a console step rather than
76
+ * anything in the request — and because every Cloud API app starts on a test
77
+ * number, it is the error most integrations meet first.
78
+ */
79
+ | "recipient_not_allowlisted"
80
+ /**
81
+ * `send()` was called without a successful `connect()`, or after `disconnect()`.
82
+ *
83
+ * Its own code because all three backends reach this state and used to describe it three
84
+ * different ways — `server_error` from web and Baileys, nothing at all from Cloud, which
85
+ * sent regardless. A caller cannot branch on prose, and a conformance test cannot assert on
86
+ * it either: one code is what makes "the implementations agree" a checkable claim rather
87
+ * than a hope.
88
+ */
89
+ | "not_connected"
90
+ /**
91
+ * The recipient cannot receive this message, and no retry changes that:
92
+ * no WhatsApp account, terms not accepted, an outdated client, or the
93
+ * business having blocked them. Terminal by nature; the cause is in the
94
+ * message.
95
+ */
96
+ | "undeliverable" | "server_error" | "timeout" | "unknown";
97
+ readonly message: string;
98
+ }
55
99
  /** Per-message send result returned by `WhatsAppBackend.send`. */
56
100
  interface WhatsAppSendResult {
57
101
  readonly ok: boolean;
58
102
  /** Set when ok=true. The wamid Meta / web assigned to the outbound message. */
59
103
  readonly wamid?: string;
60
- readonly error?: {
61
- readonly code: "auth_failed" | "rate_limit" | "invalid_request"
62
- /**
63
- * More than 24 hours since the recipient last replied. The payload was
64
- * fine and the credential is fine; WhatsApp policy refuses free-form text
65
- * outside that window. The remedy is specific and different from every
66
- * other error here — resend as an approved template — which is why it is
67
- * its own code rather than one more `invalid_request`.
68
- */
69
- | "session_window_expired"
70
- /**
71
- * The recipient cannot receive this message, and no retry changes that:
72
- * no WhatsApp account, terms not accepted, an outdated client, or the
73
- * business having blocked them. Terminal by nature; the cause is in the
74
- * message.
75
- */
76
- | "undeliverable" | "server_error" | "timeout" | "unknown";
77
- readonly message: string;
78
- };
104
+ readonly error?: WhatsAppError;
79
105
  }
80
106
  /**
81
107
  * Backend contract — every backend (cloud, web, future) implements this shape.
@@ -83,8 +109,43 @@ interface WhatsAppSendResult {
83
109
  */
84
110
  interface WhatsAppBackend {
85
111
  readonly kind: "cloud" | "web" | "baileys";
112
+ /**
113
+ * Make the backend usable, and report whether it is.
114
+ *
115
+ * Idempotent: a second call while connected returns `true` without repeating the work.
116
+ *
117
+ * **Operational failure returns `false`; misconfiguration throws.** A rejected credential, an
118
+ * unreachable server, a session that never opens — those are conditions a supervisor can retry
119
+ * or report, so they come back as `false` with the reason written where a human can read it. A
120
+ * missing peer dependency or an absent browser is not: no retry fixes it, and answering `false`
121
+ * would bury a setup error under a runtime one.
122
+ *
123
+ * The line was drawn after the conformance suite asserted the absolute version and two of three
124
+ * implementations "failed" it — correctly. They throw `ConfigurationError` and
125
+ * `WhatsAppBridgeError` for exactly the case that should not be swallowed.
126
+ */
86
127
  connect(): Promise<boolean>;
128
+ /** Release whatever `connect()` took. Idempotent, and safe on a backend that never connected. */
87
129
  disconnect(): Promise<void>;
130
+ /**
131
+ * Send one message.
132
+ *
133
+ * **Requires a successful `connect()` first, and refuses without one** — with
134
+ * `ok: false, error.code === "not_connected"`, never a throw, and without touching the
135
+ * transport. One code across every implementation, because a caller branches on the code and
136
+ * a conformance test can only assert on one.
137
+ *
138
+ * That sentence is here because its absence cost something. The interface used to declare bare
139
+ * signatures, each implementation answered the unasked question its own way, and they diverged:
140
+ * web and Baileys refused, Cloud posted regardless. A consumer swapping backends — the single
141
+ * thing this seam exists to allow — found unconnected sends leaving the process, which for
142
+ * Cloud meant a real request carrying a credential nothing had verified, or one `connect()`
143
+ * had already rejected.
144
+ *
145
+ * Enforced by `tests/backend-conformance.test.ts` against every implementation at once. A
146
+ * per-backend test proves one of them does something; only a shared one proves they agree, and
147
+ * the agreement is the product.
148
+ */
88
149
  send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
89
150
  /** Subscribe to normalized inbound events. Returns unsubscribe. */
90
151
  onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
@@ -589,10 +650,16 @@ interface MetaTemplateComponent {
589
650
  /**
590
651
  * `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).
591
652
  *
592
- * `connect()` / `disconnect()` are no-ops (HTTP push via webhook is the only
593
- * inbound channel). Outbound delegates to `WhatsAppCloudClient`. Inbound
594
- * dispatch is driven by the user calling `handleWebhookPayload(rawBody, sig)`
595
- * from inside their HTTP route.
653
+ * `connect()` verifies the credential against Meta and caches the result; `disconnect()` clears
654
+ * it. This header used to say both were no-ops, which is what the code did and what the first
655
+ * live run of the WhatsApp suite refuted (#58): a wrong or revoked token reported success at
656
+ * startup and surfaced as messages that silently never arrived.
657
+ *
658
+ * There is still no session to open — HTTP push via webhook is the only inbound channel, and
659
+ * outbound is a stateless POST. What `connect()` buys is the startup answer to "can this
660
+ * credential act as this number?", which is the question every sibling adapter answers and this
661
+ * one did not. Outbound delegates to `WhatsAppCloudClient`. Inbound dispatch is driven by the
662
+ * user calling `handleWebhookPayload(rawBody, sig)` from inside their HTTP route.
596
663
  *
597
664
  * @public
598
665
  */
@@ -616,10 +683,48 @@ interface WhatsAppCloudBackendOptions {
616
683
  declare class WhatsAppCloudBackend implements WhatsAppBackend {
617
684
  readonly kind: "cloud";
618
685
  private readonly client;
686
+ /** Verified once by `connect()`; cleared by `disconnect()`. */
687
+ private connected;
688
+ /**
689
+ * The verification currently in flight, shared by every caller that arrives during it.
690
+ *
691
+ * A flag alone only guards callers that arrive AFTER one finished — two simultaneous
692
+ * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a
693
+ * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it
694
+ * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay
695
+ * distinguishable from a revoked token.
696
+ */
697
+ private connecting?;
698
+ /**
699
+ * Which connection attempt is current.
700
+ *
701
+ * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in
702
+ * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every
703
+ * later `connect()` would short-circuit on a flag no live check stands behind — the field's own
704
+ * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend
705
+ * carries, for the same reason.
706
+ */
707
+ private generation;
619
708
  private readonly appSecret;
620
709
  private inboundHandler?;
621
710
  private statusHandler?;
622
711
  constructor(opts: WhatsAppCloudBackendOptions);
712
+ /**
713
+ * Confirm with Meta that this credential can act as this phone number.
714
+ *
715
+ * This used to be `return true`. A consumer with a wrong, expired or revoked token got success
716
+ * at startup and found out from messages that silently never arrived — no error, no log,
717
+ * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the
718
+ * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.
719
+ *
720
+ * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would
721
+ * turn a supervisor's health check into a rate-limit source against Meta.
722
+ *
723
+ * Returns false rather than throwing — the contract each sibling adapter is tested against,
724
+ * because a throw at startup takes the whole runner down with it. The reason goes to stderr
725
+ * first: told only "false", a supervisor cannot tell a revoked token, which needs a human,
726
+ * from a rate limit, which needs a wait.
727
+ */
623
728
  connect(): Promise<boolean>;
624
729
  disconnect(): Promise<void>;
625
730
  send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
package/dist/index.js CHANGED
@@ -146,10 +146,12 @@ var UNDELIVERABLE_CODES = /* @__PURE__ */ new Set([
146
146
  // no WhatsApp account, terms not accepted, or an outdated client
147
147
  ]);
148
148
  var SESSION_WINDOW_EXPIRED_CODE = 131047;
149
+ var RECIPIENT_NOT_ALLOWLISTED_CODE = 131030;
149
150
  function cloudErrorCode(status, errCode) {
150
151
  if (errCode === 190 || status === 401) return "auth_failed";
151
152
  if (RATE_LIMIT_CODES.has(errCode) || status === 429) return "rate_limit";
152
153
  if (errCode === SESSION_WINDOW_EXPIRED_CODE) return "session_window_expired";
154
+ if (errCode === RECIPIENT_NOT_ALLOWLISTED_CODE) return "recipient_not_allowlisted";
153
155
  if (UNDELIVERABLE_CODES.has(errCode)) return "undeliverable";
154
156
  if (status === 400 || errCode === 100) return "invalid_request";
155
157
  if (status >= 500) return "server_error";
@@ -162,6 +164,12 @@ function mapWhatsAppCloudError(status, body) {
162
164
  const code = cloudErrorCode(status, errCode);
163
165
  if (code === "auth_failed") return { code, message: `Bearer token rejected: ${errMsg}` };
164
166
  if (code === "rate_limit") return { code, message: `Throttled: ${errMsg}` };
167
+ if (code === "recipient_not_allowlisted") {
168
+ return {
169
+ code,
170
+ message: `Recipient is not on this number's allowed list \u2014 register it under the phone number in the app's WhatsApp API setup before sending: ${errMsg}`
171
+ };
172
+ }
165
173
  if (code === "session_window_expired") {
166
174
  return {
167
175
  code,
@@ -507,7 +515,7 @@ var WhatsAppBaileysBackend = class {
507
515
  return {
508
516
  result: Promise.resolve({
509
517
  ok: false,
510
- error: { code: "server_error", message: "Baileys backend is not connected." }
518
+ error: { code: "not_connected", message: "Baileys backend is not connected." }
511
519
  }),
512
520
  inFlight: Promise.resolve()
513
521
  };
@@ -635,6 +643,66 @@ var WhatsAppCloudClient = class {
635
643
  };
636
644
  return this.postMessage(req);
637
645
  }
646
+ /**
647
+ * Ask Meta whether this credential can actually act as this phone number.
648
+ *
649
+ * `connect()` used to answer that question with `return true`, so a wrong, expired or revoked
650
+ * token reported success at startup and surfaced as messages that silently never arrived —
651
+ * the worst failure mode a gateway has, because there is nothing in a log to see. The first
652
+ * live run of the WhatsApp suite caught it (#58); 209 unit tests could not, because a fake
653
+ * backend always accepts.
654
+ *
655
+ * It reads the phone number itself rather than `/me`, and that choice is the point: a token
656
+ * can be perfectly valid and still have no access to THIS phone number id, which is the
657
+ * likelier misconfiguration of the two. Checking only the token would wave it through.
658
+ *
659
+ * Returns a result rather than a boolean, and never throws — `connect()` is specified to
660
+ * return false rather than throw, and the reason has to survive the trip: `auth_failed` and
661
+ * `rate_limit` ask a supervisor for opposite responses.
662
+ */
663
+ async verifyCredentials() {
664
+ let response;
665
+ try {
666
+ response = await this.fetchImpl(this.baseUrl, {
667
+ method: "GET",
668
+ headers: { authorization: `Bearer ${this.opts.accessToken}` }
669
+ });
670
+ } catch (cause) {
671
+ return {
672
+ ok: false,
673
+ error: {
674
+ code: "server_error",
675
+ message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`
676
+ }
677
+ };
678
+ }
679
+ const body = await response.json().catch(() => void 0);
680
+ if (!response.ok) {
681
+ return { ok: false, error: mapWhatsAppCloudError(response.status, body ?? {}) };
682
+ }
683
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
684
+ return {
685
+ ok: false,
686
+ error: {
687
+ code: "unknown",
688
+ message: `Meta answered ${response.status} with a body this client could not read.`
689
+ }
690
+ };
691
+ }
692
+ if (body.error !== void 0) {
693
+ return { ok: false, error: mapWhatsAppCloudError(response.status, body) };
694
+ }
695
+ if (String(body.id) !== this.opts.phoneNumberId) {
696
+ return {
697
+ ok: false,
698
+ error: {
699
+ code: "invalid_request",
700
+ message: `Credential is valid but resolves to node ${String(body.id)}, not the configured phoneNumberId ${this.opts.phoneNumberId}. A WhatsApp Business Account id in place of a phone number id looks exactly like this.`
701
+ }
702
+ };
703
+ }
704
+ return { ok: true };
705
+ }
638
706
  /**
639
707
  * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.
640
708
  *
@@ -793,6 +861,28 @@ function metaStatusToReceipt(s) {
793
861
  var WhatsAppCloudBackend = class {
794
862
  kind = "cloud";
795
863
  client;
864
+ /** Verified once by `connect()`; cleared by `disconnect()`. */
865
+ connected = false;
866
+ /**
867
+ * The verification currently in flight, shared by every caller that arrives during it.
868
+ *
869
+ * A flag alone only guards callers that arrive AFTER one finished — two simultaneous
870
+ * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a
871
+ * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it
872
+ * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay
873
+ * distinguishable from a revoked token.
874
+ */
875
+ connecting;
876
+ /**
877
+ * Which connection attempt is current.
878
+ *
879
+ * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in
880
+ * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every
881
+ * later `connect()` would short-circuit on a flag no live check stands behind — the field's own
882
+ * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend
883
+ * carries, for the same reason.
884
+ */
885
+ generation = 0;
796
886
  appSecret;
797
887
  inboundHandler;
798
888
  statusHandler;
@@ -806,14 +896,64 @@ var WhatsAppCloudBackend = class {
806
896
  this.appSecret = opts.appSecret;
807
897
  }
808
898
  // Cloud has no persistent connection — webhook is push, send is HTTP.
899
+ /**
900
+ * Confirm with Meta that this credential can act as this phone number.
901
+ *
902
+ * This used to be `return true`. A consumer with a wrong, expired or revoked token got success
903
+ * at startup and found out from messages that silently never arrived — no error, no log,
904
+ * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the
905
+ * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.
906
+ *
907
+ * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would
908
+ * turn a supervisor's health check into a rate-limit source against Meta.
909
+ *
910
+ * Returns false rather than throwing — the contract each sibling adapter is tested against,
911
+ * because a throw at startup takes the whole runner down with it. The reason goes to stderr
912
+ * first: told only "false", a supervisor cannot tell a revoked token, which needs a human,
913
+ * from a rate limit, which needs a wait.
914
+ */
809
915
  async connect() {
916
+ if (this.connected) return true;
917
+ if (this.connecting !== void 0) return this.connecting;
918
+ const attempt = this.verifyOnce(++this.generation);
919
+ this.connecting = attempt;
920
+ try {
921
+ return await attempt;
922
+ } finally {
923
+ if (this.connecting === attempt) this.connecting = void 0;
924
+ }
925
+ }
926
+ /** One credential check, mapped to the boolean `connect()` is contracted to return. @internal */
927
+ async verifyOnce(generation) {
928
+ const check = await this.client.verifyCredentials();
929
+ if (!check.ok) {
930
+ process.stderr.write(
931
+ `[whatsapp-cloud] connect failed: ${check.error?.code ?? "unknown"} \u2014 ${check.error?.message ?? "no reason given"}
932
+ `
933
+ );
934
+ return false;
935
+ }
936
+ if (this.generation !== generation) return false;
937
+ this.connected = true;
810
938
  return true;
811
939
  }
812
940
  async disconnect() {
941
+ this.generation += 1;
942
+ this.connected = false;
943
+ this.connecting = void 0;
813
944
  this.inboundHandler = void 0;
814
945
  this.statusHandler = void 0;
815
946
  }
816
947
  async send(message) {
948
+ if (!this.connected) {
949
+ return {
950
+ ok: false,
951
+ error: {
952
+ code: "not_connected",
953
+ message: "Cloud backend is not connected \u2014 call connect()."
954
+ }
955
+ };
956
+ }
817
957
  return this.client.sendText(message.to, message.text, message.isGroup);
818
958
  }
819
959
  /**
@@ -832,6 +972,15 @@ var WhatsAppCloudBackend = class {
832
972
  * @param components Values for the template's variables; omit for a template that takes none.
833
973
  */
834
974
  async sendTemplate(to, templateName, languageCode, components) {
975
+ if (!this.connected) {
976
+ return {
977
+ ok: false,
978
+ error: {
979
+ code: "not_connected",
980
+ message: "Cloud backend is not connected \u2014 call connect()."
981
+ }
982
+ };
983
+ }
835
984
  return this.client.sendTemplate(to, templateName, languageCode, components);
836
985
  }
837
986
  onInbound(handler) {
@@ -1138,7 +1287,7 @@ var WhatsAppWebBackend = class {
1138
1287
  }
1139
1288
  async send(message) {
1140
1289
  if (!this.connected || this.handle === void 0 || this.handle.child.stdin === null) {
1141
- return { ok: false, error: { code: "server_error", message: "Bridge not connected." } };
1290
+ return { ok: false, error: { code: "not_connected", message: "Bridge not connected." } };
1142
1291
  }
1143
1292
  const msgId = `out-${++this.msgIdCounter}`;
1144
1293
  const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS2;