@isnap/sdk 2.3.0 → 2.3.1-next.43615425532.1

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.
Files changed (94) hide show
  1. package/CHANGELOG.md +65 -40
  2. package/README.md +361 -167
  3. package/dist/client.d.ts +37 -49
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/client.js +47 -58
  6. package/dist/client.js.map +1 -1
  7. package/dist/config.d.ts +6 -6
  8. package/dist/config.js +6 -6
  9. package/dist/generated/openapi.d.ts +910 -91
  10. package/dist/index.d.ts +3 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/internal/sleep.d.ts +2 -2
  15. package/dist/internal/sleep.js +5 -5
  16. package/dist/internal/sleep.js.map +1 -1
  17. package/dist/resources/apps.d.ts +11 -18
  18. package/dist/resources/apps.d.ts.map +1 -1
  19. package/dist/resources/apps.js +11 -18
  20. package/dist/resources/apps.js.map +1 -1
  21. package/dist/resources/area-codes.d.ts +5 -6
  22. package/dist/resources/area-codes.d.ts.map +1 -1
  23. package/dist/resources/area-codes.js +5 -6
  24. package/dist/resources/area-codes.js.map +1 -1
  25. package/dist/resources/attachments.d.ts +51 -17
  26. package/dist/resources/attachments.d.ts.map +1 -1
  27. package/dist/resources/attachments.js +42 -22
  28. package/dist/resources/attachments.js.map +1 -1
  29. package/dist/resources/byod.d.ts +14 -4
  30. package/dist/resources/byod.d.ts.map +1 -1
  31. package/dist/resources/byod.js +14 -4
  32. package/dist/resources/byod.js.map +1 -1
  33. package/dist/resources/chats.d.ts +32 -22
  34. package/dist/resources/chats.d.ts.map +1 -1
  35. package/dist/resources/chats.js +31 -21
  36. package/dist/resources/chats.js.map +1 -1
  37. package/dist/resources/fleet.d.ts +23 -0
  38. package/dist/resources/fleet.d.ts.map +1 -0
  39. package/dist/resources/fleet.js +20 -0
  40. package/dist/resources/fleet.js.map +1 -0
  41. package/dist/resources/lines.d.ts +258 -268
  42. package/dist/resources/lines.d.ts.map +1 -1
  43. package/dist/resources/lines.js +251 -266
  44. package/dist/resources/lines.js.map +1 -1
  45. package/dist/resources/lookup.d.ts +10 -13
  46. package/dist/resources/lookup.d.ts.map +1 -1
  47. package/dist/resources/lookup.js +10 -13
  48. package/dist/resources/lookup.js.map +1 -1
  49. package/dist/resources/macos-sessions.d.ts +42 -36
  50. package/dist/resources/macos-sessions.d.ts.map +1 -1
  51. package/dist/resources/macos-sessions.js +24 -22
  52. package/dist/resources/macos-sessions.js.map +1 -1
  53. package/dist/resources/messages.d.ts +35 -25
  54. package/dist/resources/messages.d.ts.map +1 -1
  55. package/dist/resources/messages.js +30 -19
  56. package/dist/resources/messages.js.map +1 -1
  57. package/dist/resources/preorders.d.ts +42 -47
  58. package/dist/resources/preorders.d.ts.map +1 -1
  59. package/dist/resources/preorders.js +42 -47
  60. package/dist/resources/preorders.js.map +1 -1
  61. package/dist/resources/trial.d.ts +30 -21
  62. package/dist/resources/trial.d.ts.map +1 -1
  63. package/dist/resources/trial.js +30 -21
  64. package/dist/resources/trial.js.map +1 -1
  65. package/dist/resources/webhooks.d.ts +39 -22
  66. package/dist/resources/webhooks.d.ts.map +1 -1
  67. package/dist/resources/webhooks.js +39 -22
  68. package/dist/resources/webhooks.js.map +1 -1
  69. package/dist/retry.d.ts +9 -10
  70. package/dist/retry.d.ts.map +1 -1
  71. package/dist/retry.js +11 -12
  72. package/dist/retry.js.map +1 -1
  73. package/dist/types.d.ts +10 -0
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/version.d.ts +1 -1
  76. package/dist/version.d.ts.map +1 -1
  77. package/dist/version.js +13 -37
  78. package/dist/version.js.map +1 -1
  79. package/dist/webhooks/parse.d.ts +10 -9
  80. package/dist/webhooks/parse.d.ts.map +1 -1
  81. package/dist/webhooks/parse.js +14 -13
  82. package/dist/webhooks/parse.js.map +1 -1
  83. package/dist/webhooks/types.d.ts +75 -111
  84. package/dist/webhooks/types.d.ts.map +1 -1
  85. package/dist/webhooks/types.js.map +1 -1
  86. package/dist/webhooks/verify.d.ts +27 -29
  87. package/dist/webhooks/verify.d.ts.map +1 -1
  88. package/dist/webhooks/verify.js +29 -35
  89. package/dist/webhooks/verify.js.map +1 -1
  90. package/examples/handle-webhook.ts +146 -0
  91. package/examples/paginate-messages.ts +54 -0
  92. package/examples/send-message.ts +37 -0
  93. package/examples/upload-attachment.ts +91 -0
  94. package/package.json +4 -8
package/README.md CHANGED
@@ -1,281 +1,475 @@
1
1
  # @isnap/sdk
2
2
 
3
- Official TypeScript SDK for the [iSnap](https://isnap.ai) P2P telephony API — real iMessage / SMS / RCS lines from real handsets, exposed as a single typed client.
3
+ TypeScript SDK for the iSnap API. iSnap sends and receives iMessage, RCS and SMS from real devices. The SDK wraps the `/v1` operations in typed methods, retries failed calls, iterates over paginated lists, uploads attachments and verifies webhook deliveries.
4
4
 
5
- > Pre-1.0. Targets contract `docs/api-contract.md` v1.0.0. Public surface is stable across the v0.x line; breaking changes will bump 0.x → 0.(x+1) until 1.0.0.
5
+ The full documentation is at [docs.isnap.ai](https://docs.isnap.ai). For help, write to [support@isnap.ai](mailto:support@isnap.ai).
6
6
 
7
7
  ## Install
8
8
 
9
9
  ```bash
10
- bun add @isnap/sdk
11
- # or
12
10
  npm install @isnap/sdk
13
11
  ```
14
12
 
15
- Requires Node 20+ (or Bun 1.2+). The SDK uses native `fetch`, `node:crypto`, and ES2022 `Error.cause` — no polyfills.
13
+ `bun add`, `pnpm add` and `yarn add` work the same way. The package has no runtime dependency.
16
14
 
17
- ## Quick start
15
+ ## Requirements
16
+
17
+ - **Runtime.** Node.js 20 or later, or Bun 1.2 or later.
18
+ - **Module format.** The package is ESM only, with one entry point and named exports. In Node.js, `require('@isnap/sdk')` fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`: from CommonJS code, load the package with `await import('@isnap/sdk')`.
19
+ - **Server side.** The SDK does not build for a browser. An API key is a secret: keep it on your server.
20
+ - **TypeScript.** Type declarations are bundled. They use web platform types such as `HeadersInit` and `Blob`, so your `tsconfig.json` needs `"DOM"` in `lib` (for example `"lib": ["ES2022", "DOM"]`), or `"skipLibCheck": true`. Set `moduleResolution` to `bundler`, `node16` or `nodenext`.
21
+
22
+ The SDK reads no environment variable. The key and every setting come from the options you pass.
23
+
24
+ ## First call
18
25
 
19
26
  ```ts
20
27
  import { ISnapClient } from '@isnap/sdk'
21
28
 
22
29
  const client = new ISnapClient({ apiKey: process.env.ISNAP_API_KEY! })
30
+ const lineId = 'line_8Xk2mQ4vTn7Bw9Rz3Lc6Yp1Hd'
23
31
 
24
32
  const message = await client.messages.send({
25
- line_id: 'line_01HX...',
26
- to: '+15551234567',
33
+ line_id: lineId,
34
+ to: '+14155550123',
27
35
  body: 'Hello from iSnap'
28
36
  })
29
37
 
30
38
  console.log(message.id, message.status)
31
39
  ```
32
40
 
41
+ This call sends a real message. An `isnap_test_` account key is not a separate test environment: it acts on the same account, lines and billing as an `isnap_live_` key. A trial key also starts with `isnap_test_`, and it acts only on its trial.
42
+
43
+ `message.status` is `queued` when the message leaves now and `scheduled` when iSnap holds it.
44
+
45
+ A successful call resolves with the `data` of the response. The HTTP status and the response headers are not available on success.
46
+
47
+ Request and response types are generated from the OpenAPI document of the API, and their fields are the snake_case fields of the API: the SDK converts no name. TypeScript rejects an unknown field in an object literal. In plain JavaScript an unknown field is sent as is: most operations drop it without an error, and `preOrders.create`, `preOrders.update`, `trial.init`, `trial.revoke`, `trial.update`, `macosSessions.rent`, `macosSessions.update`, `byod.pair` and `lines.updateConfig` refuse it with `400 validation_failed`.
48
+
33
49
  ## Configuration
34
50
 
35
51
  ```ts
36
- new ISnapClient({
37
- apiKey: 'sk_live_...', // required
38
- baseUrl: 'https://api.isnap.ai', // default
39
- maxRetries: 3, // default 3 — retries on 429/5xx with jittered backoff
40
- maxRetryDelayMs: 60_000, // ceiling on a honored Retry-After; a longer 429 is rethrown instead of slept
41
- timeoutMs: 30_000, // per-attempt timeout
42
- idempotencyKey: 'auto', // 'auto' generates UUIDs for POST/PATCH/PUT/DELETE; 'manual' = pass via opts
43
- fetch: undefined, // override (e.g. an instrumented fetch)
44
- onRetry: (info) => console.warn('retry', info)
52
+ import { ISnapClient } from '@isnap/sdk'
53
+
54
+ const client = new ISnapClient({
55
+ apiKey: process.env.ISNAP_API_KEY!,
56
+ timeoutMs: 10_000,
57
+ maxRetries: 2,
58
+ onRetry: ({ attempt, nextDelayMs }) => console.warn(`retry after attempt ${attempt} in ${nextDelayMs} ms`)
45
59
  })
46
60
  ```
47
61
 
48
- Every resource method accepts an optional `RequestOptions` final argument: `{ signal, idempotencyKey, headers, query, maxRetries }`.
62
+ | Option | Default | Meaning |
63
+ | --- | --- | --- |
64
+ | `apiKey` | required | Your API key, a non-empty string. Leading and trailing whitespace is removed. The SDK does not check its format. |
65
+ | `baseUrl` | `https://api.isnap.ai` | The address of the API. |
66
+ | `timeoutMs` | `30000` | Time allowed for each attempt, in milliseconds. It is not a limit on the whole call. |
67
+ | `maxRetries` | `3` | Number of automatic retries after the first attempt: up to 4 attempts. `0` turns automatic retries off. |
68
+ | `maxRetryDelayMs` | `60000` | Longest wait the SDK accepts before one retry, in milliseconds. |
69
+ | `idempotencyKey` | `'auto'` | `'auto'` or `'manual'`. See [Idempotency keys](#idempotency-keys). |
70
+ | `fetch` | the global `fetch` | The HTTP implementation. |
71
+ | `onRetry` | none | Called before each automatic retry with `{ attempt, nextDelayMs, error }`. `attempt` is the zero-based index of the attempt that failed. It is also called once when your `signal` cancels an attempt that is not the last one, although no retry follows. |
72
+
73
+ The constructor makes no network call. It throws a plain `Error` when `apiKey` is missing or empty, and when a number is out of range.
74
+
75
+ A client holds one credential and sends it on every request, including the operations that need none. To call with a trial key, create a second client with that key.
76
+
77
+ Every method takes a last optional argument:
78
+
79
+ | Per-call option | Meaning |
80
+ | --- | --- |
81
+ | `idempotencyKey` | The idempotency key of this call. |
82
+ | `signal` | An `AbortSignal` that cancels the call. |
83
+ | `maxRetries` | Replaces the client's `maxRetries` for this call. |
84
+ | `headers` | Extra headers. They can replace `User-Agent`, `Accept` and `Content-Type`. They cannot replace `Authorization`, nor the `Idempotency-Key` the SDK sets. |
85
+ | `query` | Extra query parameters. The four list iterators ignore it: only their filters argument is sent. |
49
86
 
50
87
  ## Resources
51
88
 
52
- | Resource | What it does |
53
- |---|---|
54
- | `client.messages` | Send / get / cancel / list messages, add reactions |
55
- | `client.chats` | List / get conversations (incl. shared-line `outbound_number`), mark read, send typing indicators, share a contact card |
56
- | `client.lines` | List, configure, and inspect rented + BYOD lines, plus quota and queue snapshots; mint wholesale shared lines and flip a line to/from test |
57
- | `client.lookup` | Test if a number is iMessage-capable before sending |
58
- | `client.attachments` | Upload images / video / files (transparent 3-step flow) |
59
- | `client.webhooks` | CRUD subscriptions, rotate secrets, list deliveries, replay events |
60
- | `client.byod` | Pair a customer-owned Mac+iPhone or Android device |
61
- | `client.trial` | Start, check, and convert trial sessions |
62
- | `client.version` / `client.health` | Read the backend API version and system health — global probes on the client itself, distinct from the per-line `client.lines.health(id)` |
89
+ | Resource | Methods |
90
+ | --- | --- |
91
+ | `client.messages` | `send`, `get`, `list`, `cancel`, `addReaction`, `removeReaction` |
92
+ | `client.chats` | `list`, `get`, `typingStart`, `typingStop`, `markRead`, `shareContactCard` |
93
+ | `client.attachments` | `create`, `get`, and the [`upload` helper](#attachments-helper) |
94
+ | `client.lookup` | `check`: whether a handle can receive iMessage |
95
+ | `client.lines` | `list`, `listMine`, `get`, `reserve`, `activate`, `release`, `assign`, `mintShared`, `patch`, `terminate`, `cancel`, `uncancel`, `setAnniversary`, `setVariant`, `cancelVariantChange`, `convertToTest`, `convertFromTest`, `transferOwnership`, `getConfig`, `updateConfig`, `quota`, `queue`, `health`, `healthReport`, `createInvite` |
96
+ | `client.preOrders` | `create`, `confirm`, `list`, `get`, `update`, `cancel` |
97
+ | `client.areaCodes` | `list`: the area codes a pre-order can request |
98
+ | `client.byod` | `pair`: an activation code for the bridge app on your own Mac and iPhone |
99
+ | `client.apps` | `manifest`: the download links of the bridge app |
100
+ | `client.fleet` | `health`: the public two-way rate report of the fleet |
101
+ | `client.macosSessions` | `rent`, `get`, `update`, `cancel`, `uncancel` |
102
+ | `client.trial` | `init`, `status`, `activity`, `revoke`, `get`, `update` |
103
+ | `client.webhooks` | `create`, `list`, `get`, `update`, `delete`, `rotateSecret`, `deliveries`, `replay`, `events` |
63
104
 
64
- ## Sending a message
105
+ Three methods live on the client itself:
65
106
 
66
- ```ts
67
- const msg = await client.messages.send({
68
- line_id: 'line_01HX...',
69
- to: '+15551234567',
70
- body: 'Order #1242 is on its way',
71
- service: 'iMessage' // optional — falls back to SMS/RCS via the line's degradation chain
72
- })
73
- ```
107
+ - `client.version()` returns the version of the API the client talks to.
108
+ - `client.health()` returns the health of the API as a whole, `{ status, timestamp, checks }`. It resolves on a `200` and on a `503`: `status` is `ok` or `degraded`. `client.lines.health(id)` is a different method: the health of one BYOD line.
109
+ - `client.request(method, path, body?, opts?)` calls any path with the same authentication, retries, idempotency key and error handling as the typed methods. Use it for an operation that has no method, such as `GET /v1/attention`.
74
110
 
75
- `messages.send` is **idempotent by default** — the SDK auto-generates an `Idempotency-Key` for every POST. Retrying the same call with the same key returns the original message without sending a duplicate.
111
+ ## Retries
76
112
 
77
- ## Listing with cursor pagination
113
+ The SDK retries a call automatically, up to `maxRetries` times, in these cases:
78
114
 
79
- `list()` returns an `AsyncIterable` that threads cursors automatically:
115
+ - The connection fails, or an attempt times out.
116
+ - The API returns `500` or `503`.
117
+ - The API returns a `429` that is a `RateLimitError`. A `429` that is a `QuotaExceededError` is never retried: see [Errors](#errors).
118
+ - A response with a status of 500 or more is not JSON.
80
119
 
81
- ```ts
82
- for await (const msg of client.messages.list({ line_id: 'line_01HX...', limit: 100 })) {
83
- console.log(msg.id, msg.created_at)
84
- }
85
- ```
120
+ It does not retry any other `4xx`, nor a JSON error with another `5xx` status such as `502` or `504`.
86
121
 
87
- To stop early, pass an `AbortSignal`. Aborting surfaces as a thrown `APIConnectionError` on the next page boundary, so wrap the loop:
122
+ Retries apply to every method, `POST`, `PATCH` and `DELETE` included. Read [Idempotency keys](#idempotency-keys) before you rely on them for a method that writes. One write method is the exception: `lines.createInvite` makes no automatic retry unless the call passes `maxRetries`. It issues a new invite on every call, a retry after a lost response would issue a second one, and a `503 line_pool_exhausted` does not clear within the wait of a retry. The key of the call is sent and ignored. To retry it, pass `maxRetries` on the call, for example `client.lines.createInvite(lineId, { exclude }, { maxRetries: 1 })`.
88
123
 
89
- ```ts
90
- import { APIConnectionError } from '@isnap/sdk'
124
+ One read cannot be repeated either. `trial.status` returns the trial key once, and only during the 60 minutes that follow the pairing, while the trial is `active`: a retry after a lost response gets no key, and neither does a first call made later. Call it with `maxRetries: 0`, from a client whose `timeoutMs` leaves time for the answer. If a call returns an `active` or `dormant` trial without `trial_api_key` and you do not hold the key, the key is lost: revoke the trial and start another.
125
+
126
+ **Waits.** When the API states no delay, the wait before retry 1, 2 and 3 is 250 ms, 500 ms and 1,000 ms, each plus 0 to 100 ms, capped at `maxRetryDelayMs`. On a `429` that carries `error.retry_after`, the SDK waits exactly that many seconds. It reads the delay from the response body, not from the `Retry-After` header. When that delay is longer than `maxRetryDelayMs`, the SDK does not wait: it throws the `RateLimitError` immediately, with `retryAfter` set, and `onRetry` is not called.
91
127
 
92
- const ac = new AbortController()
93
- setTimeout(() => ac.abort(), 5_000)
128
+ **Duration of a call.** `timeoutMs` applies to each attempt. With the defaults, a call to a server that never responds lasts more than 2 minutes: 4 attempts of 30 seconds, plus the waits.
129
+
130
+ **The request-rate limits.** The API accepts 100 requests per rolling 60 seconds, counted per account with an API key, and per network address with a trial key. `messages.send` and `messages.list` (`POST` and `GET /v1/messages`) also share a second limit of 60 requests per rolling 60 seconds, counted the same way, on top of the first. An account can have different limits. Over a limit the API returns `429 rate_limit_exceeded` with `retry_after: 60`. 60 seconds is not longer than the default `maxRetryDelayMs`, so the SDK waits 60 seconds and retries, up to 3 times: a call can last more than 3 minutes before it throws `RateLimitError`. To fail fast, pass `maxRetries: 0` on the call, or set `maxRetryDelayMs` below `60000`.
131
+
132
+ ```ts
133
+ import { RateLimitError } from '@isnap/sdk'
94
134
 
95
135
  try {
96
- for await (const msg of client.messages.list({}, { signal: ac.signal })) {
97
- // ...
98
- }
136
+ await client.messages.send(
137
+ { line_id: lineId, to: '+14155550123', body: 'Hello' },
138
+ { maxRetries: 0 }
139
+ )
99
140
  } catch (err) {
100
- if (!(err instanceof APIConnectionError)) throw err
101
- // expected — signal aborted the iterator
141
+ if (!(err instanceof RateLimitError)) throw err
142
+ console.warn(`refused: ${err.code}, retry in ${err.retryAfter} seconds`)
102
143
  }
103
144
  ```
104
145
 
105
- ## Uploading an attachment
146
+ `client.health()` is not retried unless the call passes `maxRetries`.
106
147
 
107
- `attachments.upload()` wraps the 3-step contract (register → presigned PUT → poll) into one call:
148
+ **Cancel a call.** Pass an `AbortSignal` as `signal`. Cancellation stops the current attempt and any wait, and the call rejects with `APIConnectionError`, whose `cause` is the reason of the signal. The error message does not tell a cancellation from a timeout: test `signal.aborted` on your signal.
108
149
 
109
- ```ts
110
- import { readFile } from 'node:fs/promises'
150
+ ## Idempotency keys
111
151
 
112
- const file = await readFile('./photo.jpg')
152
+ With `idempotencyKey: 'auto'`, the SDK adds an `Idempotency-Key` header, a random UUID, to every `POST`, `PATCH`, `PUT` and `DELETE` call. The key is generated once per method call and reused on the automatic retries of that call. Two separate method calls get two different keys.
113
153
 
114
- const attachment = await client.attachments.upload(file, {
115
- filename: 'photo.jpg',
116
- contentType: 'image/jpeg'
117
- })
154
+ The API reads the key on eight methods only:
118
155
 
119
- await client.messages.send({
120
- line_id: 'line_01HX...',
121
- to: '+15551234567',
122
- body: 'Here you go',
123
- attachment_ids: [attachment.id]
124
- })
125
- ```
156
+ | Method | Operation |
157
+ | --- | --- |
158
+ | `messages.send` | `POST /v1/messages` |
159
+ | `messages.addReaction` | `POST /v1/messages/{id}/reactions` |
160
+ | `messages.removeReaction` | `DELETE /v1/messages/{id}/reactions` |
161
+ | `chats.shareContactCard` | `POST /v1/chats/{chat_id}/share-contact-card` |
162
+ | `attachments.create` | `POST /v1/attachments` |
163
+ | `lines.assign` | `POST /v1/lines/assign` |
164
+ | `lines.mintShared` | `POST /v1/lines/shared` |
165
+ | `macosSessions.rent` | `POST /v1/macos-sessions/rent` |
126
166
 
127
- 5 GB cap. Four documented failure modes — note that the R2 PUT and the server-side `failed` transition share the same `upload_failed` code:
167
+ On these methods, a repeat with the same key and the same body does not act again, except in three cases:
128
168
 
129
- | Failure | `code` |
130
- |---|---|
131
- | `size_bytes` exceeds the 5 GB cap | `attachment_exceeds_storage_limit` |
132
- | R2 presigned PUT returns non-2xx | `upload_failed` |
133
- | Server transitions to `status: failed` | `upload_failed` |
134
- | Polling exhausted before `status: ready` | `upload_timeout` |
169
+ - **`chats.shareContactCard`.** Once a call has queued the card, a repeat with the same key returns `409 idempotency_conflict` instead of the first result. The automatic retries of the SDK reuse the key, so call this method with `maxRetries: 0`. After an error, read the messages of the chat's line before you send the card again.
170
+ - **`attachments.create`.** While the upload has not started, and within 15 minutes of the last call, a repeat with the same key returns the same attachment with a new upload URL, whatever the body. Once the upload has started, or those 15 minutes have passed, the same key gets `409 idempotency_terminal_state`, with no time limit.
171
+ - **`lines.assign` with `as_test_line`.** When the call fails after the line was assigned, the key is released, and a repeat with the same key assigns a second line. Call it with `maxRetries: 0`, or read your lines with `lines.listMine()` before you retry.
135
172
 
136
- ## Verifying webhooks
173
+ A key reused with a different body is a `ConflictError`, except on `attachments.create`. Its code is `idempotency_key_collision` on `lines.assign`, `lines.mintShared` and `macosSessions.rent`, and `idempotency_conflict` on `messages.send`, the two reaction methods and `chats.shareContactCard`. On these four methods the key belongs to the line: the same key used on another line is a separate call.
137
174
 
138
- ```ts
139
- import { verifyWebhook, isMessageEvent } from '@isnap/sdk'
175
+ Keep a key at 255 characters or fewer, and send the retries of one call one after the other, not in parallel.
140
176
 
141
- // Express / Hono / native handler — give us the RAW body bytes (string).
142
- async function handle(rawBody: string, headers: Record<string, string>) {
143
- const event = verifyWebhook(rawBody, headers, process.env.ISNAP_WEBHOOK_SECRET!)
177
+ The API remembers a key for 24 hours on `lines.assign`, `lines.mintShared` and `macosSessions.rent`. On `messages.send` and `chats.shareContactCard` it remembers a key for as long as it keeps the message, at least 72 hours. After that, a repeat with the same key acts again. On the two reaction methods a key does not outlive the message reacted to. On `attachments.create` the API does not forget a key.
144
178
 
145
- // Dedupe by event_id — delivery is at-least-once.
146
- if (await alreadyProcessed(event.event_id)) return
179
+ To retry a write yourself, use one of these methods outside the three cases above, while the API remembers the key, and pass the key of the first attempt:
147
180
 
148
- if (isMessageEvent(event)) {
149
- console.log(event.event_type, event.data.message.id)
150
- }
181
+ ```ts
182
+ import { APIConnectionError } from '@isnap/sdk'
183
+
184
+ const body = { line_id: lineId, to: '+14155550123', body: 'Your order has shipped' }
185
+ const idempotencyKey = crypto.randomUUID()
186
+
187
+ try {
188
+ await client.messages.send(body, { idempotencyKey })
189
+ } catch (err) {
190
+ if (!(err instanceof APIConnectionError)) throw err
191
+ // No response arrived. Same body, same key: when the first attempt created
192
+ // the message, the API returns that message and sends nothing more.
193
+ await client.messages.send(body, { idempotencyKey })
151
194
  }
152
195
  ```
153
196
 
154
- During a `rotate-secret` grace window pass both secrets:
197
+ On every other method the header is sent and ignored. An automatic retry after a lost response can then run the operation twice. This concerns `webhooks.create`, `webhooks.rotateSecret`, `webhooks.replay`, `trial.init`, `byod.pair`, `preOrders.create`, `lines.createInvite` (not retried by default) and every other method that writes. Pass `maxRetries: 0` where a second execution is not acceptable.
198
+
199
+ The same retry can also report an operation that succeeded as an error. A repeated `messages.cancel` gets `409 too_late_to_cancel`, `lines.release` gets `404 not_found`, `lines.cancelVariantChange` gets `404 no_pending_variant_change`, and `preOrders.cancel` gets `400 pre_order_already_confirmed`. When one of these methods throws, read the resource to learn whether the operation took place.
200
+
201
+ With `idempotencyKey: 'manual'`, the SDK sends a key only when the call passes one. Automatic retries stay on, so a call that writes without a key can run twice.
202
+
203
+ ## Invites
204
+
205
+ `lines.createInvite(lineId, body?, opts?)` picks a phone number for one visitor of an inbound-first line and issues the code the visitor's text must carry. It resolves with a `LineInvite`: `{ id, line_id, phone_number, code, created_at }`, where `phone_number` is in E.164. Show the number only together with its code: a text without the code does not reach the line. The code is valid only on that number, never expires and can be used more than once. `body.exclude` lists up to 50 numbers, in E.164, that the pick must avoid.
155
206
 
156
207
  ```ts
157
- verifyWebhook(rawBody, headers, [newSecret, oldSecret])
208
+ const invite = await client.lines.createInvite(lineId, { exclude: ['+14155550101'] })
209
+ console.log(`Text ${invite.code} to ${invite.phone_number}`)
158
210
  ```
159
211
 
160
- Throws `WebhookSignatureError` on missing headers, expired timestamp (5min tolerance), or signature mismatch.
161
-
162
- If verification happens behind a trusted gateway, use `parseWebhookEvent(rawBody)` to skip HMAC and just type the envelope.
212
+ Every call issues a new invite, and the API ignores the idempotency key on this operation. For that reason the SDK makes **no automatic retry** on this method by default, unlike the other writes: it behaves as if `maxRetries` were `0`, whatever the client's `maxRetries` is. A retry after a lost response would issue a second invite, and a `503 line_pool_exhausted` does not clear within the wait of a retry. Pass `maxRetries` on the call to retry it, as the last argument: `client.lines.createInvite(lineId, {}, { maxRetries: 1 })`.
163
213
 
164
- One guard per event family, each narrowing `event.data` and matching on the wire prefix: `isMessageEvent`, `isReactionEvent`, `isLineEvent`, `isTypingIndicatorEvent`, `isTrialEvent`, `isPreOrderEvent`, `isBindingEvent` (`binding.*`), `isMacosSessionEvent` (`macos_session.*`) and `isAdminEvent` (`webhook.*`, the `webhook.test` probe). They prefix-match, so a future event in a known family still narrows without an SDK upgrade. The matching `*EventType` aliases (`MessageEventType`, …) enumerate today's catalog for exhaustive `switch` statements and are kept in lockstep with the backend by a compile-time parity check. A full worked handler lives in [`examples/handle-webhook.ts`](./examples/handle-webhook.ts).
214
+ Refusals: `ServiceUnavailableError` (`503`, with the code `line_pool_exhausted`, `quota_state_unavailable` or `invite_code_unavailable`), `ConflictError` (`409 not_inbound_first_line` or `line_not_active`), `NotFoundError` for a line of another account, and `PermissionDeniedError` (`403`) when a line-scoped key does not cover the line, or when inbound-first lines are not enabled on the account (`inbound_pool_not_enabled`).
165
215
 
166
- ## System probes
216
+ ## Pagination
167
217
 
168
- Two probes live on the client itself, not on a resource:
218
+ Four methods return an `AsyncIterable`: `messages.list`, `chats.list`, `webhooks.deliveries` and `webhooks.events`. A `for await` loop receives the items one by one, and the SDK fetches the next page when the current one is consumed. No request is made before the loop starts.
169
219
 
170
220
  ```ts
171
- const { version } = await client.version() // GET /v1/version — backend API version string
172
-
173
- const health = await client.health() // GET /v1/health — { status, checks }
174
- if (health.status !== 'ok') {
175
- // A degraded backend answers 503 with a body; health() resolves it as data
176
- // rather than throwing, so you branch on health.status without a try/catch.
177
- console.warn('iSnap degraded:', health.checks)
221
+ for await (const message of client.messages.list({ line_id: lineId, limit: 100 })) {
222
+ console.log(message.id, message.created_at, message.status)
178
223
  }
179
224
  ```
180
225
 
181
- `client.health()` is the **global** backend probe. It is deliberately named apart from `client.lines.health(lineId)`, which reports one line's health — calling the wrong one returns a plausible answer about the wrong object, so reach for `client.health()` only when you mean the whole backend.
182
-
183
- ## Wholesale + test lines
226
+ - `limit` is the page size, sent on every page request. The SDK sets no default. The API defaults are 25 for messages, 20 for chats, 20 for deliveries and 100 for events, and the maximum is 100.
227
+ - Each page is one request, made in sequence. It counts toward the request-rate limit, and a page of `messages.list` also counts toward the limit of 60 on `/v1/messages`. There is no total count.
228
+ - `messages.list` yields the newest message first unless `sort` or `order` says otherwise.
229
+ - `webhooks.events` requires `since`.
230
+ - `break` stops the iteration: no further page is fetched.
231
+ - An aborted `signal` rejects the loop with `APIConnectionError`.
232
+ - An error on a page request is thrown from the loop, after the retries of that request. The SDK does not resume.
184
233
 
185
- Wholesale partners mint their own billable shared lines and can set a rental line aside as a test line for their own customers' trials:
234
+ **What cannot be resumed.** The iterators expose neither the cursor nor the page boundaries, and they take no `cursor`: an interrupted iteration cannot be resumed through them. To page by hand, call the operation with `client.request` and keep `next_cursor` yourself:
186
235
 
187
236
  ```ts
188
- const line = await client.lines.mintShared() // POST /v1/lines/shared — a NEW billable line every call
189
- await client.lines.convertToTest(rentalLineId) // set a rental line aside as a test line
190
- await client.lines.convertFromTest(rentalLineId) // turn it back into a rental line
191
- ```
237
+ import type { Message } from '@isnap/sdk'
192
238
 
193
- `mintShared()` is wholesale-partner only in v1: a direct (non-wholesale) customer is rejected with `PaymentRequiredError` (402) and a scoped API key with `PermissionDeniedError` (403). Each call mints a distinct line — the SDK's auto `Idempotency-Key` only dedupes that one call's internal retries, so a caller-level retry must reuse the same `opts.idempotencyKey` to avoid minting twice.
239
+ type MessagePage = { items: Message[]; has_more: boolean; next_cursor: string | null }
194
240
 
195
- A test line is **billed like a rental line**: it stays on your end-of-month invoice as the outbound product, on the same billing dates, so `convertToTest()` then `convertFromTest()` leaves your bill unchanged. Its `monthly_price` reads that price. `convertToTest()` refuses an inbound line (move it to outbound first) and a line with a pending cancellation (uncancel it first); end a test line with `client.lines.terminate(id)`.
241
+ let cursor: string | undefined
242
+ do {
243
+ const page = await client.request<MessagePage>('GET', '/v1/messages', undefined, {
244
+ query: { line_id: lineId, limit: 100, cursor }
245
+ })
246
+ for (const message of page.items) console.log(message.id)
247
+ cursor = page.has_more && page.next_cursor ? page.next_cursor : undefined
248
+ } while (cursor)
249
+ ```
250
+
251
+ The other list methods are not iterators:
196
252
 
197
- `convertToTest()` and `convertFromTest()` are wholesale-partner only too, like `lines.assign()`: a direct account is rejected with `PaymentRequiredError` (402 `checkout_required`), and runs its trials on the global pool with `client.trial.init()`.
253
+ | Method | Resolves with |
254
+ | --- | --- |
255
+ | `preOrders.list()` | One page, `{ items, has_more, next_cursor }`. Pass `next_cursor` back as `cursor` for the next page. |
256
+ | `lines.list()` | One page, `{ lines, total, page, limit }`, selected with `page` and `limit`. |
257
+ | `lines.listMine()` | `{ lines }`: the whole set in one response. |
258
+ | `webhooks.list()` | `{ webhooks }`: the whole set in one response. |
198
259
 
199
260
  ## Errors
200
261
 
201
- All API errors extend `APIError` and carry `status`, `code`, `message`, `traceId`, `requestId`. Subclasses match the §6 contract codes:
262
+ The SDK throws three families of errors. All extend `Error`.
263
+
264
+ | Class | When | Extends `APIError` |
265
+ | --- | --- | --- |
266
+ | `APIError` and its 12 subclasses | The API, or the SDK, refused or failed a call. | yes |
267
+ | `APIConnectionError` | There is no usable response: network failure, timeout or abort. The original error is in `cause`. It has no `status` and no `code`. | no |
268
+ | `WebhookSignatureError` | The verification of a webhook delivery failed. | no |
269
+
270
+ The subclass of an `APIError` follows the `error.status` of the response body:
271
+
272
+ | Status | Class |
273
+ | --- | --- |
274
+ | `400` | `BadRequestError` |
275
+ | `401` | `AuthenticationError` |
276
+ | `402` | `PaymentRequiredError` |
277
+ | `403` | `PermissionDeniedError` |
278
+ | `404` | `NotFoundError` |
279
+ | `409` | `ConflictError` |
280
+ | `410` | `GoneError` |
281
+ | `413`, `422` | `UnprocessableEntityError` |
282
+ | `429` | `RateLimitError` or `QuotaExceededError` |
283
+ | `500` | `InternalServerError` |
284
+ | `503` | `ServiceUnavailableError` |
285
+ | any other | `APIError` |
286
+
287
+ The class only tells the status. Branch on `err.code` for the exact cause.
288
+
289
+ Every `APIError` carries these properties:
290
+
291
+ | Property | Content |
292
+ | --- | --- |
293
+ | `status` | The status of the error. |
294
+ | `code` | The error code, such as `validation_failed` or `rate_limit_exceeded`. |
295
+ | `message` | The error message. |
296
+ | `traceId`, `requestId` | The identifiers of the response, read from its body or from its `X-Trace-Id` and `X-Request-Id` headers. An error the SDK raises on a response carries them too. They are empty strings when the response has none, and on the `attachment_exceeds_storage_limit`, `upload_failed` and `upload_timeout` errors of the attachments helper. |
297
+ | `retryAfter` | A number of seconds, on a `429` that states a delay. On any other error from the API it is `null`, and on an error the SDK raises itself it is `undefined`: test it with `typeof err.retryAfter === 'number'`. |
298
+ | `issues` | An array of `{ path, message, code }` when the error names a field: on a `400 validation_failed`, and on the other refusals that name one, such as `400 webhook_url_not_allowed` and `422 limit_out_of_bounds` (whose entry also carries `min` and `max`). On any other error from the API it is `null`, and on an error the SDK raises itself it is `undefined`. At run time `path` is an array of strings and numbers, although the type declares a string. |
299
+
300
+ **The two classes of a `429`.** A `429` becomes a `QuotaExceededError` when its code is `new_contact_quota_exceeded`, `known_contact_quota_exceeded`, `total_message_quota_exceeded`, `queue_full` or `lookup_rate_limit_exceeded`. Any other `429` becomes a `RateLimitError`: `rate_limit_exceeded`, `minute_limit_exceeded`, `hourly_limit_exceeded` and `rebind_cap_reached` are among them. Neither class extends the other: catch both.
301
+
302
+ **Codes of the SDK.** The SDK raises `APIError` with five codes that the API never sends:
303
+
304
+ | Code | When |
305
+ | --- | --- |
306
+ | `invalid_response` | The response is not JSON. The message holds the first 200 characters of the body. The class is `ServiceUnavailableError` when the status is 500 or more. |
307
+ | `unknown_error` | A JSON response signals a failure without an `error` object. |
308
+ | `response_too_large` | The `Content-Length` of the response exceeds 10,485,760 bytes. |
309
+ | `upload_failed`, `upload_timeout` | Raised by the [attachments helper](#attachments-helper). |
202
310
 
203
311
  ```ts
204
- import {
205
- APIError,
206
- APIConnectionError,
207
- AuthenticationError,
208
- BadRequestError,
209
- ConflictError,
210
- GoneError,
211
- InternalServerError,
212
- NotFoundError,
213
- PaymentRequiredError,
214
- PermissionDeniedError,
215
- QuotaExceededError,
216
- RateLimitError,
217
- ServiceUnavailableError,
218
- UnprocessableEntityError,
219
- WebhookSignatureError
220
- } from '@isnap/sdk'
312
+ import { APIConnectionError, APIError, QuotaExceededError, RateLimitError } from '@isnap/sdk'
221
313
 
222
314
  try {
223
- await client.messages.send({
224
- line_id: 'line_01HX...',
225
- to: '+15551234567',
226
- body: 'hello'
227
- })
315
+ await client.messages.send({ line_id: lineId, to: '+14155550123', body: 'Hello' })
228
316
  } catch (err) {
229
- if (err instanceof RateLimitError) {
230
- // retry-after handled automatically by the retry loop, but visible here too
231
- } else if (err instanceof QuotaExceededError) {
232
- // pause sending until next quota window
317
+ if (err instanceof QuotaExceededError) {
318
+ // A sending limit of the line is reached, or its queue is full. Never retried.
319
+ console.error(err.code, err.retryAfter)
320
+ } else if (err instanceof RateLimitError) {
321
+ // Retried by the SDK already, unless the delay exceeded maxRetryDelayMs.
322
+ console.error(err.code, err.retryAfter)
233
323
  } else if (err instanceof APIError) {
234
- console.error(err.status, err.code, err.traceId)
324
+ console.error(err.status, err.code, err.traceId, err.requestId)
235
325
  } else if (err instanceof APIConnectionError) {
236
- // network issue / timeout — already retried per `maxRetries`
326
+ // No response: network failure, timeout or abort.
327
+ console.error(err.message)
237
328
  } else {
238
329
  throw err
239
330
  }
240
331
  }
241
332
  ```
242
333
 
243
- Retries: 429 + 5xx are retried automatically with jittered exponential backoff up to `maxRetries`. The retry budget is per-call.
334
+ To report an error, write to [support@isnap.ai](mailto:support@isnap.ai) with its `traceId` and `requestId`.
244
335
 
245
- A server-sent `retry_after` is honored, but only up to `maxRetryDelayMs` (default 60s). A 429 asking for longer is **not** slept through — the `RateLimitError` is thrown straight to you, with `err.retryAfter` (seconds) intact, so you can schedule the wait yourself instead of parking the promise. The concrete case is the trial rebind cap: revoking with `reason: 'rebind'` past the per-owner limit answers with `retry_after ≈ 86400` (24h), which the SDK surfaces immediately rather than hanging for a day. `onRetry` does not fire for these — nothing is being retried. If you genuinely want the SDK to sleep that long, raise the ceiling to a large finite value (`maxRetryDelayMs: 86_400_000`); `Infinity` is rejected.
336
+ ## Webhooks
246
337
 
247
- ## Examples
338
+ `verifyWebhook(rawBody, headers, secret, { tolerance })` checks the signature and the timestamp of a delivery, then returns the parsed event. It is synchronous, and it throws `WebhookSignatureError` on any failure. Deliveries are signed according to Standard Webhooks.
248
339
 
249
- Runnable scripts in [`examples/`](https://github.com/WhatSnap/iSnap-App/tree/main/packages/sdk/examples) (browse on GitHub — they live in the repo, not the published tarball):
340
+ ```ts
341
+ import { isMessageEvent, verifyWebhook, WebhookSignatureError } from '@isnap/sdk'
342
+
343
+ // rawBody: the request body exactly as received, as a string.
344
+ // headers: the request headers, as a Headers object or a plain object.
345
+ function handleDelivery(rawBody: string, headers: Headers): number {
346
+ let event
347
+ try {
348
+ event = verifyWebhook(rawBody, headers, process.env.ISNAP_WEBHOOK_SECRET!, { tolerance: 300 })
349
+ } catch (err) {
350
+ if (err instanceof WebhookSignatureError) return 400
351
+ throw err
352
+ }
250
353
 
251
- - `send-message.ts` — minimal send
252
- - `paginate-messages.ts` — async iterator + abort
253
- - `upload-attachment.ts` — file upload + send with attachment
254
- - `handle-webhook.ts` — `node:http` server that verifies and dispatches events
354
+ if (isMessageEvent(event)) {
355
+ console.log(event.event_id, event.event_type, event.data.message.id)
356
+ }
357
+ return 200
358
+ }
359
+ ```
255
360
 
256
- Run them against a local backend:
361
+ | Argument | Content |
362
+ | --- | --- |
363
+ | `rawBody` | The request body exactly as received, as a string. A body that was parsed and serialized again fails verification. Convert a `Buffer` with `.toString('utf8')`. |
364
+ | `headers` | The request headers: a `Headers` object or a plain object, such as the `req.headers` of Node.js. The function reads the three Standard Webhooks headers, `webhook-id`, `webhook-timestamp` and `webhook-signature`. Header names are case-insensitive. |
365
+ | `secret` | The signing secret exactly as the API returned it: `whsec_` followed by 64 hexadecimal characters. It can be an array: the delivery is accepted when any entry matches. |
366
+ | `tolerance` | The largest accepted difference, in seconds, between `webhook-timestamp` and your clock, earlier or later. The default is 300. `0` requires the same second: it does not turn the check off. |
257
367
 
258
- ```bash
259
- ISNAP_API_KEY=sk_test_... bun run examples/send-message.ts
260
- ```
368
+ After the signature passes, the body must be a JSON object with a non-empty string `api_version`, `event_id`, `event_type` and `created_at`, and an object `data`. Otherwise `verifyWebhook` throws the same `WebhookSignatureError`.
261
369
 
262
- ## Development
370
+ **Type guards.** `verifyWebhook` returns a `WebhookEventBase`: `event_type` is a `string` and `data` is untyped. Narrow the event with one of the nine type guards, one per event family. Each matches on the prefix of `event_type`:
263
371
 
264
- ```bash
265
- bun install
266
- bun run --filter '@isnap/sdk' test
267
- bun run --filter '@isnap/sdk' typecheck
268
- bun run --filter '@isnap/sdk' lint
269
- bun run --filter '@isnap/sdk' build
372
+ | Guard | Prefix | Type of `data` |
373
+ | --- | --- | --- |
374
+ | `isMessageEvent` | `message.` | `data.message` is a `Message` |
375
+ | `isReactionEvent` | `reaction.` | `ReactionEventData`, a union on `direction` |
376
+ | `isLineEvent` | `line.` | `Record<string, unknown>` |
377
+ | `isTypingIndicatorEvent` | `typing_indicator.` | `Record<string, unknown>` |
378
+ | `isTrialEvent` | `trial.` | `Record<string, unknown>` |
379
+ | `isPreOrderEvent` | `pre_order.` | `Record<string, unknown>` |
380
+ | `isBindingEvent` | `binding.` | `Record<string, unknown>` |
381
+ | `isMacosSessionEvent` | `macos_session.` | `Record<string, unknown>` |
382
+ | `isAdminEvent` | `webhook.` | `Record<string, unknown>` |
383
+
384
+ Every `data` also carries `metadata` and `line_metadata`. A new event type in a known family matches its guard without an SDK upgrade. An event type the SDK does not know is returned and matches no guard: ignore event types you do not know.
385
+
386
+ **Duplicates.** `verifyWebhook` does not deduplicate. A retry or a replay carries the same `event_id`. Deduplicate on `event_id`, and record an `event_id` only once its work has succeeded, so that a retry of a delivery you failed to process runs the work again.
387
+
388
+ **Secret rotation.** After `webhooks.rotateSecret`, every delivery, retries included, is signed with the new secret only. Passing `[newSecret, oldSecret]` matters only for a request that was signed before the rotation and is still in transit.
389
+
390
+ `parseWebhookEvent(rawBody)` applies the same checks to the body without verifying a signature.
391
+
392
+ ## Attachments helper
393
+
394
+ `attachments.upload(file, { filename, contentType }, opts?)` registers the attachment, uploads the bytes to the URL the API returns, then reads the attachment until its `status` is `ready`, and resolves with it.
395
+
396
+ ```ts
397
+ import { readFile } from 'node:fs/promises'
398
+
399
+ const file = await readFile('./photo.jpg')
400
+
401
+ const attachment = await client.attachments.upload(
402
+ file,
403
+ { filename: 'photo.jpg', contentType: 'image/jpeg' },
404
+ { pollIntervalMs: 2_000, maxPolls: 60 }
405
+ )
406
+
407
+ await client.messages.send({
408
+ line_id: lineId,
409
+ to: '+14155550123',
410
+ body: 'Here is the photo',
411
+ attachments: [attachment.id]
412
+ })
270
413
  ```
271
414
 
272
- To regenerate types from the backend's frozen OpenAPI spec:
415
+ - `file` is a `Blob`, an `ArrayBuffer` or a `Uint8Array`. A Node.js `Buffer` qualifies. Streams and file paths are not accepted: the whole file is in memory.
416
+ - The upload request is sent once: it is not retried. It shares the `timeoutMs` of the client, so a large file needs a larger `timeoutMs`.
417
+ - The helper reads the attachment every `pollIntervalMs` (default 500), at most `maxPolls` times (default 60): 30 seconds plus request time.
418
+ - iSnap confirms a finished upload on a 30-second cycle, and it converts an audio file before the attachment is ready. The default budget can therefore run out on an upload that succeeds.
419
+ - Each read is one request, and it counts toward the request-rate limit with your other calls. At the default interval the helper reads up to 120 times per minute, so a larger `maxPolls` alone can exceed the limit. To wait longer, raise `pollIntervalMs` to between 2,000 and 5,000 ms: `{ pollIntervalMs: 2_000, maxPolls: 60 }` waits 2 minutes plus request time, with at most 30 reads per minute.
420
+ - Each `upload()` call registers a new attachment, unless it passes an `idempotencyKey` that an earlier call used.
421
+ - To send the file, pass the attachment id in the `attachments` array of `messages.send`.
422
+
423
+ | Failure | Thrown | `status` | `code` |
424
+ | --- | --- | --- | --- |
425
+ | `file` is none of the three types | `TypeError` | none | none |
426
+ | The file is larger than 5 GB (5,368,709,120 bytes). Raised before any request. | `APIError` | `413` | `attachment_exceeds_storage_limit` |
427
+ | The upload request fails or times out | `APIConnectionError` | none | none |
428
+ | The upload request is refused | `APIError` | the status of that response | `upload_failed` |
429
+ | The `status` of the attachment becomes `failed` | `APIError` | `422` | `upload_failed` |
430
+ | The attachment is not `ready` after `maxPolls` reads | `APIError` | `504` | `upload_timeout` |
431
+
432
+ A timeout does not cancel the attachment. On `upload_timeout`, and on `upload_failed` when the `status` of the attachment became `failed`, the attachment id is only in the error message. When the upload request is refused, the error carries no id. To keep the id, call `attachments.create`, upload the bytes yourself, and read `attachments.get` until `status` is `ready`.
433
+
434
+ ## Versions
435
+
436
+ The package follows Semantic Versioning, and its version is independent of the API version. The SDK sends no API version.
437
+
438
+ - `SDK_VERSION` is the version of the package. The SDK sends it as `User-Agent: @isnap/sdk/<version>`.
439
+ - `client.version()` returns the version of the API the client talks to.
440
+ - `MIN_API_VERSION` is informational: the SDK does not check it.
441
+
442
+ When a response carries a `Deprecation` header, the SDK logs one `console.warn` per method, path and `Sunset` value for the life of the process. The SDK writes nothing else to the console.
443
+
444
+ ## Personal data
445
+
446
+ The SDK stores nothing. It passes phone numbers, handles, message bodies and metadata through as given. `trial.status(token)` puts the pairing code of the trial in the request URL. The message of an `invalid_response` error can contain the first 200 characters of a response body. Do not copy handles, message bodies or error messages that contain them into logs, tickets or other tools.
447
+
448
+ ## Examples
449
+
450
+ The package ships four scripts in its `examples` directory:
451
+
452
+ | File | What it does |
453
+ | --- | --- |
454
+ | `examples/send-message.ts` | Sends one message. |
455
+ | `examples/paginate-messages.ts` | Reads the messages of a line with the iterator and an `AbortSignal`. |
456
+ | `examples/upload-attachment.ts` | Uploads a file and sends it as an attachment. |
457
+ | `examples/handle-webhook.ts` | Runs a `node:http` server that verifies deliveries, deduplicates on `event_id` and branches on the event family. |
458
+
459
+ They import `@isnap/sdk` like your own code. Copy one into your project and run it, for example with Bun:
273
460
 
274
461
  ```bash
275
- bun run --filter '@isnap/backend' dump-openapi # writes packages/backend/openapi.json
276
- bun run --filter '@isnap/sdk' generate # regenerates src/generated/openapi.d.ts
462
+ cp node_modules/@isnap/sdk/examples/send-message.ts .
463
+ ISNAP_API_KEY=isnap_live_... ISNAP_LINE_ID=line_... ISNAP_TO=+14155550123 bun run send-message.ts
277
464
  ```
278
465
 
466
+ The first three scripts call `https://api.isnap.ai` with your key. `send-message.ts` and `upload-attachment.ts` send a real message.
467
+
468
+ ## Help
469
+
470
+ - Documentation: [docs.isnap.ai](https://docs.isnap.ai)
471
+ - Help and defect reports: [support@isnap.ai](mailto:support@isnap.ai)
472
+
279
473
  ## License
280
474
 
281
475
  MIT