Skip to content
SMS SDK
Esc
↑↓navigate↵open⌘Jpreview
On this page

createSmsClient

createSmsClient(options): every SmsClientOptions field, its default, and the SmsClient methods it returns.

npm install @opencoredev/sms-sdk
pnpm add @opencoredev/sms-sdk
yarn add @opencoredev/sms-sdk
bun add @opencoredev/sms-sdk
nub add @opencoredev/sms-sdk
aube add @opencoredev/sms-sdk

createSmsClient(options)

Creates an SMS client over one or more adapters. It makes no network request.

import { createSmsClient, memoryIdempotencyStore } from "@opencoredev/sms-sdk";
import { telnyx } from "@opencoredev/sms-sdk/telnyx";
import { twilio } from "@opencoredev/sms-sdk/twilio";

const sms = createSmsClient({
  adapters: [
    twilio({ accountSid: process.env.TWILIO_ACCOUNT_SID ?? "", authToken: process.env.TWILIO_AUTH_TOKEN ?? "", from: "+15550100001" }),
    telnyx({ apiKey: process.env.TELNYX_API_KEY ?? "", from: "+15550100002" }),
  ],
  fallback: "on-known-rejection",
  retry: { maxAttempts: 2, baseDelayMs: 500, maxDelayMs: 10_000 },
  timeoutMs: 10_000,
  idempotency: { store: memoryIdempotencyStore(), ttlSec: 86_400, staleReservationSec: 300 },
  beforeSend: () => ({ kind: "allow" }),
  hooks: { onFailure: (event) => console.error(event.errorCode) },
});

Throws ConfigurationError when adapters is empty, two adapters share a name, or timeoutMs is not a positive number up to 2147483647.

Options

adapters

  • Type: readonly [SmsAdapter, ...SmsAdapter[]]
  • Required
  • Adapters in priority order. The first is the primary: it must support every field of a message, or send() throws UnsupportedFieldError. Names must be unique. See Providers.

fallback

  • Type: "none" | "on-known-rejection"
  • Optional
  • Defaults to "none"
  • With "none", only the primary adapter sends. With "on-known-rejection", a fallback-eligible rejection (auth, rate_limited, sender, account) moves to the next adapter that supports the message. An accepted or unknown outcome never falls back. See Fallback and retries.

retry

  • Type: { maxAttempts?: number; baseDelayMs?: number; maxDelayMs?: number }
  • Optional
  • Defaults to { maxAttempts: 2, baseDelayMs: 500, maxDelayMs: 10000 }
  • Retries on the same adapter, only after a rate_limited rejection. maxAttempts counts the first request, so 1 turns retries off. Backoff is exponential with full jitter. A provider Retry-After of at most maxDelayMs is used as the delay. A longer one stops retrying that adapter.
  • maxAttempts must be an integer from 1 to 10. baseDelayMs and maxDelayMs must be finite numbers from 0 to 2147483647; a maxDelayMs below baseDelayMs is raised to it. Anything else throws ConfigurationError.

timeoutMs

  • Type: number
  • Optional
  • Defaults to 10000
  • Timeout for each provider request. A timeout after the request starts throws HandoffUnknownError with reason: "timeout".

idempotency

  • Type: { store: IdempotencyStore; ttlSec?: number; staleReservationSec?: number }
  • Optional
  • Off by default
  • Enables idempotencyKey deduplication through store. ttlSec (default 86400) is how long accepted and rejected records are kept. After staleReservationSec (default 300), an unfinished reservation counts as an unknown outcome. Both must be whole numbers of seconds of at least 1, or createSmsClient throws ConfigurationError: a ttlSec of 0 would expire an accepted record as it is written and let the same key send twice. See Prevent duplicate sends and Idempotency store.

beforeSend

  • Type: (context: BeforeSendContext) => PolicyDecision | Promise<PolicyDecision>
  • Optional
  • Runs once per logical send, after local validation and the idempotency check, before any request. Return { kind: "allow" } or { kind: "reject", reason }. A rejection throws PolicyRejectedError and never falls back. If it throws, the error propagates, nothing is sent, and onFailure receives a policy_rejected event. For a suppression list, suppressionPolicy(list) builds this function; see STOP, HELP, and opt-outs. See Block and log sends.

hooks

  • Type: { onAttempt?, onAccepted?, onFailure? }
  • Optional
  • Redacted observability callbacks. Errors thrown by hooks are swallowed. See Block and log sends.

Returns: SmsClient

Method Returns Reference
send(input, options?) Promise<SmsSendResult> send()
validate(input) SmsValidationResult validate()
getMessage(providerId, options?) Promise<SmsMessageStatus | undefined> below
capabilities() readonly SmsAdapterInfo[] below

sms.getMessage(providerId, options?)

Asks one adapter for the provider’s current record of a message, by the provider’s message ID: SmsSendResult.providerId, or a webhook event’s providerId. It never sends. Use it to check delivery when a status webhook is late or lost.

import { sms } from "./sms";

const result = await sms.send({ to: "+14155550123", body: "Your code is 123456." });
const status = await sms.getMessage(result.providerId, { adapter: result.provider });
if (status === undefined) {
  console.log("the provider has no message with this ID yet");
} else {
  console.log(status.delivery, status.providerStatus, status.errorCode);
}
  • options.adapter: the adapter to ask, by name. Defaults to the primary adapter. Pass result.provider when fallback may have sent through another one.
  • options.signal: cancels the lookup. The client’s timeoutMs applies too.
  • Returns { provider, providerId, delivery, providerStatus?, errorCode? }, or undefined when the provider has no message with that ID. errorCode is set only when delivery is undelivered or filtered.
  • Throws MessageLookupError when the provider could not answer (network, timeout, 5xx, malformed response, or a 4xx such as bad credentials; see reason). It has retrySafe: false: a failed lookup says nothing about whether the message went out, so never resend because of one. Calling getMessage again is safe.
  • Throws ConfigurationError for an empty providerId, an adapter name that is not configured, or an adapter without getMessage.

Every built-in adapter implements it; the endpoint each one calls is on its provider page. A Vonage adapter with JWT auth needs reportsCredentials.

getMessage does not reconcile a HandoffUnknownError on its own: an unknown outcome has no provider ID to look up. See Reconcile an unknown outcome.

sms.capabilities()

Returns each configured adapter’s metadata, in order:

import { sms } from "./sms";

for (const adapter of sms.capabilities()) {
  console.log(adapter.name, adapter.support.status, adapter.capabilities.mms, adapter.defaultFrom);
}

Each entry is { name, capabilities: SmsCapabilities, support: AdapterSupport, defaultFrom: SmsFrom | undefined, messageLookup: boolean }. messageLookup is true when the adapter implements getMessage. See Adapter contract for the field types.

Types

type SmsClientOptions = {
  readonly adapters: readonly [SmsAdapter, ...SmsAdapter[]];
  readonly fallback?: "none" | "on-known-rejection";
  readonly retry?: RetryOptions;
  readonly timeoutMs?: number;
  readonly idempotency?: { readonly store: IdempotencyStore; readonly ttlSec?: number; readonly staleReservationSec?: number };
  readonly beforeSend?: (context: BeforeSendContext) => PolicyDecision | Promise<PolicyDecision>;
  readonly hooks?: SmsClientHooks;
};

type RetryOptions = { readonly maxAttempts?: number; readonly baseDelayMs?: number; readonly maxDelayMs?: number };

type BeforeSendContext = { readonly id: string; readonly message: SmsSendInput; readonly encoding: "gsm7" | "ucs2"; readonly segments: number };

type PolicyDecision = { readonly kind: "allow" } | { readonly kind: "reject"; readonly reason: string };

type SmsClientHooks = {
  readonly onAttempt?: (event: SmsAttemptEvent) => void | Promise<void>;
  readonly onAccepted?: (event: SmsAcceptedEvent) => void | Promise<void>;
  readonly onFailure?: (event: SmsFailureEvent) => void | Promise<void>;
};

type SmsHookEventBase = { readonly id: string; readonly to: string; readonly encoding: SmsEncoding; readonly segments: number; readonly idempotencyKey?: string };
type SmsAttemptEvent = SmsHookEventBase & { readonly attempt: SendAttempt };
type SmsAcceptedEvent = SmsHookEventBase & { readonly provider: string; readonly providerId: string; readonly attempts: readonly SendAttempt[] };
type SmsFailureEvent = SmsHookEventBase & { readonly errorCode: string; readonly retrySafe: boolean; readonly attempts: readonly SendAttempt[] };

type SmsAdapterInfo = {
  readonly name: string;
  readonly capabilities: SmsCapabilities;
  readonly support: AdapterSupport;
  readonly defaultFrom: SmsFrom | undefined;
  readonly messageLookup: boolean;
};

type SmsGetMessageOptions = { readonly adapter?: string; readonly signal?: AbortSignal };

type SmsMessageStatus = {
  readonly provider: string;
  readonly providerId: string;
  readonly delivery: Delivery;
  readonly providerStatus?: string;
  readonly errorCode?: string;
};

All of these are exported as types from @opencoredev/sms-sdk.

Last updated on