@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.
- package/CHANGELOG.md +65 -40
- package/README.md +361 -167
- package/dist/client.d.ts +37 -49
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +47 -58
- package/dist/client.js.map +1 -1
- package/dist/config.d.ts +6 -6
- package/dist/config.js +6 -6
- package/dist/generated/openapi.d.ts +910 -91
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/internal/sleep.d.ts +2 -2
- package/dist/internal/sleep.js +5 -5
- package/dist/internal/sleep.js.map +1 -1
- package/dist/resources/apps.d.ts +11 -18
- package/dist/resources/apps.d.ts.map +1 -1
- package/dist/resources/apps.js +11 -18
- package/dist/resources/apps.js.map +1 -1
- package/dist/resources/area-codes.d.ts +5 -6
- package/dist/resources/area-codes.d.ts.map +1 -1
- package/dist/resources/area-codes.js +5 -6
- package/dist/resources/area-codes.js.map +1 -1
- package/dist/resources/attachments.d.ts +51 -17
- package/dist/resources/attachments.d.ts.map +1 -1
- package/dist/resources/attachments.js +42 -22
- package/dist/resources/attachments.js.map +1 -1
- package/dist/resources/byod.d.ts +14 -4
- package/dist/resources/byod.d.ts.map +1 -1
- package/dist/resources/byod.js +14 -4
- package/dist/resources/byod.js.map +1 -1
- package/dist/resources/chats.d.ts +32 -22
- package/dist/resources/chats.d.ts.map +1 -1
- package/dist/resources/chats.js +31 -21
- package/dist/resources/chats.js.map +1 -1
- package/dist/resources/fleet.d.ts +23 -0
- package/dist/resources/fleet.d.ts.map +1 -0
- package/dist/resources/fleet.js +20 -0
- package/dist/resources/fleet.js.map +1 -0
- package/dist/resources/lines.d.ts +258 -268
- package/dist/resources/lines.d.ts.map +1 -1
- package/dist/resources/lines.js +251 -266
- package/dist/resources/lines.js.map +1 -1
- package/dist/resources/lookup.d.ts +10 -13
- package/dist/resources/lookup.d.ts.map +1 -1
- package/dist/resources/lookup.js +10 -13
- package/dist/resources/lookup.js.map +1 -1
- package/dist/resources/macos-sessions.d.ts +42 -36
- package/dist/resources/macos-sessions.d.ts.map +1 -1
- package/dist/resources/macos-sessions.js +24 -22
- package/dist/resources/macos-sessions.js.map +1 -1
- package/dist/resources/messages.d.ts +35 -25
- package/dist/resources/messages.d.ts.map +1 -1
- package/dist/resources/messages.js +30 -19
- package/dist/resources/messages.js.map +1 -1
- package/dist/resources/preorders.d.ts +42 -47
- package/dist/resources/preorders.d.ts.map +1 -1
- package/dist/resources/preorders.js +42 -47
- package/dist/resources/preorders.js.map +1 -1
- package/dist/resources/trial.d.ts +30 -21
- package/dist/resources/trial.d.ts.map +1 -1
- package/dist/resources/trial.js +30 -21
- package/dist/resources/trial.js.map +1 -1
- package/dist/resources/webhooks.d.ts +39 -22
- package/dist/resources/webhooks.d.ts.map +1 -1
- package/dist/resources/webhooks.js +39 -22
- package/dist/resources/webhooks.js.map +1 -1
- package/dist/retry.d.ts +9 -10
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +11 -12
- package/dist/retry.js.map +1 -1
- package/dist/types.d.ts +10 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +13 -37
- package/dist/version.js.map +1 -1
- package/dist/webhooks/parse.d.ts +10 -9
- package/dist/webhooks/parse.d.ts.map +1 -1
- package/dist/webhooks/parse.js +14 -13
- package/dist/webhooks/parse.js.map +1 -1
- package/dist/webhooks/types.d.ts +75 -111
- package/dist/webhooks/types.d.ts.map +1 -1
- package/dist/webhooks/types.js.map +1 -1
- package/dist/webhooks/verify.d.ts +27 -29
- package/dist/webhooks/verify.d.ts.map +1 -1
- package/dist/webhooks/verify.js +29 -35
- package/dist/webhooks/verify.js.map +1 -1
- package/examples/handle-webhook.ts +146 -0
- package/examples/paginate-messages.ts +54 -0
- package/examples/send-message.ts +37 -0
- package/examples/upload-attachment.ts +91 -0
- package/package.json +4 -8
package/README.md
CHANGED
|
@@ -1,281 +1,475 @@
|
|
|
1
1
|
# @isnap/sdk
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
|
|
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
|
-
|
|
13
|
+
`bun add`, `pnpm add` and `yarn add` work the same way. The package has no runtime dependency.
|
|
16
14
|
|
|
17
|
-
##
|
|
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:
|
|
26
|
-
to: '+
|
|
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
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
|
|
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 |
|
|
53
|
-
|
|
54
|
-
| `client.messages` |
|
|
55
|
-
| `client.chats` |
|
|
56
|
-
| `client.
|
|
57
|
-
| `client.lookup` |
|
|
58
|
-
| `client.
|
|
59
|
-
| `client.
|
|
60
|
-
| `client.
|
|
61
|
-
| `client.
|
|
62
|
-
| `client.
|
|
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
|
-
|
|
105
|
+
Three methods live on the client itself:
|
|
65
106
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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
|
-
|
|
111
|
+
## Retries
|
|
76
112
|
|
|
77
|
-
|
|
113
|
+
The SDK retries a call automatically, up to `maxRetries` times, in these cases:
|
|
78
114
|
|
|
79
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
90
|
-
|
|
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
|
-
|
|
93
|
-
|
|
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
|
-
|
|
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
|
|
101
|
-
|
|
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
|
-
|
|
146
|
+
`client.health()` is not retried unless the call passes `maxRetries`.
|
|
106
147
|
|
|
107
|
-
`
|
|
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
|
-
|
|
110
|
-
import { readFile } from 'node:fs/promises'
|
|
150
|
+
## Idempotency keys
|
|
111
151
|
|
|
112
|
-
|
|
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
|
-
|
|
115
|
-
filename: 'photo.jpg',
|
|
116
|
-
contentType: 'image/jpeg'
|
|
117
|
-
})
|
|
154
|
+
The API reads the key on eight methods only:
|
|
118
155
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
|
|
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
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
149
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
##
|
|
216
|
+
## Pagination
|
|
167
217
|
|
|
168
|
-
|
|
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
|
-
|
|
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
|
-
`
|
|
182
|
-
|
|
183
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
239
|
+
type MessagePage = { items: Message[]; has_more: boolean; next_cursor: string | null }
|
|
194
240
|
|
|
195
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
230
|
-
//
|
|
231
|
-
|
|
232
|
-
|
|
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
|
|
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
|
-
|
|
334
|
+
To report an error, write to [support@isnap.ai](mailto:support@isnap.ai) with its `traceId` and `requestId`.
|
|
244
335
|
|
|
245
|
-
|
|
336
|
+
## Webhooks
|
|
246
337
|
|
|
247
|
-
|
|
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
|
-
|
|
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
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
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
|
-
|
|
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
|
-
|
|
276
|
-
|
|
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
|