@kalangu/sms 0.0.0-stage → 0.1.0-alpha.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 +44 -2
- package/dist/index.d.ts +70 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +156 -0
- package/dist/index.js.map +1 -0
- package/dist/transport.d.ts +65 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +103 -0
- package/dist/transport.js.map +1 -0
- package/package.json +51 -3
- package/src/index.ts +237 -0
- package/src/transport.ts +151 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Abdoullah Ndao
|
|
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,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kalangu/sms
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Africa's Talking SMS adapter for [Kalangu](https://github.com/utachicodes/kalangu)
|
|
4
|
+
agents: sends replies and deferred answers, receives incoming messages, and
|
|
5
|
+
logs delivery reports.
|
|
6
|
+
|
|
7
|
+
> Alpha. The API may change before 1.0.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add @kalangu/core @kalangu/sms
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createAgent } from "@kalangu/core";
|
|
15
|
+
import { africasTalkingSms } from "@kalangu/sms";
|
|
16
|
+
|
|
17
|
+
const agent = createAgent({
|
|
18
|
+
start,
|
|
19
|
+
channels: [
|
|
20
|
+
africasTalkingSms({
|
|
21
|
+
username: process.env.AT_USERNAME,
|
|
22
|
+
apiKey: process.env.AT_API_KEY,
|
|
23
|
+
senderId: "CLINIC",
|
|
24
|
+
sandbox: false,
|
|
25
|
+
path: "/sms", // incoming messages
|
|
26
|
+
deliveryPath: "/sms/delivery", // delivery reports
|
|
27
|
+
}),
|
|
28
|
+
],
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
- Sends through the legacy `/version1/messaging` endpoint (the one the
|
|
33
|
+
official SDK and the sandbox use). Swap in another `transport` to use a
|
|
34
|
+
different endpoint.
|
|
35
|
+
- A refused send raises `SmsSendError` with the gateway's own `statusCode`
|
|
36
|
+
and `status`, for example `409 DoNotDisturbRejection` in Nigeria.
|
|
37
|
+
- Messages over the segment cap (`maxSegments`, default 4) are an error,
|
|
38
|
+
never truncated.
|
|
39
|
+
- "Success" in a send response means sent, not delivered; delivery reports
|
|
40
|
+
say what actually happened.
|
|
41
|
+
|
|
42
|
+
Callbacks from the gateway are not signed. Use hard-to-guess paths and,
|
|
43
|
+
where you can, allow only the gateway's IP addresses.
|
|
44
|
+
|
|
45
|
+
MIT licensed.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Africa's Talking SMS adapter (docs/design.md §7.2): sends budgeted
|
|
3
|
+
* messages, receives incoming messages, and logs delivery reports.
|
|
4
|
+
*
|
|
5
|
+
* Callbacks are not signed. Treat them as untrusted input: use a hard-to-
|
|
6
|
+
* guess path and, where you can, allow only the gateway's IP addresses.
|
|
7
|
+
*/
|
|
8
|
+
import { type Channel, type RouteAgent } from "@kalangu/core";
|
|
9
|
+
import { type SmsTransport } from "./transport.js";
|
|
10
|
+
export * from "./transport.js";
|
|
11
|
+
export interface AfricasTalkingSmsOptions {
|
|
12
|
+
/** Channel id. Default "sms". */
|
|
13
|
+
id?: string;
|
|
14
|
+
/** Your Africa's Talking username ("sandbox" in the sandbox). */
|
|
15
|
+
username?: string;
|
|
16
|
+
apiKey?: string;
|
|
17
|
+
/** Registered sender ID or short code. */
|
|
18
|
+
senderId?: string;
|
|
19
|
+
/** Incoming-message callback path, or false for none. Default "/sms". */
|
|
20
|
+
path?: string | false;
|
|
21
|
+
/** Delivery-report callback path, or false for none. Default "/sms/delivery". */
|
|
22
|
+
deliveryPath?: string | false;
|
|
23
|
+
/** Use the sandbox API. Default false. */
|
|
24
|
+
sandbox?: boolean;
|
|
25
|
+
/** Default 1, as in the official SDK. */
|
|
26
|
+
bulkSmsMode?: 0 | 1;
|
|
27
|
+
/** Passed to the gateway only when set. */
|
|
28
|
+
enqueue?: boolean;
|
|
29
|
+
/** Segment cap per message. Default 4. Longer replies are an error, never cut. */
|
|
30
|
+
maxSegments?: number;
|
|
31
|
+
/** Replaces the HTTP transport, e.g. for the JSON bulk endpoint or tests. */
|
|
32
|
+
transport?: SmsTransport;
|
|
33
|
+
fetch?: typeof fetch;
|
|
34
|
+
onDeliveryReport?: (report: DeliveryReport) => void | Promise<void>;
|
|
35
|
+
onIncoming?: (message: IncomingSms) => void | Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
export interface IncomingSms {
|
|
38
|
+
from: string;
|
|
39
|
+
to: string;
|
|
40
|
+
text: string;
|
|
41
|
+
id: string;
|
|
42
|
+
date: string;
|
|
43
|
+
linkId?: string;
|
|
44
|
+
networkCode?: string;
|
|
45
|
+
}
|
|
46
|
+
export type DeliveryStatus = "Sent" | "Submitted" | "Buffered" | "Rejected" | "Success" | "Failed" | "AbsentSubscriber" | "Expired" | (string & {});
|
|
47
|
+
export interface DeliveryReport {
|
|
48
|
+
/** Matches `messageId` from the send response. */
|
|
49
|
+
id: string;
|
|
50
|
+
phoneNumber: string;
|
|
51
|
+
networkCode: string;
|
|
52
|
+
status: DeliveryStatus;
|
|
53
|
+
failureReason?: string;
|
|
54
|
+
}
|
|
55
|
+
export type AfricasTalkingSmsChannel = Channel & {
|
|
56
|
+
send(out: {
|
|
57
|
+
to: string;
|
|
58
|
+
text: string;
|
|
59
|
+
}): Promise<void>;
|
|
60
|
+
/** The transport, for sending outside a conversation. */
|
|
61
|
+
readonly transport: SmsTransport;
|
|
62
|
+
/** Incoming-message handler, for mounting it yourself. */
|
|
63
|
+
handler(agent: RouteAgent): (req: Request) => Promise<Response>;
|
|
64
|
+
};
|
|
65
|
+
export declare function africasTalkingSms(options: AfricasTalkingSmsOptions): AfricasTalkingSmsChannel;
|
|
66
|
+
/** Reads an incoming-message callback's form fields. */
|
|
67
|
+
export declare function parseIncoming(form: FormData | URLSearchParams): IncomingSms;
|
|
68
|
+
/** Reads a delivery-report callback's form fields. */
|
|
69
|
+
export declare function parseDeliveryReport(form: FormData | URLSearchParams): DeliveryReport;
|
|
70
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAc,KAAK,OAAO,E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ED,MAAM,MAAM,cAAc,GACtB,MAAM,GACN,WAAW,GACX,UAAU,GACV,UAAU,GACV,SAAS,GACT,QAAQ,GACR,kBAAkB,GAClB,SAAS,GACT,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAElB,MAAM,WAAW,cAAc;IAC7B,kDAAkD;IAClD,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,cAAc,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,MAAM,wBAAwB,GAAG,OAAO,GAAG;IAC/C,IAAI,CAAC,GAAG,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvD,yDAAyD;IACzD,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC;IACjC,0DAA0D;IAC1D,OAAO,CAAC,KAAK,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;CACjE,CAAC;AAIF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,wBAAwB,CA2B7F;AA2BD,wDAAwD;AACxD,wBAAgB,aAAa,CAAC,IAAI,EAAE,QAAQ,GAAG,eAAe,GAAG,WAAW,CAY3E;AAED,sDAAsD;AACtD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,QAAQ,GAAG,eAAe,GAAG,cAAc,CAUpF"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Africa's Talking SMS adapter (docs/design.md §7.2): sends budgeted
|
|
3
|
+
* messages, receives incoming messages, and logs delivery reports.
|
|
4
|
+
*
|
|
5
|
+
* Callbacks are not signed. Treat them as untrusted input: use a hard-to-
|
|
6
|
+
* guess path and, where you can, allow only the gateway's IP addresses.
|
|
7
|
+
*/
|
|
8
|
+
import { smsChannel } from "@kalangu/core";
|
|
9
|
+
import { legacyTransport } from "./transport.js";
|
|
10
|
+
export * from "./transport.js";
|
|
11
|
+
const FINAL_FAILURES = new Set(["Failed", "Rejected", "AbsentSubscriber", "Expired"]);
|
|
12
|
+
export function africasTalkingSms(options) {
|
|
13
|
+
const transport = options.transport ?? httpTransport(options);
|
|
14
|
+
const id = options.id ?? "sms";
|
|
15
|
+
const path = options.path === undefined ? "/sms" : options.path;
|
|
16
|
+
const deliveryPath = options.deliveryPath === undefined ? "/sms/delivery" : options.deliveryPath;
|
|
17
|
+
const send = async (out) => {
|
|
18
|
+
await sendOne(transport, out, options.senderId);
|
|
19
|
+
};
|
|
20
|
+
const incoming = (req, agent) => handleIncoming(req, agent, id, send, options);
|
|
21
|
+
const routes = [];
|
|
22
|
+
if (path)
|
|
23
|
+
routes.push({ path, handle: incoming });
|
|
24
|
+
if (deliveryPath)
|
|
25
|
+
routes.push({ path: deliveryPath, handle: (req, agent) => handleDelivery(req, agent, options) });
|
|
26
|
+
const base = smsChannel({
|
|
27
|
+
id,
|
|
28
|
+
...(options.maxSegments !== undefined ? { budget: { maxSegments: options.maxSegments } } : {}),
|
|
29
|
+
send,
|
|
30
|
+
routes,
|
|
31
|
+
});
|
|
32
|
+
return {
|
|
33
|
+
...base,
|
|
34
|
+
send,
|
|
35
|
+
transport,
|
|
36
|
+
handler: (agent) => (req) => incoming(req, agent),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function httpTransport(options) {
|
|
40
|
+
if (!options.username || !options.apiKey) {
|
|
41
|
+
throw new TypeError("africasTalkingSms needs `username` and `apiKey`, or a custom `transport`");
|
|
42
|
+
}
|
|
43
|
+
if (options.sandbox && options.username !== "sandbox") {
|
|
44
|
+
console.warn('[kalangu] Africa\'s Talking sandbox requests normally use the username "sandbox"');
|
|
45
|
+
}
|
|
46
|
+
return legacyTransport({
|
|
47
|
+
username: options.username,
|
|
48
|
+
apiKey: options.apiKey,
|
|
49
|
+
...(options.sandbox !== undefined ? { sandbox: options.sandbox } : {}),
|
|
50
|
+
...(options.bulkSmsMode !== undefined ? { bulkSmsMode: options.bulkSmsMode } : {}),
|
|
51
|
+
...(options.enqueue !== undefined ? { enqueue: options.enqueue } : {}),
|
|
52
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
async function sendOne(transport, out, from) {
|
|
56
|
+
return transport.send({ to: [out.to], message: out.text, ...(from ? { from } : {}) });
|
|
57
|
+
}
|
|
58
|
+
/** Reads an incoming-message callback's form fields. */
|
|
59
|
+
export function parseIncoming(form) {
|
|
60
|
+
const field = fieldReader(form);
|
|
61
|
+
const message = {
|
|
62
|
+
from: field("from"),
|
|
63
|
+
to: field("to"),
|
|
64
|
+
text: field("text"),
|
|
65
|
+
id: field("id"),
|
|
66
|
+
date: field("date"),
|
|
67
|
+
};
|
|
68
|
+
if (field("linkId"))
|
|
69
|
+
message.linkId = field("linkId");
|
|
70
|
+
if (field("networkCode"))
|
|
71
|
+
message.networkCode = field("networkCode");
|
|
72
|
+
return message;
|
|
73
|
+
}
|
|
74
|
+
/** Reads a delivery-report callback's form fields. */
|
|
75
|
+
export function parseDeliveryReport(form) {
|
|
76
|
+
const field = fieldReader(form);
|
|
77
|
+
const report = {
|
|
78
|
+
id: field("id"),
|
|
79
|
+
phoneNumber: field("phoneNumber"),
|
|
80
|
+
networkCode: field("networkCode"),
|
|
81
|
+
status: field("status"),
|
|
82
|
+
};
|
|
83
|
+
if (field("failureReason"))
|
|
84
|
+
report.failureReason = field("failureReason");
|
|
85
|
+
return report;
|
|
86
|
+
}
|
|
87
|
+
async function handleIncoming(req, agent, channelId, send, options) {
|
|
88
|
+
if (req.method !== "POST")
|
|
89
|
+
return methodNotAllowed();
|
|
90
|
+
let message;
|
|
91
|
+
try {
|
|
92
|
+
message = parseIncoming(await req.formData());
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
agent.logger.warn("Unreadable SMS callback body", { error: String(err) });
|
|
96
|
+
return ok();
|
|
97
|
+
}
|
|
98
|
+
if (!message.from) {
|
|
99
|
+
agent.logger.warn("Incoming SMS without a sender", { id: message.id });
|
|
100
|
+
return ok();
|
|
101
|
+
}
|
|
102
|
+
// Answer the gateway now; the agent's reply goes out as a new message.
|
|
103
|
+
agent.background(async () => {
|
|
104
|
+
await options.onIncoming?.(message);
|
|
105
|
+
const outcome = await agent.handle({ channel: channelId, phone: message.from, input: message.text });
|
|
106
|
+
try {
|
|
107
|
+
await send({ to: message.from, text: outcome.text });
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
agent.logger.error("SMS reply failed", { phone: agent.mask(message.from), error: describe(err) });
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
return ok();
|
|
114
|
+
}
|
|
115
|
+
async function handleDelivery(req, agent, options) {
|
|
116
|
+
if (req.method !== "POST")
|
|
117
|
+
return methodNotAllowed();
|
|
118
|
+
try {
|
|
119
|
+
const report = parseDeliveryReport(await req.formData());
|
|
120
|
+
const fields = {
|
|
121
|
+
id: report.id,
|
|
122
|
+
phone: agent.mask(report.phoneNumber),
|
|
123
|
+
status: report.status,
|
|
124
|
+
...(report.failureReason ? { failureReason: report.failureReason } : {}),
|
|
125
|
+
};
|
|
126
|
+
if (FINAL_FAILURES.has(report.status))
|
|
127
|
+
agent.logger.warn("SMS not delivered", fields);
|
|
128
|
+
else
|
|
129
|
+
agent.logger.info("SMS delivery report", fields);
|
|
130
|
+
await options.onDeliveryReport?.(report);
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
agent.logger.error("Delivery report failed", { error: describe(err) });
|
|
134
|
+
}
|
|
135
|
+
return ok();
|
|
136
|
+
}
|
|
137
|
+
function fieldReader(form) {
|
|
138
|
+
return (name) => {
|
|
139
|
+
const value = form.get(name);
|
|
140
|
+
return typeof value === "string" ? value : "";
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function describe(err) {
|
|
144
|
+
if (err instanceof Error) {
|
|
145
|
+
const code = err.statusCode;
|
|
146
|
+
return code !== undefined ? `${err.name}: ${err.message} (statusCode ${String(code)})` : `${err.name}: ${err.message}`;
|
|
147
|
+
}
|
|
148
|
+
return String(err);
|
|
149
|
+
}
|
|
150
|
+
function ok() {
|
|
151
|
+
return new Response("OK", { status: 200, headers: { "content-type": "text/plain" } });
|
|
152
|
+
}
|
|
153
|
+
function methodNotAllowed() {
|
|
154
|
+
return new Response("Method not allowed", { status: 405, headers: { allow: "POST", "content-type": "text/plain" } });
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAA6C,MAAM,eAAe,CAAC;AACtF,OAAO,EAAE,eAAe,EAAsC,MAAM,gBAAgB,CAAC;AAErF,cAAc,gBAAgB,CAAC;AAmE/B,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,UAAU,EAAE,kBAAkB,EAAE,SAAS,CAAC,CAAC,CAAC;AAEtF,MAAM,UAAU,iBAAiB,CAAC,OAAiC;IACjE,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,aAAa,CAAC,OAAO,CAAC,CAAC;IAC9D,MAAM,EAAE,GAAG,OAAO,CAAC,EAAE,IAAI,KAAK,CAAC;IAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;IAChE,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC;IAEjG,MAAM,IAAI,GAAG,KA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CAAC;QAC1D,OAAO,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,OAAO,gBAAgB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC;IACzH,CAAC;IACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;AACrB,CAAC;AAED,SAAS,EAAE;IACT,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,YAAY,EAAE,EAAE,CAAC,CAAC;AACxF,CAAC;AAED,SAAS,gBAAgB;IACvB,OAAO,IAAI,QAAQ,CAAC,oBAAoB,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,YAAY,EAAE,EAAE,CAAC,CAAC;AACvH,CAAC"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP call that sends an SMS, behind a seam (docs/design.md §7.2) so
|
|
3
|
+
* the newer JSON bulk endpoint can replace the legacy one without touching
|
|
4
|
+
* the channel.
|
|
5
|
+
*/
|
|
6
|
+
export interface OutboundSms {
|
|
7
|
+
to: readonly string[];
|
|
8
|
+
message: string;
|
|
9
|
+
/** Sender ID or short code. */
|
|
10
|
+
from?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface SmsRecipient {
|
|
13
|
+
number: string;
|
|
14
|
+
status: string;
|
|
15
|
+
statusCode: number;
|
|
16
|
+
cost: string;
|
|
17
|
+
messageId: string;
|
|
18
|
+
}
|
|
19
|
+
export interface SendResult {
|
|
20
|
+
/** The gateway's summary line, e.g. "Sent to 1/1 Total Cost: KES 0.8000". */
|
|
21
|
+
message: string;
|
|
22
|
+
recipients: SmsRecipient[];
|
|
23
|
+
}
|
|
24
|
+
export interface SmsTransport {
|
|
25
|
+
send(sms: OutboundSms): Promise<SendResult>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A send the gateway refused, with its own codes kept verbatim, e.g.
|
|
29
|
+
* `statusCode: 409, status: "DoNotDisturbRejection"` for Nigeria's DND rules.
|
|
30
|
+
*/
|
|
31
|
+
export declare class SmsSendError extends Error {
|
|
32
|
+
readonly name = "SmsSendError";
|
|
33
|
+
readonly httpStatus: number | undefined;
|
|
34
|
+
readonly statusCode: number | undefined;
|
|
35
|
+
readonly status: string | undefined;
|
|
36
|
+
readonly recipients: SmsRecipient[];
|
|
37
|
+
constructor(message: string, details?: {
|
|
38
|
+
httpStatus?: number;
|
|
39
|
+
statusCode?: number;
|
|
40
|
+
status?: string;
|
|
41
|
+
recipients?: SmsRecipient[];
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** Recipient codes that mean the gateway accepted the message (not that it was delivered). */
|
|
45
|
+
export declare const ACCEPTED_STATUS_CODES: readonly number[];
|
|
46
|
+
export interface LegacyTransportOptions {
|
|
47
|
+
username: string;
|
|
48
|
+
apiKey: string;
|
|
49
|
+
/** Use api.sandbox.africastalking.com. Default false. */
|
|
50
|
+
sandbox?: boolean;
|
|
51
|
+
/** 1 bills as bulk SMS, matching the official SDK default. */
|
|
52
|
+
bulkSmsMode?: 0 | 1;
|
|
53
|
+
/** Passed only when set. */
|
|
54
|
+
enqueue?: boolean;
|
|
55
|
+
fetch?: typeof fetch;
|
|
56
|
+
}
|
|
57
|
+
export declare function legacyEndpoint(sandbox?: boolean): string;
|
|
58
|
+
/**
|
|
59
|
+
* `POST /version1/messaging`, form-encoded: the endpoint the official SDK
|
|
60
|
+
* uses and the sandbox supports. Success is HTTP 201.
|
|
61
|
+
*/
|
|
62
|
+
export declare function legacyTransport(options: LegacyTransportOptions): SmsTransport;
|
|
63
|
+
/** Reads the legacy endpoint's JSON response. */
|
|
64
|
+
export declare function parseSendResponse(raw: string, httpStatus?: number): SendResult;
|
|
65
|
+
//# sourceMappingURL=transport.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,SAAS,MAAM,EAAE,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,+BAA+B;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,UAAU;IACzB,6EAA6E;IAC7E,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,YAAY,EAAE,CAAC;CAC5B;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC7C;AAED;;;GAGG;AACH,qBAAa,YAAa,SAAQ,KAAK;IACrC,SAAkB,IAAI,kBAAkB;IACxC,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC;IAEpC,YACE,OAAO,EAAE,MAAM,EACf,OAAO,GAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,YAAY,EAAE,CAAA;KAAO,EAOzG;CACF;AAED,8FAA8F;AAC9F,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAAoB,CAAC;AAExE,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,8DAA8D;IAC9D,WAAW,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IACpB,4BAA4B;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,wBAAgB,cAAc,CAAC,OAAO,UAAQ,GAAG,MAAM,CAEtD;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,YAAY,CAgD7E;AAED,iDAAiD;AACjD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,SAAM,GAAG,UAAU,CAsB3E"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP call that sends an SMS, behind a seam (docs/design.md §7.2) so
|
|
3
|
+
* the newer JSON bulk endpoint can replace the legacy one without touching
|
|
4
|
+
* the channel.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* A send the gateway refused, with its own codes kept verbatim, e.g.
|
|
8
|
+
* `statusCode: 409, status: "DoNotDisturbRejection"` for Nigeria's DND rules.
|
|
9
|
+
*/
|
|
10
|
+
export class SmsSendError extends Error {
|
|
11
|
+
name = "SmsSendError";
|
|
12
|
+
httpStatus;
|
|
13
|
+
statusCode;
|
|
14
|
+
status;
|
|
15
|
+
recipients;
|
|
16
|
+
constructor(message, details = {}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.httpStatus = details.httpStatus;
|
|
19
|
+
this.statusCode = details.statusCode;
|
|
20
|
+
this.status = details.status;
|
|
21
|
+
this.recipients = details.recipients ?? [];
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Recipient codes that mean the gateway accepted the message (not that it was delivered). */
|
|
25
|
+
export const ACCEPTED_STATUS_CODES = [100, 101, 102];
|
|
26
|
+
export function legacyEndpoint(sandbox = false) {
|
|
27
|
+
return `https://api.${sandbox ? "sandbox." : ""}africastalking.com/version1/messaging`;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* `POST /version1/messaging`, form-encoded: the endpoint the official SDK
|
|
31
|
+
* uses and the sandbox supports. Success is HTTP 201.
|
|
32
|
+
*/
|
|
33
|
+
export function legacyTransport(options) {
|
|
34
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
35
|
+
const url = legacyEndpoint(options.sandbox);
|
|
36
|
+
return {
|
|
37
|
+
async send(sms) {
|
|
38
|
+
if (sms.to.length === 0)
|
|
39
|
+
throw new TypeError("An SMS needs at least one recipient");
|
|
40
|
+
const body = new URLSearchParams({
|
|
41
|
+
username: options.username,
|
|
42
|
+
to: sms.to.join(","),
|
|
43
|
+
message: sms.message,
|
|
44
|
+
bulkSMSMode: String(options.bulkSmsMode ?? 1),
|
|
45
|
+
});
|
|
46
|
+
if (sms.from)
|
|
47
|
+
body.set("from", sms.from);
|
|
48
|
+
if (options.enqueue !== undefined)
|
|
49
|
+
body.set("enqueue", options.enqueue ? "1" : "0");
|
|
50
|
+
const res = await doFetch(url, {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: {
|
|
53
|
+
apiKey: options.apiKey,
|
|
54
|
+
accept: "application/json",
|
|
55
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
56
|
+
},
|
|
57
|
+
body,
|
|
58
|
+
});
|
|
59
|
+
const raw = await res.text();
|
|
60
|
+
if (res.status !== 201 && res.status !== 200) {
|
|
61
|
+
throw new SmsSendError(`SMS send failed with HTTP ${res.status}: ${raw.slice(0, 200)}`, {
|
|
62
|
+
httpStatus: res.status,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const result = parseSendResponse(raw, res.status);
|
|
66
|
+
const refused = result.recipients.filter((r) => !ACCEPTED_STATUS_CODES.includes(r.statusCode));
|
|
67
|
+
if (result.recipients.length === 0) {
|
|
68
|
+
throw new SmsSendError(`SMS send accepted no recipients: ${result.message}`, { httpStatus: res.status });
|
|
69
|
+
}
|
|
70
|
+
if (refused.length > 0) {
|
|
71
|
+
const first = refused[0];
|
|
72
|
+
throw new SmsSendError(`SMS refused for ${refused.length} recipient(s): ${first.statusCode} ${first.status}`, { httpStatus: res.status, statusCode: first.statusCode, status: first.status, recipients: result.recipients });
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Reads the legacy endpoint's JSON response. */
|
|
79
|
+
export function parseSendResponse(raw, httpStatus = 201) {
|
|
80
|
+
let json;
|
|
81
|
+
try {
|
|
82
|
+
json = JSON.parse(raw);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
throw new SmsSendError(`SMS send returned a body that isn't JSON: ${raw.slice(0, 200)}`, { httpStatus });
|
|
86
|
+
}
|
|
87
|
+
const data = json.SMSMessageData;
|
|
88
|
+
if (!data || typeof data !== "object") {
|
|
89
|
+
throw new SmsSendError("SMS send response has no SMSMessageData", { httpStatus });
|
|
90
|
+
}
|
|
91
|
+
const recipients = Array.isArray(data.Recipients) ? data.Recipients : [];
|
|
92
|
+
return {
|
|
93
|
+
message: typeof data.Message === "string" ? data.Message : "",
|
|
94
|
+
recipients: recipients.map((r) => ({
|
|
95
|
+
number: String(r["number"] ?? ""),
|
|
96
|
+
status: String(r["status"] ?? ""),
|
|
97
|
+
statusCode: Number(r["statusCode"]),
|
|
98
|
+
cost: String(r["cost"] ?? ""),
|
|
99
|
+
messageId: String(r["messageId"] ?? ""),
|
|
100
|
+
})),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=transport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../src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,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;IACzE,OAAO;QACL,OAAO,EAAE,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;QAC7D,UAAU,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAA0B,EAAE,EAAE,CAAC,CAAC;YAC1D,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;YACjC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;YACjC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;YACnC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;YAC7B,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;SACxC,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kalangu/sms",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Africa's Talking SMS adapter for Kalangu agents.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"sms",
|
|
7
|
+
"africastalking",
|
|
8
|
+
"africas-talking",
|
|
9
|
+
"agents",
|
|
10
|
+
"ai",
|
|
11
|
+
"africa"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Abdoullah Ndao",
|
|
15
|
+
"homepage": "https://github.com/utachicodes/kalangu/tree/main/packages/sms#readme",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/utachicodes/kalangu.git",
|
|
19
|
+
"directory": "packages/sms"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/utachicodes/kalangu/issues"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=20"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"files": [
|
|
37
|
+
"dist",
|
|
38
|
+
"src",
|
|
39
|
+
"README.md",
|
|
40
|
+
"LICENSE"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"tag": "alpha"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@kalangu/core": "0.1.0-alpha.0"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsc -p tsconfig.build.json",
|
|
51
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
52
|
+
"test": "vitest run"
|
|
53
|
+
}
|
|
6
54
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Africa's Talking SMS adapter (docs/design.md §7.2): sends budgeted
|
|
3
|
+
* messages, receives incoming messages, and logs delivery reports.
|
|
4
|
+
*
|
|
5
|
+
* Callbacks are not signed. Treat them as untrusted input: use a hard-to-
|
|
6
|
+
* guess path and, where you can, allow only the gateway's IP addresses.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { smsChannel, type Channel, type Route, type RouteAgent } from "@kalangu/core";
|
|
10
|
+
import { legacyTransport, type SendResult, type SmsTransport } from "./transport.js";
|
|
11
|
+
|
|
12
|
+
export * from "./transport.js";
|
|
13
|
+
|
|
14
|
+
export interface AfricasTalkingSmsOptions {
|
|
15
|
+
/** Channel id. Default "sms". */
|
|
16
|
+
id?: string;
|
|
17
|
+
/** Your Africa's Talking username ("sandbox" in the sandbox). */
|
|
18
|
+
username?: string;
|
|
19
|
+
apiKey?: string;
|
|
20
|
+
/** Registered sender ID or short code. */
|
|
21
|
+
senderId?: string;
|
|
22
|
+
/** Incoming-message callback path, or false for none. Default "/sms". */
|
|
23
|
+
path?: string | false;
|
|
24
|
+
/** Delivery-report callback path, or false for none. Default "/sms/delivery". */
|
|
25
|
+
deliveryPath?: string | false;
|
|
26
|
+
/** Use the sandbox API. Default false. */
|
|
27
|
+
sandbox?: boolean;
|
|
28
|
+
/** Default 1, as in the official SDK. */
|
|
29
|
+
bulkSmsMode?: 0 | 1;
|
|
30
|
+
/** Passed to the gateway only when set. */
|
|
31
|
+
enqueue?: boolean;
|
|
32
|
+
/** Segment cap per message. Default 4. Longer replies are an error, never cut. */
|
|
33
|
+
maxSegments?: number;
|
|
34
|
+
/** Replaces the HTTP transport, e.g. for the JSON bulk endpoint or tests. */
|
|
35
|
+
transport?: SmsTransport;
|
|
36
|
+
fetch?: typeof fetch;
|
|
37
|
+
onDeliveryReport?: (report: DeliveryReport) => void | Promise<void>;
|
|
38
|
+
onIncoming?: (message: IncomingSms) => void | Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface IncomingSms {
|
|
42
|
+
from: string;
|
|
43
|
+
to: string;
|
|
44
|
+
text: string;
|
|
45
|
+
id: string;
|
|
46
|
+
date: string;
|
|
47
|
+
linkId?: string;
|
|
48
|
+
networkCode?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type DeliveryStatus =
|
|
52
|
+
| "Sent"
|
|
53
|
+
| "Submitted"
|
|
54
|
+
| "Buffered"
|
|
55
|
+
| "Rejected"
|
|
56
|
+
| "Success"
|
|
57
|
+
| "Failed"
|
|
58
|
+
| "AbsentSubscriber"
|
|
59
|
+
| "Expired"
|
|
60
|
+
| (string & {});
|
|
61
|
+
|
|
62
|
+
export interface DeliveryReport {
|
|
63
|
+
/** Matches `messageId` from the send response. */
|
|
64
|
+
id: string;
|
|
65
|
+
phoneNumber: string;
|
|
66
|
+
networkCode: string;
|
|
67
|
+
status: DeliveryStatus;
|
|
68
|
+
failureReason?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export type AfricasTalkingSmsChannel = Channel & {
|
|
72
|
+
send(out: { to: string; text: string }): Promise<void>;
|
|
73
|
+
/** The transport, for sending outside a conversation. */
|
|
74
|
+
readonly transport: SmsTransport;
|
|
75
|
+
/** Incoming-message handler, for mounting it yourself. */
|
|
76
|
+
handler(agent: RouteAgent): (req: Request) => Promise<Response>;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const FINAL_FAILURES = new Set(["Failed", "Rejected", "AbsentSubscriber", "Expired"]);
|
|
80
|
+
|
|
81
|
+
export function africasTalkingSms(options: AfricasTalkingSmsOptions): AfricasTalkingSmsChannel {
|
|
82
|
+
const transport = options.transport ?? httpTransport(options);
|
|
83
|
+
const id = options.id ?? "sms";
|
|
84
|
+
const path = options.path === undefined ? "/sms" : options.path;
|
|
85
|
+
const deliveryPath = options.deliveryPath === undefined ? "/sms/delivery" : options.deliveryPath;
|
|
86
|
+
|
|
87
|
+
const send = async (out: { to: string; text: string }): Promise<void> => {
|
|
88
|
+
await sendOne(transport, out, options.senderId);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const incoming = (req: Request, agent: RouteAgent) => handleIncoming(req, agent, id, send, options);
|
|
92
|
+
const routes: Route[] = [];
|
|
93
|
+
if (path) routes.push({ path, handle: incoming });
|
|
94
|
+
if (deliveryPath) routes.push({ path: deliveryPath, handle: (req, agent) => handleDelivery(req, agent, options) });
|
|
95
|
+
|
|
96
|
+
const base = smsChannel({
|
|
97
|
+
id,
|
|
98
|
+
...(options.maxSegments !== undefined ? { budget: { maxSegments: options.maxSegments } } : {}),
|
|
99
|
+
send,
|
|
100
|
+
routes,
|
|
101
|
+
});
|
|
102
|
+
return {
|
|
103
|
+
...base,
|
|
104
|
+
send,
|
|
105
|
+
transport,
|
|
106
|
+
handler: (agent) => (req) => incoming(req, agent),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function httpTransport(options: AfricasTalkingSmsOptions): SmsTransport {
|
|
111
|
+
if (!options.username || !options.apiKey) {
|
|
112
|
+
throw new TypeError("africasTalkingSms needs `username` and `apiKey`, or a custom `transport`");
|
|
113
|
+
}
|
|
114
|
+
if (options.sandbox && options.username !== "sandbox") {
|
|
115
|
+
console.warn('[kalangu] Africa\'s Talking sandbox requests normally use the username "sandbox"');
|
|
116
|
+
}
|
|
117
|
+
return legacyTransport({
|
|
118
|
+
username: options.username,
|
|
119
|
+
apiKey: options.apiKey,
|
|
120
|
+
...(options.sandbox !== undefined ? { sandbox: options.sandbox } : {}),
|
|
121
|
+
...(options.bulkSmsMode !== undefined ? { bulkSmsMode: options.bulkSmsMode } : {}),
|
|
122
|
+
...(options.enqueue !== undefined ? { enqueue: options.enqueue } : {}),
|
|
123
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function sendOne(
|
|
128
|
+
transport: SmsTransport,
|
|
129
|
+
out: { to: string; text: string },
|
|
130
|
+
from: string | undefined,
|
|
131
|
+
): Promise<SendResult> {
|
|
132
|
+
return transport.send({ to: [out.to], message: out.text, ...(from ? { from } : {}) });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Reads an incoming-message callback's form fields. */
|
|
136
|
+
export function parseIncoming(form: FormData | URLSearchParams): IncomingSms {
|
|
137
|
+
const field = fieldReader(form);
|
|
138
|
+
const message: IncomingSms = {
|
|
139
|
+
from: field("from"),
|
|
140
|
+
to: field("to"),
|
|
141
|
+
text: field("text"),
|
|
142
|
+
id: field("id"),
|
|
143
|
+
date: field("date"),
|
|
144
|
+
};
|
|
145
|
+
if (field("linkId")) message.linkId = field("linkId");
|
|
146
|
+
if (field("networkCode")) message.networkCode = field("networkCode");
|
|
147
|
+
return message;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Reads a delivery-report callback's form fields. */
|
|
151
|
+
export function parseDeliveryReport(form: FormData | URLSearchParams): DeliveryReport {
|
|
152
|
+
const field = fieldReader(form);
|
|
153
|
+
const report: DeliveryReport = {
|
|
154
|
+
id: field("id"),
|
|
155
|
+
phoneNumber: field("phoneNumber"),
|
|
156
|
+
networkCode: field("networkCode"),
|
|
157
|
+
status: field("status"),
|
|
158
|
+
};
|
|
159
|
+
if (field("failureReason")) report.failureReason = field("failureReason");
|
|
160
|
+
return report;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function handleIncoming(
|
|
164
|
+
req: Request,
|
|
165
|
+
agent: RouteAgent,
|
|
166
|
+
channelId: string,
|
|
167
|
+
send: (out: { to: string; text: string }) => Promise<void>,
|
|
168
|
+
options: AfricasTalkingSmsOptions,
|
|
169
|
+
): Promise<Response> {
|
|
170
|
+
if (req.method !== "POST") return methodNotAllowed();
|
|
171
|
+
|
|
172
|
+
let message: IncomingSms;
|
|
173
|
+
try {
|
|
174
|
+
message = parseIncoming(await req.formData());
|
|
175
|
+
} catch (err) {
|
|
176
|
+
agent.logger.warn("Unreadable SMS callback body", { error: String(err) });
|
|
177
|
+
return ok();
|
|
178
|
+
}
|
|
179
|
+
if (!message.from) {
|
|
180
|
+
agent.logger.warn("Incoming SMS without a sender", { id: message.id });
|
|
181
|
+
return ok();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Answer the gateway now; the agent's reply goes out as a new message.
|
|
185
|
+
agent.background(async () => {
|
|
186
|
+
await options.onIncoming?.(message);
|
|
187
|
+
const outcome = await agent.handle({ channel: channelId, phone: message.from, input: message.text });
|
|
188
|
+
try {
|
|
189
|
+
await send({ to: message.from, text: outcome.text });
|
|
190
|
+
} catch (err) {
|
|
191
|
+
agent.logger.error("SMS reply failed", { phone: agent.mask(message.from), error: describe(err) });
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
return ok();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function handleDelivery(req: Request, agent: RouteAgent, options: AfricasTalkingSmsOptions): Promise<Response> {
|
|
198
|
+
if (req.method !== "POST") return methodNotAllowed();
|
|
199
|
+
try {
|
|
200
|
+
const report = parseDeliveryReport(await req.formData());
|
|
201
|
+
const fields = {
|
|
202
|
+
id: report.id,
|
|
203
|
+
phone: agent.mask(report.phoneNumber),
|
|
204
|
+
status: report.status,
|
|
205
|
+
...(report.failureReason ? { failureReason: report.failureReason } : {}),
|
|
206
|
+
};
|
|
207
|
+
if (FINAL_FAILURES.has(report.status)) agent.logger.warn("SMS not delivered", fields);
|
|
208
|
+
else agent.logger.info("SMS delivery report", fields);
|
|
209
|
+
await options.onDeliveryReport?.(report);
|
|
210
|
+
} catch (err) {
|
|
211
|
+
agent.logger.error("Delivery report failed", { error: describe(err) });
|
|
212
|
+
}
|
|
213
|
+
return ok();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function fieldReader(form: FormData | URLSearchParams) {
|
|
217
|
+
return (name: string) => {
|
|
218
|
+
const value = form.get(name);
|
|
219
|
+
return typeof value === "string" ? value : "";
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function describe(err: unknown): string {
|
|
224
|
+
if (err instanceof Error) {
|
|
225
|
+
const code = (err as { statusCode?: unknown }).statusCode;
|
|
226
|
+
return code !== undefined ? `${err.name}: ${err.message} (statusCode ${String(code)})` : `${err.name}: ${err.message}`;
|
|
227
|
+
}
|
|
228
|
+
return String(err);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function ok(): Response {
|
|
232
|
+
return new Response("OK", { status: 200, headers: { "content-type": "text/plain" } });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function methodNotAllowed(): Response {
|
|
236
|
+
return new Response("Method not allowed", { status: 405, headers: { allow: "POST", "content-type": "text/plain" } });
|
|
237
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP call that sends an SMS, behind a seam (docs/design.md §7.2) so
|
|
3
|
+
* the newer JSON bulk endpoint can replace the legacy one without touching
|
|
4
|
+
* the channel.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface OutboundSms {
|
|
8
|
+
to: readonly string[];
|
|
9
|
+
message: string;
|
|
10
|
+
/** Sender ID or short code. */
|
|
11
|
+
from?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SmsRecipient {
|
|
15
|
+
number: string;
|
|
16
|
+
status: string;
|
|
17
|
+
statusCode: number;
|
|
18
|
+
cost: string;
|
|
19
|
+
messageId: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface SendResult {
|
|
23
|
+
/** The gateway's summary line, e.g. "Sent to 1/1 Total Cost: KES 0.8000". */
|
|
24
|
+
message: string;
|
|
25
|
+
recipients: SmsRecipient[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface SmsTransport {
|
|
29
|
+
send(sms: OutboundSms): Promise<SendResult>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A send the gateway refused, with its own codes kept verbatim, e.g.
|
|
34
|
+
* `statusCode: 409, status: "DoNotDisturbRejection"` for Nigeria's DND rules.
|
|
35
|
+
*/
|
|
36
|
+
export class SmsSendError extends Error {
|
|
37
|
+
override readonly name = "SmsSendError";
|
|
38
|
+
readonly httpStatus: number | undefined;
|
|
39
|
+
readonly statusCode: number | undefined;
|
|
40
|
+
readonly status: string | undefined;
|
|
41
|
+
readonly recipients: SmsRecipient[];
|
|
42
|
+
|
|
43
|
+
constructor(
|
|
44
|
+
message: string,
|
|
45
|
+
details: { httpStatus?: number; statusCode?: number; status?: string; recipients?: SmsRecipient[] } = {},
|
|
46
|
+
) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.httpStatus = details.httpStatus;
|
|
49
|
+
this.statusCode = details.statusCode;
|
|
50
|
+
this.status = details.status;
|
|
51
|
+
this.recipients = details.recipients ?? [];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Recipient codes that mean the gateway accepted the message (not that it was delivered). */
|
|
56
|
+
export const ACCEPTED_STATUS_CODES: readonly number[] = [100, 101, 102];
|
|
57
|
+
|
|
58
|
+
export interface LegacyTransportOptions {
|
|
59
|
+
username: string;
|
|
60
|
+
apiKey: string;
|
|
61
|
+
/** Use api.sandbox.africastalking.com. Default false. */
|
|
62
|
+
sandbox?: boolean;
|
|
63
|
+
/** 1 bills as bulk SMS, matching the official SDK default. */
|
|
64
|
+
bulkSmsMode?: 0 | 1;
|
|
65
|
+
/** Passed only when set. */
|
|
66
|
+
enqueue?: boolean;
|
|
67
|
+
fetch?: typeof fetch;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function legacyEndpoint(sandbox = false): string {
|
|
71
|
+
return `https://api.${sandbox ? "sandbox." : ""}africastalking.com/version1/messaging`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* `POST /version1/messaging`, form-encoded: the endpoint the official SDK
|
|
76
|
+
* uses and the sandbox supports. Success is HTTP 201.
|
|
77
|
+
*/
|
|
78
|
+
export function legacyTransport(options: LegacyTransportOptions): SmsTransport {
|
|
79
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
80
|
+
const url = legacyEndpoint(options.sandbox);
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
async send(sms) {
|
|
84
|
+
if (sms.to.length === 0) throw new TypeError("An SMS needs at least one recipient");
|
|
85
|
+
const body = new URLSearchParams({
|
|
86
|
+
username: options.username,
|
|
87
|
+
to: sms.to.join(","),
|
|
88
|
+
message: sms.message,
|
|
89
|
+
bulkSMSMode: String(options.bulkSmsMode ?? 1),
|
|
90
|
+
});
|
|
91
|
+
if (sms.from) body.set("from", sms.from);
|
|
92
|
+
if (options.enqueue !== undefined) body.set("enqueue", options.enqueue ? "1" : "0");
|
|
93
|
+
|
|
94
|
+
const res = await doFetch(url, {
|
|
95
|
+
method: "POST",
|
|
96
|
+
headers: {
|
|
97
|
+
apiKey: options.apiKey,
|
|
98
|
+
accept: "application/json",
|
|
99
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
100
|
+
},
|
|
101
|
+
body,
|
|
102
|
+
});
|
|
103
|
+
const raw = await res.text();
|
|
104
|
+
|
|
105
|
+
if (res.status !== 201 && res.status !== 200) {
|
|
106
|
+
throw new SmsSendError(`SMS send failed with HTTP ${res.status}: ${raw.slice(0, 200)}`, {
|
|
107
|
+
httpStatus: res.status,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const result = parseSendResponse(raw, res.status);
|
|
112
|
+
const refused = result.recipients.filter((r) => !ACCEPTED_STATUS_CODES.includes(r.statusCode));
|
|
113
|
+
if (result.recipients.length === 0) {
|
|
114
|
+
throw new SmsSendError(`SMS send accepted no recipients: ${result.message}`, { httpStatus: res.status });
|
|
115
|
+
}
|
|
116
|
+
if (refused.length > 0) {
|
|
117
|
+
const first = refused[0] as SmsRecipient;
|
|
118
|
+
throw new SmsSendError(
|
|
119
|
+
`SMS refused for ${refused.length} recipient(s): ${first.statusCode} ${first.status}`,
|
|
120
|
+
{ httpStatus: res.status, statusCode: first.statusCode, status: first.status, recipients: result.recipients },
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Reads the legacy endpoint's JSON response. */
|
|
129
|
+
export function parseSendResponse(raw: string, httpStatus = 201): SendResult {
|
|
130
|
+
let json: unknown;
|
|
131
|
+
try {
|
|
132
|
+
json = JSON.parse(raw);
|
|
133
|
+
} catch {
|
|
134
|
+
throw new SmsSendError(`SMS send returned a body that isn't JSON: ${raw.slice(0, 200)}`, { httpStatus });
|
|
135
|
+
}
|
|
136
|
+
const data = (json as { SMSMessageData?: { Message?: unknown; Recipients?: unknown } }).SMSMessageData;
|
|
137
|
+
if (!data || typeof data !== "object") {
|
|
138
|
+
throw new SmsSendError("SMS send response has no SMSMessageData", { httpStatus });
|
|
139
|
+
}
|
|
140
|
+
const recipients = Array.isArray(data.Recipients) ? data.Recipients : [];
|
|
141
|
+
return {
|
|
142
|
+
message: typeof data.Message === "string" ? data.Message : "",
|
|
143
|
+
recipients: recipients.map((r: Record<string, unknown>) => ({
|
|
144
|
+
number: String(r["number"] ?? ""),
|
|
145
|
+
status: String(r["status"] ?? ""),
|
|
146
|
+
statusCode: Number(r["statusCode"]),
|
|
147
|
+
cost: String(r["cost"] ?? ""),
|
|
148
|
+
messageId: String(r["messageId"] ?? ""),
|
|
149
|
+
})),
|
|
150
|
+
};
|
|
151
|
+
}
|