@12-apps/messaging 1.0.0 → 1.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/README.md +61 -1
- package/dist/{channel-Cs_vLGl_.d.ts → channel-HEnMO02x.d.ts} +45 -1
- package/dist/{chunk-R3DKM2IV.js → chunk-LNVSQ5IQ.js} +13 -1
- package/dist/chunk-LNVSQ5IQ.js.map +1 -0
- package/dist/{chunk-Y7MG2UDQ.js → chunk-NKH5TCSO.js} +20 -1
- package/dist/chunk-NKH5TCSO.js.map +1 -0
- package/dist/{chunk-72TDAQUW.js → chunk-S5PJXMXM.js} +2 -2
- package/dist/{engine-B5EPo66m.d.ts → engine-DAfm8V5S.d.ts} +39 -2
- package/dist/index.d.ts +30 -5
- package/dist/index.js +86 -2
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +2 -2
- package/dist/whatsapp/index.d.ts +55 -5
- package/dist/whatsapp/index.js +175 -2
- package/dist/whatsapp/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/channel.ts +58 -0
- package/src/core/engine.ts +9 -0
- package/src/core/errors.ts +31 -0
- package/src/core/inbox.ts +22 -0
- package/src/core/media.ts +84 -0
- package/src/core/memory-store.ts +4 -0
- package/src/core/ports.ts +18 -1
- package/src/core/prisma-store.ts +4 -1
- package/src/core/store.ts +6 -0
- package/src/index.ts +7 -0
- package/src/whatsapp/graph.ts +53 -5
- package/src/whatsapp/index.ts +16 -1
- package/src/whatsapp/media.ts +205 -0
- package/dist/chunk-R3DKM2IV.js.map +0 -1
- package/dist/chunk-Y7MG2UDQ.js.map +0 -1
- /package/dist/{chunk-72TDAQUW.js.map → chunk-S5PJXMXM.js.map} +0 -0
package/README.md
CHANGED
|
@@ -38,6 +38,7 @@ messaging.process-delivery (a job)
|
|
|
38
38
|
├─ parse the stored bytes through the channel's adapter
|
|
39
39
|
├─ per event, resolve the tenant: the event's account against the connections
|
|
40
40
|
│ unknown, revoked or in error ............. dropped (the edge already said 200)
|
|
41
|
+
│ unknown only, with hooks.onUnclaimedEvents handed to the host (see below)
|
|
41
42
|
├─ message → create or re-open the conversation, update lastInboundAt,
|
|
42
43
|
│ store the message (a known channel id is a no-op),
|
|
43
44
|
│ then the host's onInboundMessage({ conversation, message })
|
|
@@ -50,6 +51,29 @@ messaging.process-delivery (a job)
|
|
|
50
51
|
The tenant is never taken from the URL: a channel like WhatsApp posts every
|
|
51
52
|
connected account's events to the one callback configured on the app.
|
|
52
53
|
|
|
54
|
+
**A number nobody connected.** A host whose OWN number lives on the same app
|
|
55
|
+
(a platform notification number: its confirmation replies, its opt-outs, its
|
|
56
|
+
delivery receipts) passes `hooks.onUnclaimedEvents(channel, events)`. It is
|
|
57
|
+
handed, once per processed delivery, the parsed events of every account no
|
|
58
|
+
connection row names: already signature-checked and persisted, and stored
|
|
59
|
+
nowhere here. A revoked or errored account is a tenant's and is never handed
|
|
60
|
+
over. A throw settles the delivery `FAILED` and the reconciliation sweep runs
|
|
61
|
+
it again, so the handler is idempotent on the provider's message id. Without
|
|
62
|
+
the hook those events are dropped, as before.
|
|
63
|
+
|
|
64
|
+
**Filter on your OWN account id.** The hook is handed every account the app
|
|
65
|
+
posts for that no connection names — not only the platform's number. A host
|
|
66
|
+
that wants its own number's events keeps `event.accountId === <its phone
|
|
67
|
+
number id>` and drops the rest; anything else would act on a stranger's
|
|
68
|
+
messages.
|
|
69
|
+
|
|
70
|
+
**Meta's `wa_id` is not always the stored number.** For many Brazilian mobiles
|
|
71
|
+
Meta reports the sender WITHOUT the 9th digit (`55 11 8765-4321` for
|
|
72
|
+
`+55 11 98765-4321`). A host matching a reply to a stored number (a consent
|
|
73
|
+
reply, `@12-apps/notifications`' `applyInbound`) normalises `from` first: for a
|
|
74
|
+
`55` number with a 2-digit area code and an 8-digit subscriber starting 6–9,
|
|
75
|
+
insert the `9` — or the reply misses the account that sent it.
|
|
76
|
+
|
|
53
77
|
**Opt-out.** On WhatsApp, a message that is exactly `PARAR`, `SAIR`, `STOP` or
|
|
54
78
|
`CANCELAR` — case- and accent-insensitive, ignoring punctuation and emoji
|
|
55
79
|
around it ("PARAR.", "Parar!") — opts the contact out, as does Meta's own
|
|
@@ -101,6 +125,7 @@ interface ChannelAdapter {
|
|
|
101
125
|
verify({ rawBody, header }): boolean; // fail closed
|
|
102
126
|
parse(rawBody): NormalizedEvent[]; // message | status | opt_out
|
|
103
127
|
send({ credential, accountId, to, content }): Promise<{ externalId }>;
|
|
128
|
+
fetchMedia?({ credential, accountId, mediaId, maxBytes }): Promise<{ bytes, mimeType, size }>;
|
|
104
129
|
readonly policy: SendPolicy; // when free-form sends are allowed
|
|
105
130
|
}
|
|
106
131
|
```
|
|
@@ -111,12 +136,47 @@ channel. `OutboundContent` is `TEXT`, `BUTTONS` or `LIST`; an adapter maps it
|
|
|
111
136
|
to its wire. `serviceWindowPolicy(ms)` and `OPEN_SEND_POLICY` cover the two
|
|
112
137
|
policies known so far.
|
|
113
138
|
|
|
139
|
+
## Downloading media
|
|
140
|
+
|
|
141
|
+
An inbound voice note is stored with the channel's media id only, never its
|
|
142
|
+
bytes. A host that needs them (to transcribe the note) asks the engine:
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
const { bytes, mimeType, size } = await engine.downloadMedia(tenantId, messageId, { maxBytes, timeoutMs });
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The message must be the tenant's, an inbound `AUDIO` with a media id, and its
|
|
149
|
+
connection `CONNECTED`; the sealed credential is opened exactly as a send opens
|
|
150
|
+
it and handed only to the adapter's optional `fetchMedia`. Every refusal is a
|
|
151
|
+
`MessagingMediaError` with a code: `BAD_OPTIONS` (a `maxBytes` or `timeoutMs`
|
|
152
|
+
that is not a positive safe integer), `NOT_FOUND`, `NO_MEDIA`,
|
|
153
|
+
`UNKNOWN_CHANNEL`, `UNSUPPORTED` (the adapter has no `fetchMedia`, or the store
|
|
154
|
+
no `getMessage`), `NOT_CONNECTED`, `TOO_LARGE`, `TIMEOUT`, `CHANNEL_FAILED`.
|
|
155
|
+
`MessagingStore.getMessage(tenantId, id)` is optional, so a host's own store
|
|
156
|
+
keeps compiling; both shipped stores implement it. None carries the credential: the engine scrubs it even from a
|
|
157
|
+
channel error that echoes it.
|
|
158
|
+
|
|
159
|
+
The WhatsApp adapter looks the media id up on the Graph API, then downloads the
|
|
160
|
+
URL Meta returns, with the token in the Authorization header and nowhere else.
|
|
161
|
+
That URL must be https, with no explicit port, on a Meta media host (`graph.mediaHosts`, default
|
|
162
|
+
`DEFAULT_META_MEDIA_HOSTS`: `lookaside.fbsbx.com`, `*.fbcdn.net`,
|
|
163
|
+
`*.whatsapp.net`), a redirect is refused rather than followed, and the cap
|
|
164
|
+
(`maxBytes`, default 16 MiB) is checked against the declared `file_size` before
|
|
165
|
+
the download and against the bytes actually read during it. The whole download
|
|
166
|
+
has a deadline (`timeoutMs`, default 30 s, `DEFAULT_MEDIA_TIMEOUT_MS`): both
|
|
167
|
+
calls get an abort signal, and a body still streaming at the deadline is
|
|
168
|
+
cancelled.
|
|
169
|
+
|
|
170
|
+
**The bytes live only in the returned memory.** The package stores none of
|
|
171
|
+
them, and the host decides retention: none. Transcribe, store the transcript
|
|
172
|
+
with `setTranscript` (it is deleted with the text), and drop the buffer.
|
|
173
|
+
|
|
114
174
|
## Subpaths
|
|
115
175
|
|
|
116
176
|
| subpath | what |
|
|
117
177
|
|---|---|
|
|
118
178
|
| `@12-apps/messaging` | `createMessagingEngine`, the ports, the store port with `createPrismaMessagingStore` and `createMemoryMessagingStore`, the adapter interface, the errors, the types. |
|
|
119
|
-
| `@12-apps/messaging/whatsapp` | `createWhatsAppAdapter`, and standalone: `verifyMetaSignature`, `verifyMetaSubscription`, `parseWhatsAppPayload`, `parseWhatsAppStatuses`, `isOptOutText`, the Graph sender, and the Embedded Signup helpers `exchangeSignupCode`, `readSignupAccounts`, `subscribeAppToWaba`. |
|
|
179
|
+
| `@12-apps/messaging/whatsapp` | `createWhatsAppAdapter`, and standalone: `verifyMetaSignature`, `verifyMetaSubscription`, `parseWhatsAppPayload`, `parseWhatsAppStatuses`, `isOptOutText`, the Graph sender, `downloadWhatsAppMedia`, and the Embedded Signup helpers `exchangeSignupCode`, `readSignupAccounts`, `subscribeAppToWaba`. |
|
|
120
180
|
| `@12-apps/messaging/server` | `createApiMessaging` (the webhook route pair, in `@12-apps/wiring`'s `WireRoute` shape) and `MESSAGING_JOBS`. |
|
|
121
181
|
| `@12-apps/messaging/manifest`, `/manifest/server` | The wiring manifests. |
|
|
122
182
|
|
|
@@ -240,6 +240,15 @@ interface ChannelAdapter {
|
|
|
240
240
|
send(input: ChannelSendInput): Promise<{
|
|
241
241
|
externalId: string;
|
|
242
242
|
}>;
|
|
243
|
+
/**
|
|
244
|
+
* Download one inbound message's media (a voice note) by the channel's media
|
|
245
|
+
* id, into memory. OPTIONAL: a channel with no media leaves it out, and the
|
|
246
|
+
* engine refuses a download through it (`UNSUPPORTED`). Throws
|
|
247
|
+
* {@link ChannelMediaFailure} when the channel refuses, or when the media is
|
|
248
|
+
* larger than `maxBytes` — declared OR actual — or past its deadline (`TIMEOUT`). The same rule as `send`: the
|
|
249
|
+
* opened credential is never logged, put in an error, or returned.
|
|
250
|
+
*/
|
|
251
|
+
fetchMedia?(input: ChannelMediaInput): Promise<ChannelMedia>;
|
|
243
252
|
/** When this channel lets the tenant send free-form messages. */
|
|
244
253
|
readonly policy: SendPolicy;
|
|
245
254
|
}
|
|
@@ -258,6 +267,41 @@ interface ChannelSendInput {
|
|
|
258
267
|
to: string;
|
|
259
268
|
content: OutboundContent;
|
|
260
269
|
}
|
|
270
|
+
interface ChannelMediaInput {
|
|
271
|
+
/** The opened credential of the connection the message arrived through. */
|
|
272
|
+
credential: string;
|
|
273
|
+
/** The connection's account on the channel (WhatsApp's phone_number_id). */
|
|
274
|
+
accountId: string;
|
|
275
|
+
/** The channel's id for the media, as the inbound message carried it. */
|
|
276
|
+
mediaId: string;
|
|
277
|
+
/** The most bytes the caller accepts. Larger media is refused, never truncated. */
|
|
278
|
+
maxBytes: number;
|
|
279
|
+
/**
|
|
280
|
+
* The deadline for the whole download, lookup and body included; past it the
|
|
281
|
+
* calls are aborted and the download fails `TIMEOUT`. Default
|
|
282
|
+
* {@link DEFAULT_MEDIA_TIMEOUT_MS}.
|
|
283
|
+
*/
|
|
284
|
+
timeoutMs?: number;
|
|
285
|
+
}
|
|
286
|
+
/** The default deadline of one media download: 30 s. */
|
|
287
|
+
declare const DEFAULT_MEDIA_TIMEOUT_MS = 30000;
|
|
288
|
+
/** Downloaded media: in memory only. The package never stores it. */
|
|
289
|
+
interface ChannelMedia {
|
|
290
|
+
bytes: Uint8Array;
|
|
291
|
+
/** The channel's MIME type for it (`audio/ogg; codecs=opus`), or `application/octet-stream`. */
|
|
292
|
+
mimeType: string;
|
|
293
|
+
/** `bytes.length`. */
|
|
294
|
+
size: number;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* A media download the channel refused, or the adapter refused to finish.
|
|
298
|
+
* `TOO_LARGE` is the size cap, declared or actual; every other code is the
|
|
299
|
+
* adapter's or the channel's. Never carries the credential.
|
|
300
|
+
*/
|
|
301
|
+
declare class ChannelMediaFailure extends Error {
|
|
302
|
+
readonly code: string;
|
|
303
|
+
constructor(code: string, message: string);
|
|
304
|
+
}
|
|
261
305
|
/** A channel refused or failed a send. `code` is the channel's own, as text. */
|
|
262
306
|
declare class ChannelSendFailure extends Error {
|
|
263
307
|
readonly code: string;
|
|
@@ -290,4 +334,4 @@ declare function serviceWindowPolicy(windowMs: number): SendPolicy;
|
|
|
290
334
|
/** A policy for a channel with no window (e-mail): every send is allowed. */
|
|
291
335
|
declare const OPEN_SEND_POLICY: SendPolicy;
|
|
292
336
|
|
|
293
|
-
export { type AuthorKind as A, type ConversationView as C,
|
|
337
|
+
export { type AuthorKind as A, type ConversationView as C, DEFAULT_MEDIA_TIMEOUT_MS as D, type HandshakeAnswer as H, type InboxDeliveryView as I, type MessageView as M, type NormalizedEvent as N, OPEN_SEND_POLICY as O, type ReceiptStatus as R, type SendPolicy as S, type ChannelAdapter as a, type ChannelKind as b, type ChannelMedia as c, ChannelMediaFailure as d, type ChannelMediaInput as e, ChannelSendFailure as f, type ChannelSendInput as g, type ConnectionStatus as h, type ConnectionView as i, type ConversationState as j, type ConversationSummary as k, type DeliveryState as l, type DeliveryStatus as m, type InboundContent as n, type InboundMessageEvent as o, type MessageDirection as p, type MessageKind as q, type OptOutEvent as r, type OutboundContent as s, type SendPolicyContext as t, type SendPolicyVerdict as u, type StatusEvent as v, isWindowOpen as w, serviceWindowPolicy as x };
|
|
@@ -28,6 +28,17 @@ var MessagingConnectError = class extends Error {
|
|
|
28
28
|
this.code = code;
|
|
29
29
|
}
|
|
30
30
|
};
|
|
31
|
+
var MessagingMediaError = class extends Error {
|
|
32
|
+
static {
|
|
33
|
+
__name(this, "MessagingMediaError");
|
|
34
|
+
}
|
|
35
|
+
code;
|
|
36
|
+
constructor(code, message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "MessagingMediaError";
|
|
39
|
+
this.code = code;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
31
42
|
function errorText(error) {
|
|
32
43
|
const text = error instanceof Error ? error.message : String(error);
|
|
33
44
|
return text.slice(0, 500);
|
|
@@ -37,6 +48,7 @@ __name(errorText, "errorText");
|
|
|
37
48
|
export {
|
|
38
49
|
MessagingSendError,
|
|
39
50
|
MessagingConnectError,
|
|
51
|
+
MessagingMediaError,
|
|
40
52
|
errorText
|
|
41
53
|
};
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
//# sourceMappingURL=chunk-LNVSQ5IQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/errors.ts"],"sourcesContent":["/**\n * The engine's refusals, as typed errors with machine codes. The sentence a\n * person reads for each is the host's copy, keyed by `code`.\n */\n\n/** Why a send was refused or failed. */\nexport type MessagingSendErrorCode =\n /** The contact opted out; nothing is sent until they write again. */\n | \"OPTED_OUT\"\n /** The channel's service window is closed (WhatsApp: 24 h after the contact's last message). */\n | \"WINDOW_CLOSED\"\n /** The conversation's connection is not connected (revoked, in error, or gone). */\n | \"NOT_CONNECTED\"\n /** No such conversation in this tenant. */\n | \"NOT_FOUND\"\n /** No adapter for the conversation's channel is mounted. */\n | \"UNKNOWN_CHANNEL\"\n /** The channel was called and refused or failed; the outbound row is FAILED. */\n | \"CHANNEL_FAILED\";\n\nexport class MessagingSendError extends Error {\n readonly code: MessagingSendErrorCode;\n /** The outbound row, when one was recorded before the failure. */\n readonly messageId: string | null;\n constructor(code: MessagingSendErrorCode, message: string, messageId: string | null = null) {\n super(message);\n this.name = \"MessagingSendError\";\n this.code = code;\n this.messageId = messageId;\n }\n}\n\n/** Why a connection could not be saved. */\nexport type MessagingConnectErrorCode =\n /** The account is connected to another tenant. */\n | \"ACCOUNT_TAKEN\"\n /** No adapter for that channel is mounted. */\n | \"UNKNOWN_CHANNEL\";\n\nexport class MessagingConnectError extends Error {\n readonly code: MessagingConnectErrorCode;\n constructor(code: MessagingConnectErrorCode, message: string) {\n super(message);\n this.name = \"MessagingConnectError\";\n this.code = code;\n }\n}\n\n/** Why a media download was refused or failed. */\nexport type MessagingMediaErrorCode =\n /** No such message in this tenant. */\n | \"NOT_FOUND\"\n /** The message carries no downloadable media (not an inbound audio, or no media id). */\n | \"NO_MEDIA\"\n /** No adapter for the message's channel is mounted. */\n | \"UNKNOWN_CHANNEL\"\n /** The channel's adapter has no media download, or the store cannot read a message by id. */\n | \"UNSUPPORTED\"\n /** The message's connection is not connected (revoked, in error, gone, or holds no credential). */\n | \"NOT_CONNECTED\"\n /** `maxBytes` or `timeoutMs` is not a positive safe integer. */\n | \"BAD_OPTIONS\"\n /** The media is larger than the cap, as declared or as read. */\n | \"TOO_LARGE\"\n /** The download did not finish before its deadline. */\n | \"TIMEOUT\"\n /** The channel was called and refused or failed. */\n | \"CHANNEL_FAILED\";\n\n/** A media download refused. Its message never carries the credential. */\nexport class MessagingMediaError extends Error {\n readonly code: MessagingMediaErrorCode;\n constructor(code: MessagingMediaErrorCode, message: string) {\n super(message);\n this.name = \"MessagingMediaError\";\n this.code = code;\n }\n}\n\n/** The error text a row keeps: bounded, because a channel's error body can be a page. */\nexport function errorText(error: unknown): string {\n const text = error instanceof Error ? error.message : String(error);\n return text.slice(0, 500);\n}\n"],"mappings":";;;;;AAoBO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EApB9C,OAoB8C;AAAA;AAAA;AAAA,EACnC;AAAA;AAAA,EAEA;AAAA,EACT,YAAY,MAA8B,SAAiB,YAA2B,MAAM;AAC1F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,YAAY;AAAA,EACnB;AACF;AASO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAvCjD,OAuCiD;AAAA;AAAA;AAAA,EACtC;AAAA,EACT,YAAY,MAAiC,SAAiB;AAC5D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAwBO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAtE/C,OAsE+C;AAAA;AAAA;AAAA,EACpC;AAAA,EACT,YAAY,MAA+B,SAAiB;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAGO,SAAS,UAAU,OAAwB;AAChD,QAAM,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAClE,SAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AAHgB;","names":[]}
|
|
@@ -3,6 +3,22 @@ import {
|
|
|
3
3
|
} from "./chunk-7QVYU63E.js";
|
|
4
4
|
|
|
5
5
|
// src/core/channel.ts
|
|
6
|
+
var DEFAULT_MEDIA_TIMEOUT_MS = 3e4;
|
|
7
|
+
function isPositiveSafeInteger(value) {
|
|
8
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
9
|
+
}
|
|
10
|
+
__name(isPositiveSafeInteger, "isPositiveSafeInteger");
|
|
11
|
+
var ChannelMediaFailure = class extends Error {
|
|
12
|
+
static {
|
|
13
|
+
__name(this, "ChannelMediaFailure");
|
|
14
|
+
}
|
|
15
|
+
code;
|
|
16
|
+
constructor(code, message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "ChannelMediaFailure";
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
6
22
|
var ChannelSendFailure = class extends Error {
|
|
7
23
|
static {
|
|
8
24
|
__name(this, "ChannelSendFailure");
|
|
@@ -28,9 +44,12 @@ __name(serviceWindowPolicy, "serviceWindowPolicy");
|
|
|
28
44
|
var OPEN_SEND_POLICY = { check: /* @__PURE__ */ __name(() => ({ allowed: true }), "check") };
|
|
29
45
|
|
|
30
46
|
export {
|
|
47
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
48
|
+
isPositiveSafeInteger,
|
|
49
|
+
ChannelMediaFailure,
|
|
31
50
|
ChannelSendFailure,
|
|
32
51
|
isWindowOpen,
|
|
33
52
|
serviceWindowPolicy,
|
|
34
53
|
OPEN_SEND_POLICY
|
|
35
54
|
};
|
|
36
|
-
//# sourceMappingURL=chunk-
|
|
55
|
+
//# sourceMappingURL=chunk-NKH5TCSO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/channel.ts"],"sourcesContent":["import type { ChannelKind, NormalizedEvent, OutboundContent } from \"./types\";\n\n/**\n * THE CHANNEL ADAPTER: everything the engine needs to know about one\n * messaging channel, and nothing the engine decides.\n *\n * The engine owns the mechanism — the inbox and its dedupe, the tenant\n * resolution, the conversation and its state, the outbound bookkeeping, the\n * retention. An adapter owns the channel's wire: how a delivery proves where\n * it came from, what its body means, how a message goes out, and when the\n * channel lets a tenant speak first. WhatsApp Cloud is the first adapter\n * (`@12-apps/messaging/whatsapp`); e-mail or a chat workspace join the same\n * way, as one more object of this shape.\n */\nexport interface ChannelAdapter {\n /** The channel's key, stored on every row: `whatsapp`. Lowercase, dash-separated. */\n readonly kind: ChannelKind;\n\n /**\n * Answer the channel's subscription handshake (a `GET` with a challenge),\n * or null for a channel that has none. `ok: false` is a refusal (403).\n */\n handshake(query: Readonly<Record<string, string | undefined>>): HandshakeAnswer | null;\n\n /**\n * Is this delivery really from the channel? Computed over the RAW body\n * bytes, exactly as received. MUST fail closed: a missing secret, a missing\n * header or a malformed one is `false`, never an exception and never `true`.\n */\n verify(delivery: { rawBody: Uint8Array; header(name: string): string | null }): boolean;\n\n /**\n * Turn a raw body into normalized events, in the order the channel listed\n * them. A body the adapter does not recognize yields `[]`; a body that is not\n * even JSON throws (the inbox records the failure).\n */\n parse(rawBody: string): NormalizedEvent[];\n\n /**\n * Send one message from a connected account and report the channel's id\n * for it. Throws {@link ChannelSendFailure} when the channel refuses.\n * `credential` is the OPENED credential: an adapter never logs it, never\n * puts it in an error, never returns it.\n */\n send(input: ChannelSendInput): Promise<{ externalId: string }>;\n\n /**\n * Download one inbound message's media (a voice note) by the channel's media\n * id, into memory. OPTIONAL: a channel with no media leaves it out, and the\n * engine refuses a download through it (`UNSUPPORTED`). Throws\n * {@link ChannelMediaFailure} when the channel refuses, or when the media is\n * larger than `maxBytes` — declared OR actual — or past its deadline (`TIMEOUT`). The same rule as `send`: the\n * opened credential is never logged, put in an error, or returned.\n */\n fetchMedia?(input: ChannelMediaInput): Promise<ChannelMedia>;\n\n /** When this channel lets the tenant send free-form messages. */\n readonly policy: SendPolicy;\n}\n\nexport type HandshakeAnswer = { ok: true; challenge: string } | { ok: false };\n\nexport interface ChannelSendInput {\n /** The opened credential of the connection sending it. */\n credential: string;\n /** The connection's account on the channel (WhatsApp's phone_number_id). */\n accountId: string;\n /** The recipient's address. */\n to: string;\n content: OutboundContent;\n}\n\nexport interface ChannelMediaInput {\n /** The opened credential of the connection the message arrived through. */\n credential: string;\n /** The connection's account on the channel (WhatsApp's phone_number_id). */\n accountId: string;\n /** The channel's id for the media, as the inbound message carried it. */\n mediaId: string;\n /** The most bytes the caller accepts. Larger media is refused, never truncated. */\n maxBytes: number;\n /**\n * The deadline for the whole download, lookup and body included; past it the\n * calls are aborted and the download fails `TIMEOUT`. Default\n * {@link DEFAULT_MEDIA_TIMEOUT_MS}.\n */\n timeoutMs?: number;\n}\n\n/** The default deadline of one media download: 30 s. */\nexport const DEFAULT_MEDIA_TIMEOUT_MS = 30_000;\n\n/** Is `value` a usable byte cap or deadline: a positive safe integer (never NaN, Infinity or 0). */\nexport function isPositiveSafeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\n}\n\n/** Downloaded media: in memory only. The package never stores it. */\nexport interface ChannelMedia {\n bytes: Uint8Array;\n /** The channel's MIME type for it (`audio/ogg; codecs=opus`), or `application/octet-stream`. */\n mimeType: string;\n /** `bytes.length`. */\n size: number;\n}\n\n/**\n * A media download the channel refused, or the adapter refused to finish.\n * `TOO_LARGE` is the size cap, declared or actual; every other code is the\n * adapter's or the channel's. Never carries the credential.\n */\nexport class ChannelMediaFailure extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"ChannelMediaFailure\";\n this.code = code;\n }\n}\n\n/** A channel refused or failed a send. `code` is the channel's own, as text. */\nexport class ChannelSendFailure extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"ChannelSendFailure\";\n this.code = code;\n }\n}\n\n/** What a send policy is asked. */\nexport interface SendPolicyContext {\n /** When the contact last wrote; null if never. */\n lastInboundAt: Date | null;\n now: Date;\n}\n\nexport type SendPolicyVerdict = { allowed: true } | { allowed: false; reason: \"WINDOW_CLOSED\" };\n\n/** A channel's rule for free-form sends. */\nexport interface SendPolicy {\n check(context: SendPolicyContext): SendPolicyVerdict;\n}\n\n/**\n * Is a service window still open? Open while LESS than `windowMs` has passed\n * since the contact's last message: at exactly the window's length it is\n * closed. Never open for a contact who never wrote.\n */\nexport function isWindowOpen(lastInboundAt: Date | null, now: Date, windowMs: number): boolean {\n if (!lastInboundAt) return false;\n return now.getTime() - lastInboundAt.getTime() < windowMs;\n}\n\n/** A policy that allows free-form sends only inside a window after the contact's last message. */\nexport function serviceWindowPolicy(windowMs: number): SendPolicy {\n return {\n check: ({ lastInboundAt, now }) =>\n isWindowOpen(lastInboundAt, now, windowMs) ? { allowed: true } : { allowed: false, reason: \"WINDOW_CLOSED\" },\n };\n}\n\n/** A policy for a channel with no window (e-mail): every send is allowed. */\nexport const OPEN_SEND_POLICY: SendPolicy = { check: () => ({ allowed: true }) };\n"],"mappings":";;;;;AA0FO,IAAM,2BAA2B;AAGjC,SAAS,sBAAsB,OAAiC;AACrE,SAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,QAAQ;AAC7E;AAFgB;AAkBT,IAAM,sBAAN,cAAkC,MAAM;AAAA,EA/G/C,OA+G+C;AAAA;AAAA;AAAA,EACpC;AAAA,EACT,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAzH9C,OAyH8C;AAAA;AAAA;AAAA,EACnC;AAAA,EACT,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAqBO,SAAS,aAAa,eAA4B,KAAW,UAA2B;AAC7F,MAAI,CAAC,cAAe,QAAO;AAC3B,SAAO,IAAI,QAAQ,IAAI,cAAc,QAAQ,IAAI;AACnD;AAHgB;AAMT,SAAS,oBAAoB,UAA8B;AAChE,SAAO;AAAA,IACL,OAAO,wBAAC,EAAE,eAAe,IAAI,MAC3B,aAAa,eAAe,KAAK,QAAQ,IAAI,EAAE,SAAS,KAAK,IAAI,EAAE,SAAS,OAAO,QAAQ,gBAAgB,GADtG;AAAA,EAET;AACF;AALgB;AAQT,IAAM,mBAA+B,EAAE,OAAO,8BAAO,EAAE,SAAS,KAAK,IAAvB,SAA0B;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
errorText
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-LNVSQ5IQ.js";
|
|
4
4
|
import {
|
|
5
5
|
__name
|
|
6
6
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -133,4 +133,4 @@ export {
|
|
|
133
133
|
MESSAGING_JOBS,
|
|
134
134
|
createApiMessaging
|
|
135
135
|
};
|
|
136
|
-
//# sourceMappingURL=chunk-
|
|
136
|
+
//# sourceMappingURL=chunk-S5PJXMXM.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { j as ConversationState, k as ConversationSummary, i as ConnectionView, m as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, h as ConnectionStatus, C as ConversationView, M as MessageView, p as MessageDirection, q as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, s as OutboundContent, c as ChannelMedia } from './channel-HEnMO02x.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* THE STORE PORT: every read and write the engine makes, as named operations.
|
|
@@ -73,6 +73,12 @@ interface MessagingStore {
|
|
|
73
73
|
message: MessageView;
|
|
74
74
|
}>;
|
|
75
75
|
updateMessage(tenantId: string, id: string, patch: MessagePatch): Promise<MessageView | null>;
|
|
76
|
+
/**
|
|
77
|
+
* The tenant's message by id; null for another tenant's or none. Optional so
|
|
78
|
+
* a host's own store keeps compiling; both shipped stores implement it, and
|
|
79
|
+
* `downloadMedia` is refused (`UNSUPPORTED`) on a store without it.
|
|
80
|
+
*/
|
|
81
|
+
getMessage?(tenantId: string, id: string): Promise<MessageView | null>;
|
|
76
82
|
listMessages(tenantId: string, conversationId: string): Promise<MessageView[]>;
|
|
77
83
|
/**
|
|
78
84
|
* Stamp a receipt on the tenant's outbound message: the receipt's timestamp
|
|
@@ -249,6 +255,23 @@ interface MessagingHooks {
|
|
|
249
255
|
* it, and an answer that slips through anyway is read as `AGENT`.
|
|
250
256
|
*/
|
|
251
257
|
reopenState?(conversation: ConversationView): ReopenState | Promise<ReopenState>;
|
|
258
|
+
/**
|
|
259
|
+
* Events of a channel account NOBODY connected: a message, an opt-out or a
|
|
260
|
+
* delivery receipt of a number the host itself owns on the same app (its
|
|
261
|
+
* platform notification number, typically), which no tenant row resolves.
|
|
262
|
+
*
|
|
263
|
+
* Without this hook they are dropped, exactly as before. With it, the host is
|
|
264
|
+
* handed them once per processed delivery: already signature-checked,
|
|
265
|
+
* persisted and parsed, and still stored nowhere here (no conversation, no
|
|
266
|
+
* message). An event of a CONNECTED, revoked or errored tenant account is
|
|
267
|
+
* never handed over: a tenant's traffic is the tenant's, and the host's
|
|
268
|
+
* platform path must not see it.
|
|
269
|
+
*
|
|
270
|
+
* A throw settles the delivery FAILED, so the reconciliation sweep runs it
|
|
271
|
+
* again: the host's handler must be idempotent on the provider's message id.
|
|
272
|
+
* Default: nothing.
|
|
273
|
+
*/
|
|
274
|
+
onUnclaimedEvents?(channel: string, events: NormalizedEvent[]): Promise<void> | void;
|
|
252
275
|
}
|
|
253
276
|
/** Everything a host hands `createMessagingEngine`. */
|
|
254
277
|
interface MessagingEngineConfig {
|
|
@@ -349,6 +372,15 @@ interface ConnectInput {
|
|
|
349
372
|
credential: string;
|
|
350
373
|
}
|
|
351
374
|
|
|
375
|
+
/** The default cap on one download: 16 MiB, WhatsApp's own limit for audio. */
|
|
376
|
+
declare const DEFAULT_MEDIA_MAX_BYTES: number;
|
|
377
|
+
interface DownloadMediaOptions {
|
|
378
|
+
/** The most bytes accepted; larger media is refused (`TOO_LARGE`). Default {@link DEFAULT_MEDIA_MAX_BYTES}. */
|
|
379
|
+
maxBytes?: number;
|
|
380
|
+
/** The deadline for the whole download; past it the download fails `TIMEOUT`. Default {@link DEFAULT_MEDIA_TIMEOUT_MS}. */
|
|
381
|
+
timeoutMs?: number;
|
|
382
|
+
}
|
|
383
|
+
|
|
352
384
|
/** Who is sending: the host's agent, or a person on the tenant's staff. */
|
|
353
385
|
type SendAuthor = {
|
|
354
386
|
kind: "AGENT";
|
|
@@ -392,6 +424,11 @@ declare function createMessagingEngine(config: MessagingEngineConfig): {
|
|
|
392
424
|
more: boolean;
|
|
393
425
|
}>;
|
|
394
426
|
send: (input: SendInput) => Promise<MessageView>;
|
|
427
|
+
/**
|
|
428
|
+
* Download an inbound audio message's media into memory (`{ bytes, mimeType, size }`),
|
|
429
|
+
* through its connection. Nothing is stored; throws `MessagingMediaError`.
|
|
430
|
+
*/
|
|
431
|
+
downloadMedia: (tenantId: string, messageId: string, options?: DownloadMediaOptions) => Promise<ChannelMedia>;
|
|
395
432
|
connect: (input: ConnectInput) => Promise<ConnectionView>;
|
|
396
433
|
revoke: (tenantId: string, connectionId: string, reason?: string | null) => Promise<boolean>;
|
|
397
434
|
markError: (tenantId: string, connectionId: string, reason: string) => Promise<boolean>;
|
|
@@ -411,4 +448,4 @@ declare function createMessagingEngine(config: MessagingEngineConfig): {
|
|
|
411
448
|
};
|
|
412
449
|
type MessagingEngine = ReturnType<typeof createMessagingEngine>;
|
|
413
450
|
|
|
414
|
-
export { type ConnectInput as C,
|
|
451
|
+
export { type ConnectInput as C, DEFAULT_MEDIA_MAX_BYTES as D, type EventOutcome as E, type InboundMessageNotice as I, type MessagingStore as M, type NewConnection as N, PROCESS_DELIVERY_JOB as P, type StoredConnection as S, type ConversationPatch as a, type DeliveryOutcome as b, type DownloadMediaOptions as c, MESSAGING_DEFAULTS as d, type MessagePatch as e, type MessagingClockPort as f, type MessagingEngine as g, type MessagingEngineConfig as h, type MessagingEnqueuePort as i, type MessagingHooks as j, type MessagingLogger as k, type MessagingSecretsPort as l, type NewConversation as m, type NewMessage as n, type SendAuthor as o, type SendInput as p, createMessagingEngine as q };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { S as StoredConnection, M as MessagingStore } from './engine-
|
|
2
|
-
export { C as ConnectInput, a as ConversationPatch, D as DeliveryOutcome, E as EventOutcome, I as InboundMessageNotice,
|
|
3
|
-
import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-
|
|
4
|
-
export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as
|
|
1
|
+
import { S as StoredConnection, M as MessagingStore } from './engine-DAfm8V5S.js';
|
|
2
|
+
export { C as ConnectInput, a as ConversationPatch, D as DEFAULT_MEDIA_MAX_BYTES, b as DeliveryOutcome, c as DownloadMediaOptions, E as EventOutcome, I as InboundMessageNotice, d as MESSAGING_DEFAULTS, e as MessagePatch, f as MessagingClockPort, g as MessagingEngine, h as MessagingEngineConfig, i as MessagingEnqueuePort, j as MessagingHooks, k as MessagingLogger, l as MessagingSecretsPort, N as NewConnection, m as NewConversation, n as NewMessage, P as PROCESS_DELIVERY_JOB, o as SendAuthor, p as SendInput, q as createMessagingEngine } from './engine-DAfm8V5S.js';
|
|
3
|
+
import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-HEnMO02x.js';
|
|
4
|
+
export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelMedia, d as ChannelMediaFailure, e as ChannelMediaInput, f as ChannelSendFailure, g as ChannelSendInput, h as ConnectionStatus, i as ConnectionView, j as ConversationState, k as ConversationSummary, D as DEFAULT_MEDIA_TIMEOUT_MS, l as DeliveryState, m as DeliveryStatus, H as HandshakeAnswer, n as InboundContent, o as InboundMessageEvent, p as MessageDirection, q as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, r as OptOutEvent, s as OutboundContent, R as ReceiptStatus, S as SendPolicy, t as SendPolicyContext, u as SendPolicyVerdict, v as StatusEvent, w as isWindowOpen, x as serviceWindowPolicy } from './channel-HEnMO02x.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* The engine's refusals, as typed errors with machine codes. The sentence a
|
|
@@ -37,6 +37,31 @@ declare class MessagingConnectError extends Error {
|
|
|
37
37
|
readonly code: MessagingConnectErrorCode;
|
|
38
38
|
constructor(code: MessagingConnectErrorCode, message: string);
|
|
39
39
|
}
|
|
40
|
+
/** Why a media download was refused or failed. */
|
|
41
|
+
type MessagingMediaErrorCode =
|
|
42
|
+
/** No such message in this tenant. */
|
|
43
|
+
"NOT_FOUND"
|
|
44
|
+
/** The message carries no downloadable media (not an inbound audio, or no media id). */
|
|
45
|
+
| "NO_MEDIA"
|
|
46
|
+
/** No adapter for the message's channel is mounted. */
|
|
47
|
+
| "UNKNOWN_CHANNEL"
|
|
48
|
+
/** The channel's adapter has no media download, or the store cannot read a message by id. */
|
|
49
|
+
| "UNSUPPORTED"
|
|
50
|
+
/** The message's connection is not connected (revoked, in error, gone, or holds no credential). */
|
|
51
|
+
| "NOT_CONNECTED"
|
|
52
|
+
/** `maxBytes` or `timeoutMs` is not a positive safe integer. */
|
|
53
|
+
| "BAD_OPTIONS"
|
|
54
|
+
/** The media is larger than the cap, as declared or as read. */
|
|
55
|
+
| "TOO_LARGE"
|
|
56
|
+
/** The download did not finish before its deadline. */
|
|
57
|
+
| "TIMEOUT"
|
|
58
|
+
/** The channel was called and refused or failed. */
|
|
59
|
+
| "CHANNEL_FAILED";
|
|
60
|
+
/** A media download refused. Its message never carries the credential. */
|
|
61
|
+
declare class MessagingMediaError extends Error {
|
|
62
|
+
readonly code: MessagingMediaErrorCode;
|
|
63
|
+
constructor(code: MessagingMediaErrorCode, message: string);
|
|
64
|
+
}
|
|
40
65
|
|
|
41
66
|
/**
|
|
42
67
|
* An in-memory {@link MessagingStore}, for a host's tests and this package's
|
|
@@ -94,4 +119,4 @@ declare function createPrismaMessagingStore(db: MessagingPrismaDb | (() => Promi
|
|
|
94
119
|
/** The inbox key of a raw body: its SHA-256, hex. A redelivery is the same bytes, so the same key. */
|
|
95
120
|
declare function bodyHash(rawBody: string): string;
|
|
96
121
|
|
|
97
|
-
export { ConversationView, InboxDeliveryView, type MemoryStoreDump, MessageView, MessagingConnectError, type MessagingConnectErrorCode, type MessagingPrismaDb, MessagingSendError, type MessagingSendErrorCode, MessagingStore, StoredConnection, bodyHash, createMemoryMessagingStore, createPrismaMessagingStore };
|
|
122
|
+
export { ConversationView, InboxDeliveryView, type MemoryStoreDump, MessageView, MessagingConnectError, type MessagingConnectErrorCode, MessagingMediaError, type MessagingMediaErrorCode, type MessagingPrismaDb, MessagingSendError, type MessagingSendErrorCode, MessagingStore, StoredConnection, bodyHash, createMemoryMessagingStore, createPrismaMessagingStore };
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
+
ChannelMediaFailure,
|
|
2
3
|
ChannelSendFailure,
|
|
4
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
3
5
|
OPEN_SEND_POLICY,
|
|
6
|
+
isPositiveSafeInteger,
|
|
4
7
|
isWindowOpen,
|
|
5
8
|
serviceWindowPolicy
|
|
6
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-NKH5TCSO.js";
|
|
7
10
|
import {
|
|
8
11
|
MessagingConnectError,
|
|
12
|
+
MessagingMediaError,
|
|
9
13
|
MessagingSendError,
|
|
10
14
|
errorText
|
|
11
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-LNVSQ5IQ.js";
|
|
12
16
|
import {
|
|
13
17
|
__name
|
|
14
18
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -285,6 +289,7 @@ async function processDelivery(ctx, deliveryId) {
|
|
|
285
289
|
try {
|
|
286
290
|
const outcomes = [];
|
|
287
291
|
for (const event of events) outcomes.push(await handleEvent(ctx, row.channel, event));
|
|
292
|
+
await handOverUnclaimed(ctx, row.channel, events, outcomes);
|
|
288
293
|
const unapplied = outcomes.filter((outcome) => outcome.kind === "receipt" && !outcome.applied).length;
|
|
289
294
|
if (unapplied > 0) {
|
|
290
295
|
const error = `${unapplied} receipt(s) for a message not stored yet`;
|
|
@@ -300,6 +305,16 @@ async function processDelivery(ctx, deliveryId) {
|
|
|
300
305
|
}
|
|
301
306
|
}
|
|
302
307
|
__name(processDelivery, "processDelivery");
|
|
308
|
+
async function handOverUnclaimed(ctx, channel, events, outcomes) {
|
|
309
|
+
const hook = ctx.config.hooks?.onUnclaimedEvents;
|
|
310
|
+
if (!hook) return;
|
|
311
|
+
const unclaimed = events.filter((_, index) => {
|
|
312
|
+
const outcome = outcomes[index];
|
|
313
|
+
return outcome?.kind === "dropped" && outcome.reason === "unknown-account";
|
|
314
|
+
});
|
|
315
|
+
if (unclaimed.length > 0) await hook(channel, unclaimed);
|
|
316
|
+
}
|
|
317
|
+
__name(handOverUnclaimed, "handOverUnclaimed");
|
|
303
318
|
async function reconcileInbox(ctx) {
|
|
304
319
|
const { store, clock, logger, reconcileAfterMs, maxDeliveryAttempts, reconcileBatchSize } = ctx.config;
|
|
305
320
|
const due = await store.listRetryableDeliveries({
|
|
@@ -320,6 +335,58 @@ async function reconcileInbox(ctx) {
|
|
|
320
335
|
}
|
|
321
336
|
__name(reconcileInbox, "reconcileInbox");
|
|
322
337
|
|
|
338
|
+
// src/core/media.ts
|
|
339
|
+
var DEFAULT_MEDIA_MAX_BYTES = 16 * 1024 * 1024;
|
|
340
|
+
var KEPT_CODES = /* @__PURE__ */ new Set(["TOO_LARGE", "TIMEOUT", "BAD_OPTIONS"]);
|
|
341
|
+
function mediaIdOf(message) {
|
|
342
|
+
if (message.direction !== "INBOUND" || message.kind !== "AUDIO" || !message.attachmentRef) {
|
|
343
|
+
throw new MessagingMediaError("NO_MEDIA", `message ${message.id} carries no downloadable media`);
|
|
344
|
+
}
|
|
345
|
+
return message.attachmentRef;
|
|
346
|
+
}
|
|
347
|
+
__name(mediaIdOf, "mediaIdOf");
|
|
348
|
+
async function admitDownload(ctx, tenantId, message) {
|
|
349
|
+
const adapter = ctx.adapters.get(message.channel);
|
|
350
|
+
if (!adapter) throw new MessagingMediaError("UNKNOWN_CHANNEL", `no adapter for channel "${message.channel}"`);
|
|
351
|
+
if (!adapter.fetchMedia) throw new MessagingMediaError("UNSUPPORTED", `channel "${message.channel}" has no media download`);
|
|
352
|
+
const { store, secrets } = ctx.config;
|
|
353
|
+
const conversation = await store.getConversation(tenantId, message.conversationId);
|
|
354
|
+
const connection = conversation ? await store.getConnection(tenantId, conversation.connectionId) : null;
|
|
355
|
+
if (!connection || connection.status !== "CONNECTED" || connection.credentialSealed === null) {
|
|
356
|
+
throw new MessagingMediaError("NOT_CONNECTED", `message ${message.id}: its connection is not connected`);
|
|
357
|
+
}
|
|
358
|
+
const credential = await secrets.open(connection.credentialSealed);
|
|
359
|
+
return { fetchMedia: adapter.fetchMedia.bind(adapter), credential, accountId: connection.externalAccountId };
|
|
360
|
+
}
|
|
361
|
+
__name(admitDownload, "admitDownload");
|
|
362
|
+
function mediaFailureOf(error, credential) {
|
|
363
|
+
const coded = error instanceof ChannelMediaFailure || error instanceof ChannelSendFailure;
|
|
364
|
+
const raw = coded ? `${error.code}: ${error.message}` : errorText(error);
|
|
365
|
+
const text = (credential ? raw.split(credential).join("[credential]") : raw).slice(0, 500);
|
|
366
|
+
const kept = error instanceof ChannelMediaFailure && KEPT_CODES.has(error.code);
|
|
367
|
+
return new MessagingMediaError(kept ? error.code : "CHANNEL_FAILED", text);
|
|
368
|
+
}
|
|
369
|
+
__name(mediaFailureOf, "mediaFailureOf");
|
|
370
|
+
async function downloadMedia(ctx, tenantId, messageId, options = {}) {
|
|
371
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MEDIA_MAX_BYTES;
|
|
372
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;
|
|
373
|
+
if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {
|
|
374
|
+
throw new MessagingMediaError("BAD_OPTIONS", "maxBytes and timeoutMs must be positive safe integers");
|
|
375
|
+
}
|
|
376
|
+
const { store } = ctx.config;
|
|
377
|
+
if (!store.getMessage) throw new MessagingMediaError("UNSUPPORTED", "the store cannot read a message by id (getMessage)");
|
|
378
|
+
const message = await store.getMessage(tenantId, messageId);
|
|
379
|
+
if (!message) throw new MessagingMediaError("NOT_FOUND", `no message ${messageId}`);
|
|
380
|
+
const mediaId = mediaIdOf(message);
|
|
381
|
+
const { fetchMedia, credential, accountId } = await admitDownload(ctx, tenantId, message);
|
|
382
|
+
try {
|
|
383
|
+
return await fetchMedia({ credential, accountId, mediaId, maxBytes, timeoutMs });
|
|
384
|
+
} catch (error) {
|
|
385
|
+
throw mediaFailureOf(error, credential);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
__name(downloadMedia, "downloadMedia");
|
|
389
|
+
|
|
323
390
|
// src/core/retention.ts
|
|
324
391
|
async function sweepRetention(ctx) {
|
|
325
392
|
const { store, clock, retentionMs, retentionBatchSize, maxDeliveryAttempts } = ctx.config;
|
|
@@ -429,6 +496,12 @@ function createMessagingEngine(config) {
|
|
|
429
496
|
sweepRetention: /* @__PURE__ */ __name(() => sweepRetention(ctx), "sweepRetention"),
|
|
430
497
|
// ── Sending ──────────────────────────────────────────────────────────────
|
|
431
498
|
send: /* @__PURE__ */ __name((input) => sendMessage(ctx, input), "send"),
|
|
499
|
+
// ── Media ────────────────────────────────────────────────────────────────
|
|
500
|
+
/**
|
|
501
|
+
* Download an inbound audio message's media into memory (`{ bytes, mimeType, size }`),
|
|
502
|
+
* through its connection. Nothing is stored; throws `MessagingMediaError`.
|
|
503
|
+
*/
|
|
504
|
+
downloadMedia: /* @__PURE__ */ __name((tenantId, messageId, options) => downloadMedia(ctx, tenantId, messageId, options), "downloadMedia"),
|
|
432
505
|
// ── Connections ──────────────────────────────────────────────────────────
|
|
433
506
|
connect: /* @__PURE__ */ __name((input) => connect(ctx, input), "connect"),
|
|
434
507
|
revoke: /* @__PURE__ */ __name((tenantId, connectionId, reason) => revoke(ctx, tenantId, connectionId, reason), "revoke"),
|
|
@@ -653,6 +726,10 @@ function memoryMessages({ messages }) {
|
|
|
653
726
|
messages.set(id, next);
|
|
654
727
|
return copy(next);
|
|
655
728
|
},
|
|
729
|
+
async getMessage(tenantId, id) {
|
|
730
|
+
const row = messages.get(id);
|
|
731
|
+
return row && row.tenantId === tenantId ? copy(row) : null;
|
|
732
|
+
},
|
|
656
733
|
async listMessages(tenantId, conversationId) {
|
|
657
734
|
return [...messages.values()].filter((row) => row.tenantId === tenantId && row.conversationId === conversationId).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()).map(copy);
|
|
658
735
|
},
|
|
@@ -903,6 +980,9 @@ function messageOperations(client) {
|
|
|
903
980
|
if (result.count === 0) return null;
|
|
904
981
|
return await delegate.findUnique({ where: { id } });
|
|
905
982
|
},
|
|
983
|
+
async getMessage(tenantId, id) {
|
|
984
|
+
return await (await client()).messagingMessage.findFirst({ where: { id, tenantId } }) ?? null;
|
|
985
|
+
},
|
|
906
986
|
async listMessages(tenantId, conversationId) {
|
|
907
987
|
return await (await client()).messagingMessage.findMany({
|
|
908
988
|
where: { tenantId, conversationId },
|
|
@@ -972,9 +1052,13 @@ function statusesBelow(status) {
|
|
|
972
1052
|
}
|
|
973
1053
|
__name(statusesBelow, "statusesBelow");
|
|
974
1054
|
export {
|
|
1055
|
+
ChannelMediaFailure,
|
|
975
1056
|
ChannelSendFailure,
|
|
1057
|
+
DEFAULT_MEDIA_MAX_BYTES,
|
|
1058
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
976
1059
|
MESSAGING_DEFAULTS,
|
|
977
1060
|
MessagingConnectError,
|
|
1061
|
+
MessagingMediaError,
|
|
978
1062
|
MessagingSendError,
|
|
979
1063
|
OPEN_SEND_POLICY,
|
|
980
1064
|
PROCESS_DELIVERY_JOB,
|