smswire 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +173 -2
- package/dist/index.cjs +420 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1754 -0
- package/dist/index.d.ts +1754 -0
- package/dist/index.js +388 -0
- package/dist/index.js.map +1 -0
- package/package.json +34 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SMSWire
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,174 @@
|
|
|
1
|
-
#
|
|
1
|
+
# SMSWire for Node.js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Send SMS and one-time codes from your app through your own Android phones with [SMSWire](https://smswire.app).
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install smswire
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Node 20+ (also Bun, Deno and edge runtimes with `fetch` and Web Crypto). No dependencies.
|
|
10
|
+
|
|
11
|
+
## Set up
|
|
12
|
+
|
|
13
|
+
Each project on the dashboard has an API key and a slug (the part after `/p/` in its endpoint). Keep them in the environment:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
SMSWIRE_KEY="smswire_live_…"
|
|
17
|
+
SMSWIRE_PROJECT="prj_…"
|
|
18
|
+
SMSWIRE_WEBHOOK_SECRET="whsec_…" # only if you receive webhooks
|
|
19
|
+
# SMSWIRE_URL="https://api.smswire.app" # your server, if you host SMSWire yourself
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { SMSWire } from 'smswire';
|
|
24
|
+
|
|
25
|
+
const sms = new SMSWire(); // or new SMSWire({ apiKey, project, baseUrl })
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Send
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
const message = await sms.messages.send({
|
|
32
|
+
to: '+251911234567',
|
|
33
|
+
body: 'Your order {{order}} shipped',
|
|
34
|
+
variables: { order: 'A-1042' },
|
|
35
|
+
type: 'transactional', // otp | transactional | notification | marketing
|
|
36
|
+
tags: ['orders'],
|
|
37
|
+
metadata: { user_id: 42 }, // echoed back in webhooks
|
|
38
|
+
});
|
|
39
|
+
// → { id: 'msg_…', status: 'queued', segments: 1, … }
|
|
40
|
+
|
|
41
|
+
// Your own idempotency key makes your retries safe too (the SDK adds a random one otherwise).
|
|
42
|
+
await sms.messages.send({ to, body }, { idempotencyKey: `order-${order.id}` });
|
|
43
|
+
|
|
44
|
+
await sms.messages.get(message.id);
|
|
45
|
+
await sms.messages.cancel(message.id); // before it reaches a phone
|
|
46
|
+
|
|
47
|
+
const page = await sms.messages.list({ status: 'failed', limit: 50 });
|
|
48
|
+
for await (const m of sms.messages.listAll({ tag: 'orders' })) console.log(m.id, m.status);
|
|
49
|
+
|
|
50
|
+
const batch = await sms.messages.sendBulk({
|
|
51
|
+
name: 'Weekend sale',
|
|
52
|
+
body: 'Hi {{name}}, 20% off this weekend',
|
|
53
|
+
rate: 30, // per minute
|
|
54
|
+
messages: [{ to: '+251911234567', variables: { name: 'Abebe' } }, { to: '+251922345678', variables: { name: 'Sara' } }],
|
|
55
|
+
});
|
|
56
|
+
// → { batch_id, accepted, rejected: [{ index, to, reason }] }
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Templates in more than one language
|
|
60
|
+
|
|
61
|
+
A template saved on the dashboard can hold a text per language. Send it by name and each recipient
|
|
62
|
+
gets the one they read — the `language` on their contact — while everyone else gets the default text.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
await sms.messages.sendBulk({
|
|
66
|
+
template: 'order-shipped',
|
|
67
|
+
messages: [
|
|
68
|
+
{ to: '+251911234567', variables: { name: 'Abebe' } }, // reads am → the Amharic text
|
|
69
|
+
{ to: '+14155550123', variables: { name: 'Alex' } }, // no language → the default text
|
|
70
|
+
{ to: '+5511999990000', language: 'pt-BR', variables: { name: 'Bruna' } }, // this one, in Portuguese
|
|
71
|
+
],
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// One language for everybody, whatever they read:
|
|
75
|
+
await sms.messages.send({ to: '+251911234567', template: 'order-shipped', language: 'am', variables: { name: 'Abebe' } });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
A message says which language it went out in (`language`; `null` means the default text), and
|
|
79
|
+
`pt-BR` matches a text written in `pt`, so regions need not be written twice.
|
|
80
|
+
|
|
81
|
+
## One-time codes
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
const otp = await sms.otp.send({ to: '+251911234567', length: 6, ttl: 300 });
|
|
85
|
+
// later, with what the user typed:
|
|
86
|
+
const { valid, reason } = await sms.otp.verify({ id: otp.id, code: input });
|
|
87
|
+
// reason: invalid | expired | too_many_attempts | already_used
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Recurring sends
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const schedule = await sms.schedules.create({
|
|
94
|
+
name: 'Weekly report',
|
|
95
|
+
cron: '0 9 * * 1',
|
|
96
|
+
timezone: 'Africa/Addis_Ababa',
|
|
97
|
+
to: '+251911234567',
|
|
98
|
+
body: 'Your weekly report is ready',
|
|
99
|
+
});
|
|
100
|
+
await sms.schedules.update(schedule.id, { enabled: false });
|
|
101
|
+
await sms.schedules.list();
|
|
102
|
+
await sms.schedules.delete(schedule.id);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Contact groups
|
|
106
|
+
|
|
107
|
+
Groups belong to the workspace, so every project's key sees the same ones. With `keywords`, someone who texts exactly one of them to a workspace phone joins the group (and gets `join_reply` once); your webhook hears `group.joined`.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
const group = await sms.groups.create({ name: 'Promo', keywords: ['A2'], join_reply: "You're in! Reply STOP to opt out." });
|
|
111
|
+
await sms.groups.addMembers(group.id, [{ phone: '+251911234567', name: 'Abebe' }]);
|
|
112
|
+
for await (const member of sms.groups.listAllMembers(group.id)) console.log(member.phone, member.source);
|
|
113
|
+
await sms.messages.sendBulk({ group_ids: [group.id], body: 'Hi {{name|there}}, 20% off today' });
|
|
114
|
+
await sms.groups.removeMember(group.id, '+251911234567');
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Campaigns
|
|
118
|
+
|
|
119
|
+
A campaign is a send with a name: a message, who it goes to, who to leave out, and when. It is made as a
|
|
120
|
+
draft and nothing goes out until you start it, so you can check who it reaches first. Each run is an
|
|
121
|
+
ordinary batch. `marketing` needs `consent` -- that the recipients agreed to hear from you -- and
|
|
122
|
+
`stop_footer` ends every marketing message with your opt-out line, counted in its SMS parts.
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
const campaign = await sms.campaigns.create({
|
|
126
|
+
name: 'Weekend sale',
|
|
127
|
+
body: 'Hi {{name|there}}, 20% off this weekend',
|
|
128
|
+
type: 'marketing',
|
|
129
|
+
consent: true,
|
|
130
|
+
audience: { group_ids: [group.id] },
|
|
131
|
+
exclude: { recent_days: 7 },
|
|
132
|
+
stop_footer: 'Reply STOP to opt out',
|
|
133
|
+
quiet_hours: { start: '20:00', end: '08:00', timezone: 'Africa/Addis_Ababa' },
|
|
134
|
+
});
|
|
135
|
+
const { recipients, excluded } = await sms.campaigns.preview(campaign.id);
|
|
136
|
+
await sms.campaigns.send(campaign.id);
|
|
137
|
+
const results = await sms.campaigns.results(campaign.id);
|
|
138
|
+
console.log(results.delivered, results.replies, results.opt_outs, results.parts);
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Webhooks
|
|
142
|
+
|
|
143
|
+
Status updates (`message.status`) and replies (`message.received`) are POSTed to the project's webhook URL, signed with `X-SMSWire-Signature`. Verify the **raw** body:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import express from 'express';
|
|
147
|
+
import { SMSWireSignatureError } from 'smswire';
|
|
148
|
+
|
|
149
|
+
app.post('/hooks/smswire', express.raw({ type: 'application/json' }), async (req, res) => {
|
|
150
|
+
let event;
|
|
151
|
+
try {
|
|
152
|
+
event = await sms.webhooks.verify(req.body, req.get('X-SMSWire-Signature'));
|
|
153
|
+
} catch (e) {
|
|
154
|
+
if (e instanceof SMSWireSignatureError) return res.sendStatus(400);
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
if (event.event === 'message.status') await markOrder(event.metadata, event.status);
|
|
158
|
+
if (event.event === 'message.received') await handleReply(event.from, event.body);
|
|
159
|
+
res.sendStatus(200);
|
|
160
|
+
});
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Without a client: `verifyWebhook(rawBody, signature, secret)`. The same event can arrive twice; make the handler idempotent.
|
|
164
|
+
|
|
165
|
+
## Errors and retries
|
|
166
|
+
|
|
167
|
+
Failed calls throw `SMSWireError` with `status` (null when no answer came), `code` (`invalid_request`, `invalid_api_key`, `rate_limited`, `daily_limit_reached`, `network_error`, `timeout`, …), `message` and `retryAfter`.
|
|
168
|
+
|
|
169
|
+
The SDK retries (default `maxRetries: 2`, waiting `Retry-After` or backing off):
|
|
170
|
+
|
|
171
|
+
- reads, updates, deletes and `messages.send` (it carries an idempotency key): on 429, 5xx and network errors;
|
|
172
|
+
- `sendBulk`, `otp.send`, `otp.verify`, `schedules.create`: on 429 only, since a 5xx or a dropped connection may already have done the work.
|
|
173
|
+
|
|
174
|
+
A `Retry-After` longer than `maxRetryWait` (60 s, e.g. a daily limit) throws at once.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
SIGNATURE_HEADER: () => SIGNATURE_HEADER,
|
|
24
|
+
SMSWire: () => SMSWire,
|
|
25
|
+
SMSWireError: () => SMSWireError,
|
|
26
|
+
SMSWireSignatureError: () => SMSWireSignatureError,
|
|
27
|
+
VERSION: () => VERSION,
|
|
28
|
+
default: () => index_default,
|
|
29
|
+
verifyWebhook: () => verifyWebhook
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(index_exports);
|
|
32
|
+
|
|
33
|
+
// src/errors.ts
|
|
34
|
+
var SMSWireError = class extends Error {
|
|
35
|
+
constructor(status, code, message, retryAfter2 = null, options) {
|
|
36
|
+
super(message, options);
|
|
37
|
+
this.status = status;
|
|
38
|
+
this.code = code;
|
|
39
|
+
this.retryAfter = retryAfter2;
|
|
40
|
+
}
|
|
41
|
+
status;
|
|
42
|
+
code;
|
|
43
|
+
retryAfter;
|
|
44
|
+
name = "SMSWireError";
|
|
45
|
+
};
|
|
46
|
+
var SMSWireSignatureError = class extends Error {
|
|
47
|
+
name = "SMSWireSignatureError";
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// src/http.ts
|
|
51
|
+
var sleep = (seconds) => new Promise((r) => setTimeout(r, seconds * 1e3));
|
|
52
|
+
function retryAfter(header) {
|
|
53
|
+
if (!header) return null;
|
|
54
|
+
const n = Number(header);
|
|
55
|
+
if (Number.isFinite(n)) return Math.max(0, n);
|
|
56
|
+
const at = Date.parse(header);
|
|
57
|
+
return Number.isNaN(at) ? null : Math.max(0, (at - Date.now()) / 1e3);
|
|
58
|
+
}
|
|
59
|
+
var backoff = (attempt) => Math.min(8, 0.5 * 2 ** attempt) * (1 + Math.random() * 0.25);
|
|
60
|
+
async function errorFrom(res) {
|
|
61
|
+
const text = await res.text().catch(() => "");
|
|
62
|
+
let code = "http_error";
|
|
63
|
+
let message = `HTTP ${res.status}`;
|
|
64
|
+
try {
|
|
65
|
+
const body = JSON.parse(text);
|
|
66
|
+
if (typeof body.error === "string" && typeof body.message === "string") {
|
|
67
|
+
code = body.error;
|
|
68
|
+
message = body.message;
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
72
|
+
return new SMSWireError(res.status, code, message, retryAfter(res.headers.get("retry-after")));
|
|
73
|
+
}
|
|
74
|
+
function retryDelay(err, req, attempt, opts) {
|
|
75
|
+
if (attempt >= opts.maxRetries) return null;
|
|
76
|
+
const retryable = err.status === 429 || req.idempotent && (err.status === null || err.status >= 500);
|
|
77
|
+
if (!retryable) return null;
|
|
78
|
+
if (err.retryAfter !== null) return err.retryAfter <= opts.maxRetryWait ? err.retryAfter : null;
|
|
79
|
+
return backoff(attempt);
|
|
80
|
+
}
|
|
81
|
+
async function send(opts, req) {
|
|
82
|
+
const url = new URL(opts.baseUrl.replace(/\/+$/, "") + req.path);
|
|
83
|
+
for (const [k, v] of Object.entries(req.query ?? {})) {
|
|
84
|
+
if (v !== void 0 && v !== null) url.searchParams.set(k, String(v));
|
|
85
|
+
}
|
|
86
|
+
const headers = {
|
|
87
|
+
Authorization: `Bearer ${opts.apiKey}`,
|
|
88
|
+
Accept: "application/json",
|
|
89
|
+
"User-Agent": opts.userAgent,
|
|
90
|
+
...req.headers
|
|
91
|
+
};
|
|
92
|
+
if (req.body !== void 0) headers["Content-Type"] = "application/json";
|
|
93
|
+
const body = req.body === void 0 ? void 0 : JSON.stringify(req.body);
|
|
94
|
+
for (let attempt = 0; ; attempt++) {
|
|
95
|
+
let res;
|
|
96
|
+
let err;
|
|
97
|
+
try {
|
|
98
|
+
res = await opts.fetch(url, { method: req.method, headers, body, signal: AbortSignal.timeout(opts.timeout) });
|
|
99
|
+
} catch (e) {
|
|
100
|
+
const timedOut = e instanceof Error && e.name === "TimeoutError";
|
|
101
|
+
err = new SMSWireError(
|
|
102
|
+
null,
|
|
103
|
+
timedOut ? "timeout" : "network_error",
|
|
104
|
+
timedOut ? `No answer within ${opts.timeout} ms` : `Could not reach ${url.origin}: ${e.message}`,
|
|
105
|
+
null,
|
|
106
|
+
{ cause: e }
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
if (res?.ok) {
|
|
110
|
+
const text = await res.text();
|
|
111
|
+
return text ? JSON.parse(text) : void 0;
|
|
112
|
+
}
|
|
113
|
+
if (res) err = await errorFrom(res);
|
|
114
|
+
const wait = retryDelay(err, req, attempt, opts);
|
|
115
|
+
if (wait === null) throw err;
|
|
116
|
+
await sleep(wait);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/resources/messages.ts
|
|
121
|
+
var Messages = class {
|
|
122
|
+
constructor(call, base) {
|
|
123
|
+
this.call = call;
|
|
124
|
+
this.base = base;
|
|
125
|
+
}
|
|
126
|
+
call;
|
|
127
|
+
base;
|
|
128
|
+
/** Queues one SMS for the project's phone. */
|
|
129
|
+
send(params, options = {}) {
|
|
130
|
+
return this.call({
|
|
131
|
+
method: "POST",
|
|
132
|
+
path: this.base,
|
|
133
|
+
body: params,
|
|
134
|
+
headers: { "Idempotency-Key": options.idempotencyKey ?? crypto.randomUUID() },
|
|
135
|
+
idempotent: true
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/** Queues a batch. Invalid or opted-out items come back in `rejected`; the rest go out as one batch. */
|
|
139
|
+
sendBulk(params) {
|
|
140
|
+
return this.call({ method: "POST", path: `${this.base}/bulk`, body: params, idempotent: false });
|
|
141
|
+
}
|
|
142
|
+
get(id) {
|
|
143
|
+
return this.call({ method: "GET", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
|
|
144
|
+
}
|
|
145
|
+
/** Stops a message that hasn't reached a phone yet. */
|
|
146
|
+
cancel(id) {
|
|
147
|
+
return this.call({ method: "DELETE", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
|
|
148
|
+
}
|
|
149
|
+
/** One page, newest first. Pass `next_cursor` back as `cursor` for the next. */
|
|
150
|
+
list(params = {}) {
|
|
151
|
+
return this.call({ method: "GET", path: this.base, query: params, idempotent: true });
|
|
152
|
+
}
|
|
153
|
+
/** Every matching message, newest first, fetching pages as you go. */
|
|
154
|
+
async *listAll(params = {}) {
|
|
155
|
+
let cursor;
|
|
156
|
+
do {
|
|
157
|
+
const page = await this.list({ ...params, cursor: cursor ?? void 0 });
|
|
158
|
+
yield* page.data;
|
|
159
|
+
cursor = page.next_cursor;
|
|
160
|
+
} while (cursor);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// src/resources/otp.ts
|
|
165
|
+
var OneTimeCodes = class {
|
|
166
|
+
constructor(call, base) {
|
|
167
|
+
this.call = call;
|
|
168
|
+
this.base = base;
|
|
169
|
+
}
|
|
170
|
+
call;
|
|
171
|
+
base;
|
|
172
|
+
/** Texts a fresh code to `to`. Keep the returned `id` for verify(). */
|
|
173
|
+
send(params) {
|
|
174
|
+
return this.call({ method: "POST", path: this.base, body: params, idempotent: false });
|
|
175
|
+
}
|
|
176
|
+
/** Checks what the user typed. `valid` is false with a `reason` when it's wrong, expired or used. */
|
|
177
|
+
verify(params) {
|
|
178
|
+
return this.call({ method: "POST", path: `${this.base}/verify`, body: params, idempotent: false });
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// src/resources/campaigns.ts
|
|
183
|
+
var Campaigns = class {
|
|
184
|
+
constructor(call, base) {
|
|
185
|
+
this.call = call;
|
|
186
|
+
this.base = base;
|
|
187
|
+
}
|
|
188
|
+
call;
|
|
189
|
+
base;
|
|
190
|
+
/**
|
|
191
|
+
* Makes a draft. Marketing needs `consent: true` -- that the recipients agreed to hear from
|
|
192
|
+
* you -- and `stop_footer` ends every marketing message with your opt-out line. With `cron` it
|
|
193
|
+
* repeats instead of sending once.
|
|
194
|
+
*/
|
|
195
|
+
create(params) {
|
|
196
|
+
return this.call({ method: "POST", path: this.base, body: params, idempotent: false });
|
|
197
|
+
}
|
|
198
|
+
list() {
|
|
199
|
+
return this.call({ method: "GET", path: this.base, idempotent: true });
|
|
200
|
+
}
|
|
201
|
+
get(id) {
|
|
202
|
+
return this.call({ method: "GET", path: this.one(id), idempotent: true });
|
|
203
|
+
}
|
|
204
|
+
/** Absent fields stay as they are, and the change reaches the runs still to come. */
|
|
205
|
+
update(id, params) {
|
|
206
|
+
return this.call({ method: "PATCH", path: this.one(id), body: params, idempotent: true });
|
|
207
|
+
}
|
|
208
|
+
/** The campaign goes; its runs stay in the message log. */
|
|
209
|
+
async delete(id) {
|
|
210
|
+
await this.call({ method: "DELETE", path: this.one(id), idempotent: true });
|
|
211
|
+
}
|
|
212
|
+
/** Who it would reach right now: groups read, duplicates dropped, exclusions applied. */
|
|
213
|
+
preview(id) {
|
|
214
|
+
return this.call({ method: "GET", path: `${this.one(id)}/preview`, idempotent: true });
|
|
215
|
+
}
|
|
216
|
+
/** How it did: delivery, SMS parts, replies and the opt-outs it cost. */
|
|
217
|
+
results(id) {
|
|
218
|
+
return this.call({ method: "GET", path: `${this.one(id)}/results`, idempotent: true });
|
|
219
|
+
}
|
|
220
|
+
/** Starts it: `queued` with a batch, or `scheduled` when it waits for its time or its cron. */
|
|
221
|
+
send(id) {
|
|
222
|
+
return this.call({ method: "POST", path: `${this.one(id)}/send`, idempotent: false });
|
|
223
|
+
}
|
|
224
|
+
/** Holds every run still going, or lets them carry on. */
|
|
225
|
+
control(id, status) {
|
|
226
|
+
return this.call({ method: "POST", path: `${this.one(id)}/control`, body: { status }, idempotent: true });
|
|
227
|
+
}
|
|
228
|
+
/** Stops it for good: what is still on the server is cancelled and refunded. */
|
|
229
|
+
cancel(id) {
|
|
230
|
+
return this.call({ method: "POST", path: `${this.one(id)}/cancel`, idempotent: true });
|
|
231
|
+
}
|
|
232
|
+
one(id) {
|
|
233
|
+
return `${this.base}/${encodeURIComponent(id)}`;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
// src/resources/groups.ts
|
|
238
|
+
var Groups = class {
|
|
239
|
+
constructor(call, base) {
|
|
240
|
+
this.call = call;
|
|
241
|
+
this.base = base;
|
|
242
|
+
}
|
|
243
|
+
call;
|
|
244
|
+
base;
|
|
245
|
+
/** With `keywords`, someone who texts one of them (the whole text) to a workspace phone joins. */
|
|
246
|
+
create(params) {
|
|
247
|
+
return this.call({ method: "POST", path: this.base, body: params, idempotent: false });
|
|
248
|
+
}
|
|
249
|
+
list() {
|
|
250
|
+
return this.call({ method: "GET", path: this.base, idempotent: true });
|
|
251
|
+
}
|
|
252
|
+
get(id) {
|
|
253
|
+
return this.call({ method: "GET", path: this.one(id), idempotent: true });
|
|
254
|
+
}
|
|
255
|
+
/** Absent fields stay as they are; `keywords: []` turns joining by text off. */
|
|
256
|
+
update(id, params) {
|
|
257
|
+
return this.call({ method: "PATCH", path: this.one(id), body: params, idempotent: true });
|
|
258
|
+
}
|
|
259
|
+
/** The group goes; its contacts stay. */
|
|
260
|
+
async delete(id) {
|
|
261
|
+
await this.call({ method: "DELETE", path: this.one(id), idempotent: true });
|
|
262
|
+
}
|
|
263
|
+
/** One page of members, alphabetically; pass `next_cursor` back as `cursor` for the next. */
|
|
264
|
+
listMembers(id, params = {}) {
|
|
265
|
+
return this.call({ method: "GET", path: `${this.one(id)}/members`, query: params, idempotent: true });
|
|
266
|
+
}
|
|
267
|
+
/** Every member, fetching pages as you iterate. */
|
|
268
|
+
async *listAllMembers(id, params = {}) {
|
|
269
|
+
let cursor;
|
|
270
|
+
do {
|
|
271
|
+
const page = await this.listMembers(id, { ...params, cursor });
|
|
272
|
+
yield* page.data;
|
|
273
|
+
cursor = page.next_cursor ?? void 0;
|
|
274
|
+
} while (cursor);
|
|
275
|
+
}
|
|
276
|
+
/** Adds people by number; new numbers become contacts (a given name replaces theirs, fields merge). */
|
|
277
|
+
addMembers(id, members) {
|
|
278
|
+
return this.call({ method: "POST", path: `${this.one(id)}/members`, body: { members }, idempotent: true });
|
|
279
|
+
}
|
|
280
|
+
/** Takes the number out of the group; the contact stays. */
|
|
281
|
+
async removeMember(id, phone) {
|
|
282
|
+
await this.call({ method: "DELETE", path: `${this.one(id)}/members/${encodeURIComponent(phone)}`, idempotent: true });
|
|
283
|
+
}
|
|
284
|
+
one(id) {
|
|
285
|
+
return `${this.base}/${encodeURIComponent(id)}`;
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
// src/resources/schedules.ts
|
|
290
|
+
var Schedules = class {
|
|
291
|
+
constructor(call, base) {
|
|
292
|
+
this.call = call;
|
|
293
|
+
this.base = base;
|
|
294
|
+
}
|
|
295
|
+
call;
|
|
296
|
+
base;
|
|
297
|
+
/** A message (or batch) sent again and again on a cron schedule. */
|
|
298
|
+
create(params) {
|
|
299
|
+
return this.call({ method: "POST", path: this.base, body: params, idempotent: false });
|
|
300
|
+
}
|
|
301
|
+
list() {
|
|
302
|
+
return this.call({ method: "GET", path: this.base, idempotent: true });
|
|
303
|
+
}
|
|
304
|
+
/** One schedule, with its recent runs. */
|
|
305
|
+
get(id) {
|
|
306
|
+
return this.call({ method: "GET", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
|
|
307
|
+
}
|
|
308
|
+
/** Absent fields stay as they are; recipients can't change. */
|
|
309
|
+
update(id, params) {
|
|
310
|
+
return this.call({ method: "PATCH", path: `${this.base}/${encodeURIComponent(id)}`, body: params, idempotent: true });
|
|
311
|
+
}
|
|
312
|
+
async delete(id) {
|
|
313
|
+
await this.call({ method: "DELETE", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
// src/webhooks.ts
|
|
318
|
+
var SIGNATURE_HEADER = "X-SMSWire-Signature";
|
|
319
|
+
var encoder = new TextEncoder();
|
|
320
|
+
function bytes(body) {
|
|
321
|
+
if (typeof body === "string") return encoder.encode(body);
|
|
322
|
+
return body instanceof Uint8Array ? body : new Uint8Array(body);
|
|
323
|
+
}
|
|
324
|
+
function parse(header) {
|
|
325
|
+
let t = null;
|
|
326
|
+
const signatures = [];
|
|
327
|
+
for (const part of header.split(",")) {
|
|
328
|
+
const i = part.indexOf("=");
|
|
329
|
+
if (i < 0) continue;
|
|
330
|
+
const key = part.slice(0, i).trim();
|
|
331
|
+
const value = part.slice(i + 1).trim();
|
|
332
|
+
if (key === "t" && /^\d+$/.test(value)) t = Number(value);
|
|
333
|
+
else if (key === "v1" && /^[0-9a-f]{64}$/i.test(value)) signatures.push(value.toLowerCase());
|
|
334
|
+
}
|
|
335
|
+
return t === null || !signatures.length ? null : { t, signatures };
|
|
336
|
+
}
|
|
337
|
+
async function hmacHex(secret, message) {
|
|
338
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
339
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, message));
|
|
340
|
+
return Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
341
|
+
}
|
|
342
|
+
function constantTimeEqual(a, b) {
|
|
343
|
+
if (a.length !== b.length) return false;
|
|
344
|
+
let diff = 0;
|
|
345
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
346
|
+
return diff === 0;
|
|
347
|
+
}
|
|
348
|
+
async function verifyWebhook(rawBody, signature, secret, options = {}) {
|
|
349
|
+
if (!secret) throw new SMSWireSignatureError("No webhook signing secret given");
|
|
350
|
+
const parsed = parse(signature ?? "");
|
|
351
|
+
if (!parsed) throw new SMSWireSignatureError(`Missing or malformed ${SIGNATURE_HEADER} header`);
|
|
352
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
353
|
+
if (Math.abs(now - parsed.t) > (options.tolerance ?? 300)) {
|
|
354
|
+
throw new SMSWireSignatureError("Signature timestamp is outside the tolerance");
|
|
355
|
+
}
|
|
356
|
+
const body = bytes(rawBody);
|
|
357
|
+
const prefix = encoder.encode(`${parsed.t}.`);
|
|
358
|
+
const signed = new Uint8Array(prefix.length + body.length);
|
|
359
|
+
signed.set(prefix);
|
|
360
|
+
signed.set(body, prefix.length);
|
|
361
|
+
const expected = await hmacHex(secret, signed);
|
|
362
|
+
if (!parsed.signatures.some((s) => constantTimeEqual(s, expected))) {
|
|
363
|
+
throw new SMSWireSignatureError("Signature does not match");
|
|
364
|
+
}
|
|
365
|
+
return JSON.parse(new TextDecoder().decode(body));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// src/client.ts
|
|
369
|
+
var VERSION = "0.2.0";
|
|
370
|
+
var env = (name) => typeof process === "undefined" ? void 0 : process.env?.[name] || void 0;
|
|
371
|
+
var SMSWire = class {
|
|
372
|
+
messages;
|
|
373
|
+
otp;
|
|
374
|
+
schedules;
|
|
375
|
+
groups;
|
|
376
|
+
campaigns;
|
|
377
|
+
webhooks;
|
|
378
|
+
constructor(options = {}) {
|
|
379
|
+
const apiKey = options.apiKey ?? env("SMSWIRE_KEY");
|
|
380
|
+
const project = options.project ?? env("SMSWIRE_PROJECT");
|
|
381
|
+
if (!apiKey) throw new Error("SMSWire: pass apiKey or set SMSWIRE_KEY");
|
|
382
|
+
if (!project) throw new Error("SMSWire: pass project or set SMSWIRE_PROJECT");
|
|
383
|
+
const http = {
|
|
384
|
+
apiKey,
|
|
385
|
+
baseUrl: options.baseUrl ?? env("SMSWIRE_URL") ?? "https://api.smswire.app",
|
|
386
|
+
maxRetries: options.maxRetries ?? 2,
|
|
387
|
+
maxRetryWait: options.maxRetryWait ?? 60,
|
|
388
|
+
timeout: options.timeout ?? 3e4,
|
|
389
|
+
fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
|
|
390
|
+
userAgent: `smswire-node/${VERSION}`
|
|
391
|
+
};
|
|
392
|
+
const call = (req) => send(http, req);
|
|
393
|
+
const p = `/v1/p/${encodeURIComponent(project)}`;
|
|
394
|
+
this.messages = new Messages(call, `${p}/messages`);
|
|
395
|
+
this.otp = new OneTimeCodes(call, `${p}/otp`);
|
|
396
|
+
this.schedules = new Schedules(call, `${p}/schedules`);
|
|
397
|
+
this.groups = new Groups(call, `${p}/groups`);
|
|
398
|
+
this.campaigns = new Campaigns(call, `${p}/campaigns`);
|
|
399
|
+
const secret = options.webhookSecret ?? env("SMSWIRE_WEBHOOK_SECRET");
|
|
400
|
+
this.webhooks = {
|
|
401
|
+
verify: (rawBody, signature, opts) => {
|
|
402
|
+
if (!secret) throw new Error("SMSWire: pass webhookSecret or set SMSWIRE_WEBHOOK_SECRET");
|
|
403
|
+
return verifyWebhook(rawBody, signature, secret, opts);
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
// src/index.ts
|
|
410
|
+
var index_default = SMSWire;
|
|
411
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
412
|
+
0 && (module.exports = {
|
|
413
|
+
SIGNATURE_HEADER,
|
|
414
|
+
SMSWire,
|
|
415
|
+
SMSWireError,
|
|
416
|
+
SMSWireSignatureError,
|
|
417
|
+
VERSION,
|
|
418
|
+
verifyWebhook
|
|
419
|
+
});
|
|
420
|
+
//# sourceMappingURL=index.cjs.map
|