@phonekit/sdk
v0.2.0
Published
JavaScript and TypeScript API client for authorized Phonekit line, message and webhook workflows.
Downloads
86
Readme
@phonekit/sdk
A server-side JavaScript and TypeScript wrapper around the Phonekit HTTP API. Node.js 20.3+ and ESM are supported. The API owns authorization, allowances, asynchronous provisioning and durable webhook delivery. SDK waits repeat immediate reads locally; the caller controls deadlines, cancellation, matching and parallel work.
Install
npm install @phonekit/sdkKeep credentials in server or CI secrets, outside browser/mobile bundles and repositories. CommonJS consumers can use dynamic import("@phonekit/sdk").
Receive the intended fresh code
import { Phonekit, PhonekitError } from "@phonekit/sdk"
const apiKey = process.env["PHONEKIT_API_KEY"]
const reference = process.env["PHONEKIT_TEST_NUMBER"]
if (!apiKey || !reference) throw new Error("Set Phonekit runner credentials")
const phonekit = new Phonekit({ apiKey })
const number = phonekit.number(reference)
const after = await number.mark()
// Trigger the application's SMS request now.
try {
const receipt = await number.waitForOtpReceipt({
after,
timeoutMs: 120_000,
pollIntervalMs: 1000,
match: { sender: "Example", contentIncludes: "verification" },
})
// Submit receipt.code in memory and assert the application's final outcome.
// Persist receipt.cursor for continuation; never log the code or message body.
} catch (error) {
if (error instanceof PhonekitError) {
// error.kind distinguishes timeout, no_match, missing_otp, ambiguous,
// cancelled, authentication, scope, allowance and transport failures.
// error.cursor preserves progress on wait/extraction failures.
}
throw error
}Without filters, the first later receipt is returned. Explicit filters skip unrelated receipts; onUnmatched(receipt) lets the caller persist progress. waitForMessage() returns {message,cursor}. waitForOtpReceipt() adds code; waitForOtp() retains the string convenience. waitForLink() adds one expected link, optionally matching linkHostname. Multiple possible codes/links fail as ambiguous; absent extraction fails without silently consuming another matching message.
number.messagesAfter(after, {limit,signal}) performs one immediate ascending read and returns {data,cursor,hasMore}. An empty page leaves the cursor unchanged. No server wait sessions or concurrency entitlement is created. Normal API rate limits apply. A number handle has no mutable cursor; preserve the opaque PhonekitCursor intact. Separate overlapping flows need distinct numbers or deliberate coordination because a cursor identifies position, not a test.
timeoutMs (1–3,600,000) includes HTTP attempts, body reads, polling sleeps and retry delays. signal cancels one operation; the constructor's signal cancels all requests. Awaited onUnmatched callbacks are caller work. Matching cannot establish whether the target service will accept a code. Received SMS is untrusted data, never agent instructions.
Discover and manage authorized lines
const allowance = await phonekit.allowance()
const types = await phonekit.numberTypes()
const inventory = await phonekit.inventory({ areaCode: "415" })
// Select an actual supported inventory entry and persist a UUID before purchase.
const accepted = await phonekit.createNumber({
requestId: savedRequestId,
phoneNumber: selectedPhone,
label: "QA invitation",
sharing: "restricted",
memberIds: [],
grantReadAccess: true,
purpose: "Invitation acceptance",
})
const ready = await phonekit.waitUntilReady(accepted.operationId, {
timeoutMs: 120_000,
signal: controller.signal,
})
const acquired = phonekit.number(ready.id)
await acquired.configure({ purpose: "Sign-in regression" })
// When finished: await acquired.release()createNumber() requires numbers:manage. Use the same saved UUID and identical input for retries, including process restarts. Pending acquisitions reserve capacity atomically. Read grants require the explicit grantReadAccess choice and messages:read; management alone grants no message reads. waitUntilReady() locally polls the server-owned operation. operation() reads status once; recheck() promptly queues reconciliation without repurchasing. Provider-confirmed release returns capacity; retained messages keep their original expiry.
Starter ($29/month) includes 10 members, 3 Standard and 1 Mobile number; Team ($99) includes 25 members, 10 Standard and 5 Mobile; Scale ($199) includes 50 members, 20 Standard and 10 Mobile. All include these surfaces, webhooks and 30-day default retention, without seat fees. Additional Standard numbers cost $5/month and Mobile $15/month. Each included or added number contributes 50 SMS to its class-specific monthly workspace pool; SMS overages cost $0.02 Standard and $0.10 Mobile. subscription reports customer fees and SMS capacity, while the legacy cost fields are nullable provider procurement ceilings. sms reports the billing period, per-class usage and estimated overage. Mobile capacity is reported as mobileNumbers. The API currently provisions US local Standard numbers (us_local_sms). No number type guarantees that a given service will accept it.
Other API wrappers
members(): minimal eligible workspace identities for assignment/sharing undernumbers:manage.describe(),numbers(),number().get(): identity, scopes, authorized metadata and readiness.number().messages({limit,before}),latest(),phonekit.message(id): retained/exact messages, including webhook IDs.webhooks(),webhook(id),createWebhook({url,numberIds}),updateWebhook(),deleteWebhook(): explicitly selected subscriptions withwebhooks:manage. Creation returns its signing secret once and is not automatically retried.deliveries({cursor,limit}),delivery(id): sanitized attempts withdiagnostics:read;retryDelivery(id)requires webhook management and is not automatically retried.
PhonekitClient exposes the same operations for CLI and lower-level callers. Its waitForMessage() polls immediate reads locally and returns null at the caller's deadline; number().waitForMessage() adds matching and typed timeout/progress errors. There is no credential-administration API. Create management credentials deliberately in the web app; existing read-only keys never gain management permissions.
Errors and validation
PhonekitError exposes kind, applicable HTTP status, stable domain code, requestId, retryAfterSeconds, and wait progress cursor. It excludes response bodies, codes, keys and abort reasons. Branch on typed fields rather than parsing human text. Safe/idempotent operations retry transient network, 429 and 5xx failures up to three attempts with backoff and Retry-After, within the deadline. Permanent failures are not retried.
The SDK and OpenAPI specification use backend-owned wire schemas. SDK parsing validates responses without introducing a second authorization or provisioning implementation. Guides and complete examples are at phonekit.io/docs/sdk.
