@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
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Receive iSnap webhook deliveries: verify each one, deduplicate on
3
+ * `event_id`, and branch on the event family.
4
+ *
5
+ * The server uses `node:http` and no other dependency. `verifyWebhook` needs
6
+ * the request body exactly as received, as a string: read it before any JSON
7
+ * parser does.
8
+ *
9
+ * Copy this file into your project, then run it:
10
+ *
11
+ * ISNAP_WEBHOOK_SECRET=whsec_... bun run handle-webhook.ts
12
+ *
13
+ * It listens on the port given in `PORT` (default 3001), at the path
14
+ * `/webhooks/isnap`.
15
+ */
16
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
17
+ import {
18
+ isAdminEvent,
19
+ isBindingEvent,
20
+ isLineEvent,
21
+ isMacosSessionEvent,
22
+ isMessageEvent,
23
+ isPreOrderEvent,
24
+ isReactionEvent,
25
+ isTrialEvent,
26
+ isTypingIndicatorEvent,
27
+ verifyWebhook,
28
+ WebhookSignatureError,
29
+ type WebhookEventBase
30
+ } from '@isnap/sdk'
31
+
32
+ const secret = required('ISNAP_WEBHOOK_SECRET')
33
+ const port = Number(process.env.PORT ?? 3001)
34
+
35
+ // Replace this with a persistent store. A retry or a replay carries the same
36
+ // `event_id`, and this in-memory set is lost when the process restarts.
37
+ const seen = new Set<string>()
38
+
39
+ const server = createServer(async (req, res) => {
40
+ if (req.method !== 'POST' || req.url !== '/webhooks/isnap') {
41
+ return reply(res, 404, { error: 'not_found' })
42
+ }
43
+
44
+ const rawBody = await readBody(req)
45
+
46
+ let event
47
+ try {
48
+ event = verifyWebhook(rawBody, req.headers, secret)
49
+ } catch (err) {
50
+ if (err instanceof WebhookSignatureError) {
51
+ return reply(res, 400, { error: 'invalid_signature', message: err.message })
52
+ }
53
+ throw err
54
+ }
55
+
56
+ if (seen.has(event.event_id)) {
57
+ return reply(res, 200, { ok: true, deduped: true })
58
+ }
59
+
60
+ try {
61
+ processEvent(event)
62
+ } catch {
63
+ // The event is not recorded as seen, so the retry of this delivery runs
64
+ // the work again.
65
+ console.error('processing failed', event.event_type, event.event_id)
66
+ return reply(res, 500, { error: 'processing_failed' })
67
+ }
68
+ // Record the event only once its work has succeeded.
69
+ seen.add(event.event_id)
70
+
71
+ // Return a 2xx within 10 seconds. Any other outcome is a failed attempt,
72
+ // which iSnap retries up to six times. A `410` is not retried: it turns the
73
+ // subscription off (`active: false`).
74
+ reply(res, 200, { ok: true })
75
+ })
76
+
77
+ server.listen(port, () => {
78
+ console.log(`Listening for iSnap webhooks on http://localhost:${port}/webhooks/isnap`)
79
+ })
80
+
81
+ // Replace the logs with your work. Throw when the work fails.
82
+ function processEvent(event: WebhookEventBase): void {
83
+ // Handles and phone numbers in `data` are personal data: this example logs
84
+ // ids and types only.
85
+ if (isMessageEvent(event)) {
86
+ console.log('message', event.event_type, event.data.message.id)
87
+ } else if (isReactionEvent(event)) {
88
+ // `data` is a union on `direction`: an inbound reaction names the contact
89
+ // who reacted (`from_handle`), an outbound one names the line's own handle
90
+ // (`actor_handle`). Narrow on `direction` before you read the handle.
91
+ const who = event.data.direction === 'inbound' ? 'a contact' : 'the line'
92
+ console.log(
93
+ 'reaction',
94
+ event.event_type,
95
+ event.data.reaction_id,
96
+ event.data.reaction_type,
97
+ `by ${who}`
98
+ )
99
+ } else if (isLineEvent(event)) {
100
+ console.log('line', event.event_type, event.event_id)
101
+ } else if (isTypingIndicatorEvent(event)) {
102
+ console.log('typing', event.event_type, event.event_id)
103
+ } else if (isTrialEvent(event)) {
104
+ console.log('trial', event.event_type, event.event_id)
105
+ } else if (isPreOrderEvent(event)) {
106
+ console.log('pre_order', event.event_type, event.event_id)
107
+ } else if (isBindingEvent(event)) {
108
+ // The pairing between a shared line and one contact ended.
109
+ console.log('binding', event.event_type, event.data.reason)
110
+ } else if (isMacosSessionEvent(event)) {
111
+ // A hosted macOS session was assigned to the account, or its rental
112
+ // ended. `data` has no `line_id`.
113
+ console.log('macos_session', event.event_type, event.data.macos_session_id, event.data.reason)
114
+ } else if (isAdminEvent(event)) {
115
+ // `webhook.test`: the probe sent to a suspended webhook subscription.
116
+ // There is nothing to process. The 2xx of the handler resumes the
117
+ // subscription.
118
+ console.log('probe', event.event_type)
119
+ } else {
120
+ console.log('unknown event_type, ignored', event.event_type)
121
+ }
122
+ }
123
+
124
+ function readBody(req: IncomingMessage): Promise<string> {
125
+ return new Promise((resolve, reject) => {
126
+ const chunks: Buffer[] = []
127
+ req.on('data', (chunk: Buffer) => chunks.push(chunk))
128
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
129
+ req.on('error', reject)
130
+ })
131
+ }
132
+
133
+ function reply(res: ServerResponse, status: number, body: unknown): void {
134
+ res.statusCode = status
135
+ res.setHeader('Content-Type', 'application/json')
136
+ res.end(JSON.stringify(body))
137
+ }
138
+
139
+ function required(name: string): string {
140
+ const value = process.env[name]
141
+ if (!value) {
142
+ console.error(`Missing required env var ${name}`)
143
+ process.exit(1)
144
+ }
145
+ return value
146
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Read the messages of a line, newest first. `messages.list()` returns an
3
+ * async iterable: the SDK fetches the next page when the loop has consumed
4
+ * the current one.
5
+ *
6
+ * This script calls the iSnap API at https://api.isnap.ai with your key. It
7
+ * only reads.
8
+ *
9
+ * Copy this file into your project, then run it:
10
+ *
11
+ * ISNAP_API_KEY=isnap_live_... ISNAP_LINE_ID=line_... \
12
+ * bun run paginate-messages.ts
13
+ */
14
+ import { APIConnectionError, ISnapClient } from '@isnap/sdk'
15
+
16
+ const apiKey = required('ISNAP_API_KEY')
17
+ const lineId = required('ISNAP_LINE_ID')
18
+
19
+ const client = new ISnapClient({ apiKey })
20
+
21
+ // Stop after 10 seconds even if pages keep coming. An aborted signal rejects
22
+ // the loop with an APIConnectionError: immediately when a page request is in
23
+ // flight, at the next page boundary otherwise. Catch it so the script exits
24
+ // cleanly, and clear the timer so the script exits when the loop ends.
25
+ const ac = new AbortController()
26
+ const timer = setTimeout(() => ac.abort(), 10_000)
27
+
28
+ let count = 0
29
+ try {
30
+ for await (const message of client.messages.list(
31
+ { line_id: lineId, limit: 100 },
32
+ { signal: ac.signal }
33
+ )) {
34
+ count++
35
+ console.log(`${message.id}\t${message.created_at}\t${message.status}`)
36
+ if (count >= 500) break // no further page is fetched after a break
37
+ }
38
+ } catch (err) {
39
+ if (!(err instanceof APIConnectionError)) throw err
40
+ console.log('(stopped: aborted or connection failure)')
41
+ } finally {
42
+ clearTimeout(timer)
43
+ }
44
+
45
+ console.log(`\niterated ${count} messages`)
46
+
47
+ function required(name: string): string {
48
+ const value = process.env[name]
49
+ if (!value) {
50
+ console.error(`Missing required env var ${name}`)
51
+ process.exit(1)
52
+ }
53
+ return value
54
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Send one message from a line. The line's device chooses the service:
3
+ * iMessage, RCS or SMS.
4
+ *
5
+ * This script calls the iSnap API at https://api.isnap.ai with your key and
6
+ * sends a real message to ISNAP_TO. An `isnap_test_` account key acts on the
7
+ * same account, lines and billing as an `isnap_live_` key.
8
+ *
9
+ * Copy this file into your project, then run it:
10
+ *
11
+ * ISNAP_API_KEY=isnap_live_... ISNAP_LINE_ID=line_... ISNAP_TO=+14155550123 \
12
+ * bun run send-message.ts
13
+ */
14
+ import { ISnapClient } from '@isnap/sdk'
15
+
16
+ const apiKey = required('ISNAP_API_KEY')
17
+ const lineId = required('ISNAP_LINE_ID')
18
+ const to = required('ISNAP_TO')
19
+
20
+ const client = new ISnapClient({ apiKey })
21
+
22
+ const message = await client.messages.send({
23
+ line_id: lineId,
24
+ to,
25
+ body: 'Hello from the iSnap SDK example.'
26
+ })
27
+
28
+ console.log(`sent ${message.id} (status: ${message.status})`)
29
+
30
+ function required(name: string): string {
31
+ const value = process.env[name]
32
+ if (!value) {
33
+ console.error(`Missing required env var ${name}`)
34
+ process.exit(1)
35
+ }
36
+ return value
37
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Upload a file and send it as an attachment. `attachments.upload()`
3
+ * registers the attachment, uploads the bytes and waits until the attachment
4
+ * is ready.
5
+ *
6
+ * This script calls the iSnap API at https://api.isnap.ai with your key and
7
+ * sends a real message to ISNAP_TO. An `isnap_test_` account key acts on the
8
+ * same account, lines and billing as an `isnap_live_` key.
9
+ *
10
+ * Copy this file into your project, then run it:
11
+ *
12
+ * ISNAP_API_KEY=isnap_live_... ISNAP_LINE_ID=line_... ISNAP_TO=+14155550123 \
13
+ * bun run upload-attachment.ts ./photo.jpg
14
+ */
15
+ import { readFile } from 'node:fs/promises'
16
+ import { basename, extname } from 'node:path'
17
+ import { APIError, ISnapClient, type Attachment } from '@isnap/sdk'
18
+
19
+ const apiKey = required('ISNAP_API_KEY')
20
+ const lineId = required('ISNAP_LINE_ID')
21
+ const to = required('ISNAP_TO')
22
+
23
+ const filePath = process.argv[2]
24
+ if (!filePath) {
25
+ console.error('Usage: bun run upload-attachment.ts <path-to-file>')
26
+ process.exit(1)
27
+ }
28
+
29
+ const file = await readFile(filePath)
30
+ const contentType = guessContentType(filePath)
31
+
32
+ const client = new ISnapClient({ apiKey })
33
+
34
+ // By default the helper reads the attachment 60 times, 500 ms apart: 30
35
+ // seconds. iSnap confirms a finished upload on a 30-second cycle, so the
36
+ // default can run out on an upload that succeeds. Each read is a request that
37
+ // counts toward the request-rate limit: 60 reads 2 seconds apart wait 2
38
+ // minutes with at most 30 requests per minute.
39
+ let attachment: Attachment
40
+ try {
41
+ attachment = await client.attachments.upload(
42
+ file,
43
+ { filename: basename(filePath), contentType },
44
+ { pollIntervalMs: 2_000, maxPolls: 60 }
45
+ )
46
+ } catch (err) {
47
+ if (err instanceof APIError && err.code === 'upload_timeout') {
48
+ // The attachment is not canceled and can still become ready. Its id is in
49
+ // the error message.
50
+ console.error(`not ready in time: ${err.message}`)
51
+ process.exit(1)
52
+ }
53
+ throw err
54
+ }
55
+ console.log(`uploaded ${attachment.id} (${attachment.size_bytes} bytes)`)
56
+
57
+ const message = await client.messages.send({
58
+ line_id: lineId,
59
+ to,
60
+ body: 'See attached.',
61
+ attachments: [attachment.id]
62
+ })
63
+ console.log(`sent ${message.id} with attachment`)
64
+
65
+ function guessContentType(path: string): string {
66
+ const ext = extname(path).toLowerCase()
67
+ switch (ext) {
68
+ case '.jpg':
69
+ case '.jpeg':
70
+ return 'image/jpeg'
71
+ case '.png':
72
+ return 'image/png'
73
+ case '.gif':
74
+ return 'image/gif'
75
+ case '.mp4':
76
+ return 'video/mp4'
77
+ case '.pdf':
78
+ return 'application/pdf'
79
+ default:
80
+ return 'application/octet-stream'
81
+ }
82
+ }
83
+
84
+ function required(name: string): string {
85
+ const value = process.env[name]
86
+ if (!value) {
87
+ console.error(`Missing required env var ${name}`)
88
+ process.exit(1)
89
+ }
90
+ return value
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isnap/sdk",
3
- "version": "2.3.0",
3
+ "version": "2.3.1-next.43615425532.1",
4
4
  "description": "Official TypeScript SDK for the iSnap P2P telephony API",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -14,6 +14,7 @@
14
14
  },
15
15
  "files": [
16
16
  "dist",
17
+ "examples",
17
18
  "README.md",
18
19
  "CHANGELOG.md",
19
20
  "LICENSE"
@@ -29,14 +30,9 @@
29
30
  "sdk",
30
31
  "typescript"
31
32
  ],
32
- "homepage": "https://github.com/WhatSnap/iSnap-App/tree/main/packages/sdk#readme",
33
+ "homepage": "https://docs.isnap.ai/sdk/overview",
33
34
  "bugs": {
34
- "url": "https://github.com/WhatSnap/iSnap-App/issues"
35
- },
36
- "repository": {
37
- "type": "git",
38
- "url": "git+https://github.com/WhatSnap/iSnap-App.git",
39
- "directory": "packages/sdk"
35
+ "email": "support@isnap.ai"
40
36
  },
41
37
  "scripts": {
42
38
  "build": "tsc -p tsconfig.build.json && bun scripts/copy-generated.ts",