@12-apps/messaging 0.0.0-stage → 1.1.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.
Files changed (57) hide show
  1. package/ADOPTING.md +119 -0
  2. package/README.md +157 -2
  3. package/dist/channel-Cs_vLGl_.d.ts +293 -0
  4. package/dist/chunk-72TDAQUW.js +136 -0
  5. package/dist/chunk-72TDAQUW.js.map +1 -0
  6. package/dist/chunk-7QVYU63E.js +7 -0
  7. package/dist/chunk-7QVYU63E.js.map +1 -0
  8. package/dist/chunk-R3DKM2IV.js +42 -0
  9. package/dist/chunk-R3DKM2IV.js.map +1 -0
  10. package/dist/chunk-Y7MG2UDQ.js +36 -0
  11. package/dist/chunk-Y7MG2UDQ.js.map +1 -0
  12. package/dist/engine-DTnp2zUL.d.ts +431 -0
  13. package/dist/index.d.ts +97 -0
  14. package/dist/index.js +999 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/manifest/index.d.ts +36 -0
  17. package/dist/manifest/index.js +14 -0
  18. package/dist/manifest/index.js.map +1 -0
  19. package/dist/manifest/server.d.ts +21 -0
  20. package/dist/manifest/server.js +17 -0
  21. package/dist/manifest/server.js.map +1 -0
  22. package/dist/server/index.d.ts +78 -0
  23. package/dist/server/index.js +15 -0
  24. package/dist/server/index.js.map +1 -0
  25. package/dist/whatsapp/index.d.ts +180 -0
  26. package/dist/whatsapp/index.js +385 -0
  27. package/dist/whatsapp/index.js.map +1 -0
  28. package/package.json +90 -4
  29. package/prisma/messaging.prisma +140 -0
  30. package/prisma/migrations/20261114120000_messaging_connector/migration.sql +110 -0
  31. package/src/core/channel.ts +106 -0
  32. package/src/core/connections.ts +67 -0
  33. package/src/core/context.ts +28 -0
  34. package/src/core/engine.ts +64 -0
  35. package/src/core/errors.ts +53 -0
  36. package/src/core/hash.ts +6 -0
  37. package/src/core/inbound.ts +240 -0
  38. package/src/core/inbox.ts +139 -0
  39. package/src/core/memory-store.ts +273 -0
  40. package/src/core/ports.ts +129 -0
  41. package/src/core/prisma-store.ts +354 -0
  42. package/src/core/retention.ts +27 -0
  43. package/src/core/sender.ts +106 -0
  44. package/src/core/store.ts +217 -0
  45. package/src/core/types.ts +189 -0
  46. package/src/index.ts +54 -0
  47. package/src/manifest/index.ts +32 -0
  48. package/src/manifest/server.ts +18 -0
  49. package/src/server/index.ts +22 -0
  50. package/src/server/jobs.ts +99 -0
  51. package/src/server/webhook.ts +92 -0
  52. package/src/whatsapp/graph.ts +136 -0
  53. package/src/whatsapp/index.ts +64 -0
  54. package/src/whatsapp/opt-out.ts +26 -0
  55. package/src/whatsapp/parse.ts +200 -0
  56. package/src/whatsapp/signature.ts +52 -0
  57. package/src/whatsapp/signup.ts +115 -0
package/dist/index.js ADDED
@@ -0,0 +1,999 @@
1
+ import {
2
+ ChannelSendFailure,
3
+ OPEN_SEND_POLICY,
4
+ isWindowOpen,
5
+ serviceWindowPolicy
6
+ } from "./chunk-Y7MG2UDQ.js";
7
+ import {
8
+ MessagingConnectError,
9
+ MessagingSendError,
10
+ errorText
11
+ } from "./chunk-R3DKM2IV.js";
12
+ import {
13
+ __name
14
+ } from "./chunk-7QVYU63E.js";
15
+
16
+ // src/core/connections.ts
17
+ async function connect(ctx, input) {
18
+ const { store, secrets, clock } = ctx.config;
19
+ if (!ctx.adapters.has(input.channel)) {
20
+ throw new MessagingConnectError("UNKNOWN_CHANNEL", `no adapter for channel "${input.channel}"`);
21
+ }
22
+ const existing = await store.findConnectionByAccount(input.channel, input.externalAccountId);
23
+ if (existing && existing.tenantId !== input.tenantId && existing.status !== "REVOKED") {
24
+ throw new MessagingConnectError("ACCOUNT_TAKEN", `account ${input.externalAccountId} is held by another tenant`);
25
+ }
26
+ const saved = await store.saveConnection({
27
+ tenantId: input.tenantId,
28
+ channel: input.channel,
29
+ externalAccountId: input.externalAccountId,
30
+ externalParentId: input.externalParentId ?? null,
31
+ displayAddress: input.displayAddress,
32
+ credentialSealed: await secrets.seal(input.credential),
33
+ connectedAt: clock.now()
34
+ });
35
+ if (!saved) throw new MessagingConnectError("ACCOUNT_TAKEN", `account ${input.externalAccountId} is held by another tenant`);
36
+ return saved;
37
+ }
38
+ __name(connect, "connect");
39
+ async function revoke(ctx, tenantId, connectionId, reason = null) {
40
+ return ctx.config.store.setConnectionStatus(tenantId, connectionId, {
41
+ status: "REVOKED",
42
+ statusReason: reason,
43
+ revokedAt: ctx.config.clock.now(),
44
+ credentialSealed: null
45
+ });
46
+ }
47
+ __name(revoke, "revoke");
48
+ async function markError(ctx, tenantId, connectionId, reason) {
49
+ return ctx.config.store.setConnectionStatus(tenantId, connectionId, {
50
+ status: "ERROR",
51
+ statusReason: reason.slice(0, 500),
52
+ revokedAt: null
53
+ });
54
+ }
55
+ __name(markError, "markError");
56
+
57
+ // src/core/ports.ts
58
+ var MESSAGING_DEFAULTS = {
59
+ retentionMs: 12 * 60 * 60 * 1e3,
60
+ retentionBatchSize: 500,
61
+ reconcileBatchSize: 50,
62
+ maxDeliveryAttempts: 5,
63
+ reconcileAfterMs: 2 * 60 * 1e3
64
+ };
65
+
66
+ // src/core/context.ts
67
+ function engineContext(config) {
68
+ const adapters = /* @__PURE__ */ new Map();
69
+ for (const adapter of config.adapters) {
70
+ if (adapters.has(adapter.kind)) throw new Error(`messaging: channel "${adapter.kind}" is mounted twice`);
71
+ adapters.set(adapter.kind, adapter);
72
+ }
73
+ return {
74
+ config: {
75
+ ...config,
76
+ retentionMs: config.retentionMs ?? MESSAGING_DEFAULTS.retentionMs,
77
+ retentionBatchSize: config.retentionBatchSize ?? MESSAGING_DEFAULTS.retentionBatchSize,
78
+ reconcileBatchSize: config.reconcileBatchSize ?? MESSAGING_DEFAULTS.reconcileBatchSize,
79
+ maxDeliveryAttempts: config.maxDeliveryAttempts ?? MESSAGING_DEFAULTS.maxDeliveryAttempts,
80
+ reconcileAfterMs: config.reconcileAfterMs ?? MESSAGING_DEFAULTS.reconcileAfterMs
81
+ },
82
+ adapters
83
+ };
84
+ }
85
+ __name(engineContext, "engineContext");
86
+
87
+ // src/core/hash.ts
88
+ import { createHash } from "crypto";
89
+ function bodyHash(rawBody) {
90
+ return createHash("sha256").update(rawBody, "utf8").digest("hex");
91
+ }
92
+ __name(bodyHash, "bodyHash");
93
+
94
+ // src/core/inbound.ts
95
+ async function handleEvent(ctx, channel, event) {
96
+ const connection = await ctx.config.store.findConnectionByAccount(channel, event.accountId);
97
+ if (!connection) return { kind: "dropped", reason: "unknown-account" };
98
+ if (connection.status !== "CONNECTED") return { kind: "dropped", reason: "not-connected" };
99
+ if (event.type === "message") return handleMessage(ctx, connection, event);
100
+ if (event.type === "opt_out") return handleOptOut(ctx, connection, event);
101
+ const applied = await ctx.config.store.applyReceipt({
102
+ tenantId: connection.tenantId,
103
+ channel,
104
+ externalId: event.externalId,
105
+ status: event.status,
106
+ at: event.at,
107
+ error: event.error
108
+ });
109
+ return { kind: "receipt", applied };
110
+ }
111
+ __name(handleEvent, "handleEvent");
112
+ function columnsOf(content) {
113
+ switch (content.kind) {
114
+ case "TEXT":
115
+ return { kind: "TEXT", body: content.text, attachmentRef: null };
116
+ case "INTERACTIVE":
117
+ return { kind: "INTERACTIVE", body: content.title, attachmentRef: content.replyId };
118
+ case "AUDIO":
119
+ return { kind: "AUDIO", body: null, attachmentRef: content.mediaId };
120
+ default:
121
+ return { kind: "OTHER", body: null, attachmentRef: null };
122
+ }
123
+ }
124
+ __name(columnsOf, "columnsOf");
125
+ var later = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
126
+ var MAX_WRITE_ATTEMPTS = 6;
127
+ async function handleMessage(ctx, connection, event) {
128
+ const { store } = ctx.config;
129
+ if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
130
+ const columns = columnsOf(event.content);
131
+ const conversation = await openConversation(ctx, connection, event, columns.body !== null);
132
+ const inserted = await store.insertMessage({
133
+ conversationId: conversation.id,
134
+ tenantId: connection.tenantId,
135
+ channel: connection.channel,
136
+ direction: "INBOUND",
137
+ ...columns,
138
+ options: null,
139
+ externalId: event.externalId,
140
+ deliveryStatus: "RECEIVED",
141
+ authorKind: "CONTACT",
142
+ staffUserId: null,
143
+ createdAt: event.sentAt
144
+ });
145
+ if (!inserted.created) return { kind: "duplicate" };
146
+ if (event.optOut || conversation.state === "OPTED_OUT") return { kind: "opted-out", conversationId: conversation.id };
147
+ await notifyHost(ctx, conversation, inserted.message);
148
+ return { kind: "message", conversationId: conversation.id, messageId: inserted.message.id };
149
+ }
150
+ __name(handleMessage, "handleMessage");
151
+ async function openConversation(ctx, connection, event, carriesText) {
152
+ const { store } = ctx.config;
153
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
154
+ const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
155
+ const result = existing ? await updateExisting(ctx, connection, existing, event, carriesText) : await createFirst(ctx, connection, event, carriesText);
156
+ if (result) return result;
157
+ }
158
+ throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);
159
+ }
160
+ __name(openConversation, "openConversation");
161
+ async function createFirst(ctx, connection, event, carriesText) {
162
+ const state = event.optOut ? "OPTED_OUT" : "AGENT";
163
+ const created = await ctx.config.store.createConversation({
164
+ tenantId: connection.tenantId,
165
+ channel: connection.channel,
166
+ contactId: event.contactId,
167
+ contactName: event.contactName,
168
+ connectionId: connection.id,
169
+ state,
170
+ lastInboundAt: event.sentAt,
171
+ lastMessageAt: event.sentAt,
172
+ optedOutAt: event.optOut ? event.sentAt : null,
173
+ hasText: carriesText
174
+ });
175
+ return created.state === state && created.lastInboundAt?.getTime() === event.sentAt.getTime() ? created : null;
176
+ }
177
+ __name(createFirst, "createFirst");
178
+ async function updateExisting(ctx, connection, existing, event, carriesText) {
179
+ const state = await nextState(ctx, existing, event);
180
+ return ctx.config.store.updateConversation(
181
+ connection.tenantId,
182
+ existing.id,
183
+ {
184
+ // Left out when unchanged: the write never carries a state it did not decide.
185
+ ...state !== existing.state ? { state } : {},
186
+ ...event.optOut ? { optedOutAt: later(existing.optedOutAt, event.sentAt) } : {},
187
+ ...connection.id !== existing.connectionId ? { connectionId: connection.id } : {},
188
+ lastInboundAt: later(existing.lastInboundAt, event.sentAt),
189
+ lastMessageAt: later(existing.lastMessageAt, event.sentAt),
190
+ ...event.contactName ? { contactName: event.contactName } : {},
191
+ ...carriesText ? { hasText: true } : {}
192
+ },
193
+ { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
194
+ );
195
+ }
196
+ __name(updateExisting, "updateExisting");
197
+ async function nextState(ctx, conversation, event) {
198
+ if (event.optOut) return "OPTED_OUT";
199
+ if (conversation.state === "OPTED_OUT") {
200
+ if (conversation.optedOutAt && event.sentAt <= conversation.optedOutAt) return "OPTED_OUT";
201
+ } else if (conversation.state !== "CLOSED") {
202
+ return conversation.state;
203
+ }
204
+ const chosen = await ctx.config.hooks?.reopenState?.(conversation);
205
+ return chosen && chosen !== "OPTED_OUT" ? chosen : "AGENT";
206
+ }
207
+ __name(nextState, "nextState");
208
+ async function notifyHost(ctx, conversation, message) {
209
+ const hook = ctx.config.hooks?.onInboundMessage;
210
+ if (!hook) return;
211
+ try {
212
+ await hook({ conversation, message });
213
+ } catch (error) {
214
+ ctx.config.logger.error(`messaging.inbound: onInboundMessage failed for ${conversation.id}: ${errorText(error)}`, { error });
215
+ }
216
+ }
217
+ __name(notifyHost, "notifyHost");
218
+ async function handleOptOut(ctx, connection, event) {
219
+ const { store } = ctx.config;
220
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
221
+ const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
222
+ if (!existing) {
223
+ const created = await store.createConversation({
224
+ tenantId: connection.tenantId,
225
+ channel: connection.channel,
226
+ contactId: event.contactId,
227
+ contactName: null,
228
+ connectionId: connection.id,
229
+ state: "OPTED_OUT",
230
+ lastInboundAt: null,
231
+ lastMessageAt: null,
232
+ optedOutAt: event.at,
233
+ hasText: false
234
+ });
235
+ if (created.state === "OPTED_OUT") return { kind: "opted-out", conversationId: created.id };
236
+ continue;
237
+ }
238
+ const updated = await store.updateConversation(
239
+ connection.tenantId,
240
+ existing.id,
241
+ {
242
+ ...existing.state !== "OPTED_OUT" ? { state: "OPTED_OUT" } : {},
243
+ optedOutAt: later(existing.optedOutAt, event.at)
244
+ },
245
+ { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
246
+ );
247
+ if (updated) return { kind: "opted-out", conversationId: existing.id };
248
+ }
249
+ throw new Error(`conversation ${event.contactId} kept changing under this opt-out; retry`);
250
+ }
251
+ __name(handleOptOut, "handleOptOut");
252
+
253
+ // src/core/inbox.ts
254
+ var PROCESS_DELIVERY_JOB = "messaging.process-delivery";
255
+ async function receiveDelivery(ctx, channel, rawBody) {
256
+ const { store, clock, enqueue, logger } = ctx.config;
257
+ const recorded = await store.recordDelivery({ channel, bodyHash: bodyHash(rawBody), rawBody, receivedAt: clock.now() });
258
+ if (recorded.fresh) {
259
+ const queued = await enqueue.enqueue(
260
+ PROCESS_DELIVERY_JOB,
261
+ { deliveryId: recorded.id },
262
+ { dedupeKey: `${PROCESS_DELIVERY_JOB}:${recorded.id}` }
263
+ );
264
+ if (!queued.enqueued) logger.warn(`messaging.inbox: delivery ${recorded.id} not queued (${queued.reason ?? "no reason"})`);
265
+ }
266
+ return { deliveryId: recorded.id, fresh: recorded.fresh };
267
+ }
268
+ __name(receiveDelivery, "receiveDelivery");
269
+ async function processDelivery(ctx, deliveryId) {
270
+ const { store, clock, logger } = ctx.config;
271
+ const row = await store.getDelivery(deliveryId);
272
+ if (!row) return { kind: "missing" };
273
+ if (row.state === "PROCESSED") return { kind: "already-processed" };
274
+ const adapter = ctx.adapters.get(row.channel);
275
+ let events;
276
+ try {
277
+ if (!adapter) throw new Error(`no adapter mounted for channel "${row.channel}"`);
278
+ events = adapter.parse(row.rawBody);
279
+ } catch (error) {
280
+ const reason = errorText(error);
281
+ logger.warn(`messaging.inbox: delivery ${deliveryId} unreadable: ${reason}`);
282
+ await store.settleDelivery(deliveryId, { state: "PROCESSED", error: `unreadable: ${reason}`, at: clock.now() });
283
+ return { kind: "unreadable", reason };
284
+ }
285
+ try {
286
+ const outcomes = [];
287
+ for (const event of events) outcomes.push(await handleEvent(ctx, row.channel, event));
288
+ await handOverUnclaimed(ctx, row.channel, events, outcomes);
289
+ const unapplied = outcomes.filter((outcome) => outcome.kind === "receipt" && !outcome.applied).length;
290
+ if (unapplied > 0) {
291
+ const error = `${unapplied} receipt(s) for a message not stored yet`;
292
+ logger.warn(`messaging.inbox: delivery ${deliveryId}: ${error}`);
293
+ await store.settleDelivery(deliveryId, { state: "FAILED", error, at: clock.now() });
294
+ } else {
295
+ await store.settleDelivery(deliveryId, { state: "PROCESSED", error: null, at: clock.now() });
296
+ }
297
+ return { kind: "processed", events: outcomes };
298
+ } catch (error) {
299
+ await store.settleDelivery(deliveryId, { state: "FAILED", error: errorText(error), at: clock.now() });
300
+ throw error;
301
+ }
302
+ }
303
+ __name(processDelivery, "processDelivery");
304
+ async function handOverUnclaimed(ctx, channel, events, outcomes) {
305
+ const hook = ctx.config.hooks?.onUnclaimedEvents;
306
+ if (!hook) return;
307
+ const unclaimed = events.filter((_, index) => {
308
+ const outcome = outcomes[index];
309
+ return outcome?.kind === "dropped" && outcome.reason === "unknown-account";
310
+ });
311
+ if (unclaimed.length > 0) await hook(channel, unclaimed);
312
+ }
313
+ __name(handOverUnclaimed, "handOverUnclaimed");
314
+ async function reconcileInbox(ctx) {
315
+ const { store, clock, logger, reconcileAfterMs, maxDeliveryAttempts, reconcileBatchSize } = ctx.config;
316
+ const due = await store.listRetryableDeliveries({
317
+ receivedBefore: new Date(clock.now().getTime() - reconcileAfterMs),
318
+ maxAttempts: maxDeliveryAttempts,
319
+ take: reconcileBatchSize
320
+ });
321
+ let failed = 0;
322
+ for (const row of due) {
323
+ try {
324
+ await processDelivery(ctx, row.id);
325
+ } catch (error) {
326
+ failed += 1;
327
+ logger.warn(`messaging.inbox: delivery ${row.id} failed again: ${errorText(error)}`);
328
+ }
329
+ }
330
+ return { retried: due.length, failed };
331
+ }
332
+ __name(reconcileInbox, "reconcileInbox");
333
+
334
+ // src/core/retention.ts
335
+ async function sweepRetention(ctx) {
336
+ const { store, clock, retentionMs, retentionBatchSize, maxDeliveryAttempts } = ctx.config;
337
+ const cutoff = new Date(clock.now().getTime() - retentionMs);
338
+ const text = await store.purgeExpiredText({ cutoff, take: retentionBatchSize });
339
+ const deliveries = await store.purgeExpiredDeliveries({ cutoff, maxAttempts: maxDeliveryAttempts, take: retentionBatchSize });
340
+ return { ...text, deliveries, more: text.conversations === retentionBatchSize || deliveries >= retentionBatchSize };
341
+ }
342
+ __name(sweepRetention, "sweepRetention");
343
+
344
+ // src/core/sender.ts
345
+ async function sendMessage(ctx, input) {
346
+ const { store, clock } = ctx.config;
347
+ const conversation = await store.getConversation(input.tenantId, input.conversationId);
348
+ if (!conversation) throw new MessagingSendError("NOT_FOUND", `no conversation ${input.conversationId}`);
349
+ const { adapter, connection } = await admit(ctx, conversation);
350
+ const now = clock.now();
351
+ const recorded = await store.insertMessage({
352
+ conversationId: conversation.id,
353
+ tenantId: conversation.tenantId,
354
+ channel: conversation.channel,
355
+ direction: "OUTBOUND",
356
+ kind: input.content.kind === "TEXT" ? "TEXT" : "INTERACTIVE",
357
+ body: input.content.text,
358
+ options: optionsOf(input.content),
359
+ attachmentRef: null,
360
+ externalId: null,
361
+ deliveryStatus: "PENDING",
362
+ authorKind: input.author.kind,
363
+ staffUserId: input.author.kind === "STAFF" ? input.author.staffUserId ?? null : null,
364
+ createdAt: now
365
+ });
366
+ await store.updateConversation(conversation.tenantId, conversation.id, {
367
+ lastMessageAt: now,
368
+ hasText: true
369
+ });
370
+ let externalId;
371
+ try {
372
+ if (connection.credentialSealed === null) throw new Error("the connection holds no credential");
373
+ const credential = await ctx.config.secrets.open(connection.credentialSealed);
374
+ ({ externalId } = await adapter.send({
375
+ credential,
376
+ accountId: connection.externalAccountId,
377
+ to: conversation.contactId,
378
+ content: input.content
379
+ }));
380
+ } catch (error) {
381
+ const reason = error instanceof ChannelSendFailure ? `${error.code}: ${error.message}` : errorText(error);
382
+ await store.updateMessage(conversation.tenantId, recorded.message.id, {
383
+ deliveryStatus: "FAILED",
384
+ error: reason.slice(0, 500),
385
+ failedAt: clock.now()
386
+ });
387
+ throw new MessagingSendError("CHANNEL_FAILED", reason, recorded.message.id);
388
+ }
389
+ const accepted = await store.updateMessage(conversation.tenantId, recorded.message.id, {
390
+ externalId,
391
+ deliveryStatus: "ACCEPTED"
392
+ });
393
+ return accepted ?? recorded.message;
394
+ }
395
+ __name(sendMessage, "sendMessage");
396
+ async function admit(ctx, conversation) {
397
+ if (conversation.state === "OPTED_OUT") {
398
+ throw new MessagingSendError("OPTED_OUT", `conversation ${conversation.id} opted out`);
399
+ }
400
+ const adapter = ctx.adapters.get(conversation.channel);
401
+ if (!adapter) throw new MessagingSendError("UNKNOWN_CHANNEL", `no adapter for channel "${conversation.channel}"`);
402
+ const verdict = adapter.policy.check({ lastInboundAt: conversation.lastInboundAt, now: ctx.config.clock.now() });
403
+ if (!verdict.allowed) {
404
+ throw new MessagingSendError(verdict.reason, `conversation ${conversation.id}: the channel's window is closed`);
405
+ }
406
+ const connection = await ctx.config.store.getConnection(
407
+ conversation.tenantId,
408
+ conversation.connectionId
409
+ );
410
+ if (!connection || connection.status !== "CONNECTED") {
411
+ throw new MessagingSendError("NOT_CONNECTED", `conversation ${conversation.id}: its connection is not connected`);
412
+ }
413
+ return { adapter, connection };
414
+ }
415
+ __name(admit, "admit");
416
+ function optionsOf(content) {
417
+ if (content.kind === "BUTTONS") return JSON.stringify({ buttons: content.buttons });
418
+ if (content.kind === "LIST") return JSON.stringify({ buttonLabel: content.buttonLabel, sections: content.sections });
419
+ return null;
420
+ }
421
+ __name(optionsOf, "optionsOf");
422
+
423
+ // src/core/engine.ts
424
+ function createMessagingEngine(config) {
425
+ const ctx = engineContext(config);
426
+ const { store, clock } = ctx.config;
427
+ return {
428
+ /** The adapter mounted for a channel, or undefined. */
429
+ adapter: /* @__PURE__ */ __name((channel) => ctx.adapters.get(channel), "adapter"),
430
+ /** The channels this engine serves. */
431
+ channels: /* @__PURE__ */ __name(() => [...ctx.adapters.keys()], "channels"),
432
+ // ── The pipeline ─────────────────────────────────────────────────────────
433
+ /** Store a VERIFIED raw delivery and queue its processing. The edge answers 200 after this. */
434
+ receive: /* @__PURE__ */ __name((channel, rawBody) => receiveDelivery(ctx, channel, rawBody), "receive"),
435
+ /** The `process-delivery` job's body. */
436
+ processDelivery: /* @__PURE__ */ __name((deliveryId) => processDelivery(ctx, deliveryId), "processDelivery"),
437
+ /** The `reconcile-inbox` sweep's body. */
438
+ reconcile: /* @__PURE__ */ __name(() => reconcileInbox(ctx), "reconcile"),
439
+ /** The `retention` sweep's body. */
440
+ sweepRetention: /* @__PURE__ */ __name(() => sweepRetention(ctx), "sweepRetention"),
441
+ // ── Sending ──────────────────────────────────────────────────────────────
442
+ send: /* @__PURE__ */ __name((input) => sendMessage(ctx, input), "send"),
443
+ // ── Connections ──────────────────────────────────────────────────────────
444
+ connect: /* @__PURE__ */ __name((input) => connect(ctx, input), "connect"),
445
+ revoke: /* @__PURE__ */ __name((tenantId, connectionId, reason) => revoke(ctx, tenantId, connectionId, reason), "revoke"),
446
+ markError: /* @__PURE__ */ __name((tenantId, connectionId, reason) => markError(ctx, tenantId, connectionId, reason), "markError"),
447
+ listConnections: /* @__PURE__ */ __name((tenantId) => store.listConnections(tenantId), "listConnections"),
448
+ // ── Conversations, for the host's own surfaces ───────────────────────────
449
+ getConversation: /* @__PURE__ */ __name((tenantId, conversationId) => store.getConversation(tenantId, conversationId), "getConversation"),
450
+ listMessages: /* @__PURE__ */ __name((tenantId, conversationId) => store.listMessages(tenantId, conversationId), "listMessages"),
451
+ /**
452
+ * Move a conversation between AGENT, HUMAN and CLOSED (a hand-off). OPTED_OUT
453
+ * is the contact's alone, both ways: an opted-out conversation is not
454
+ * moved (null), and only the contact's next message re-opens it.
455
+ */
456
+ setState: /* @__PURE__ */ __name((tenantId, conversationId, state) => (
457
+ // ONE guarded write: an opt-out landing between a read and this write cannot be overwritten.
458
+ store.updateConversation(tenantId, conversationId, { state }, { stateNot: "OPTED_OUT" })
459
+ ), "setState"),
460
+ /** Replace the structured summary that outlives the text. */
461
+ setSummary: /* @__PURE__ */ __name((tenantId, conversationId, summary) => store.updateConversation(tenantId, conversationId, { summary, summaryUpdatedAt: clock.now() }), "setSummary"),
462
+ /** Store an audio message's transcript (deleted with the text). */
463
+ setTranscript: /* @__PURE__ */ __name(async (tenantId, messageId, transcript) => {
464
+ const message = await store.updateMessage(tenantId, messageId, { transcript });
465
+ if (message) await store.updateConversation(tenantId, message.conversationId, { hasText: true });
466
+ return message;
467
+ }, "setTranscript")
468
+ };
469
+ }
470
+ __name(createMessagingEngine, "createMessagingEngine");
471
+
472
+ // src/core/memory-store.ts
473
+ import { randomUUID } from "crypto";
474
+
475
+ // src/core/store.ts
476
+ var DELIVERY_RANK = {
477
+ RECEIVED: 0,
478
+ PENDING: 1,
479
+ ACCEPTED: 2,
480
+ SENT: 3,
481
+ DELIVERED: 4,
482
+ READ: 5,
483
+ FAILED: 6
484
+ };
485
+ var RECEIPT_COLUMN = {
486
+ SENT: "sentAt",
487
+ DELIVERED: "deliveredAt",
488
+ READ: "readAt",
489
+ FAILED: "failedAt"
490
+ };
491
+
492
+ // src/core/memory-store.ts
493
+ function createMemoryMessagingStore() {
494
+ const tables = {
495
+ deliveries: /* @__PURE__ */ new Map(),
496
+ connections: /* @__PURE__ */ new Map(),
497
+ conversations: /* @__PURE__ */ new Map(),
498
+ messages: /* @__PURE__ */ new Map()
499
+ };
500
+ return {
501
+ ...memoryInbox(tables),
502
+ ...memoryConnections(tables),
503
+ ...memoryConversations(tables),
504
+ ...memoryMessages(tables),
505
+ purgeExpiredText: /* @__PURE__ */ __name(async (input) => purge(tables, input), "purgeExpiredText"),
506
+ purgeExpiredDeliveries: /* @__PURE__ */ __name(async (input) => purgeDeliveries(tables, input), "purgeExpiredDeliveries"),
507
+ dump: /* @__PURE__ */ __name(() => ({
508
+ deliveries: [...tables.deliveries.values()].map(copy),
509
+ connections: [...tables.connections.values()].map(copy),
510
+ conversations: [...tables.conversations.values()].map(copy),
511
+ messages: [...tables.messages.values()].map(copy)
512
+ }), "dump")
513
+ };
514
+ }
515
+ __name(createMemoryMessagingStore, "createMemoryMessagingStore");
516
+ var copy = /* @__PURE__ */ __name((row) => ({ ...row }), "copy");
517
+ function without(row, key) {
518
+ return Object.fromEntries(Object.entries(row).filter(([name]) => name !== key));
519
+ }
520
+ __name(without, "without");
521
+ var deliveryView = /* @__PURE__ */ __name((row) => without(row, "bodyHash"), "deliveryView");
522
+ var connectionView = /* @__PURE__ */ __name((row) => without(row, "credentialSealed"), "connectionView");
523
+ function memoryInbox({ deliveries }) {
524
+ return {
525
+ async recordDelivery({ channel, bodyHash: bodyHash2, rawBody, receivedAt }) {
526
+ const existing = [...deliveries.values()].find((row) => row.channel === channel && row.bodyHash === bodyHash2);
527
+ if (existing) return { id: existing.id, fresh: false };
528
+ const id = randomUUID();
529
+ deliveries.set(id, { id, channel, bodyHash: bodyHash2, rawBody, state: "PENDING", attempts: 0, error: null, receivedAt, processedAt: null });
530
+ return { id, fresh: true };
531
+ },
532
+ async getDelivery(id) {
533
+ const row = deliveries.get(id);
534
+ return row ? deliveryView(row) : null;
535
+ },
536
+ async settleDelivery(id, { state, error, at }) {
537
+ const row = deliveries.get(id);
538
+ if (row) deliveries.set(id, { ...row, state, error, processedAt: at, attempts: row.attempts + 1 });
539
+ },
540
+ async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {
541
+ return [...deliveries.values()].filter((row) => row.state !== "PROCESSED" && row.attempts < maxAttempts && row.receivedAt < receivedBefore).sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime()).slice(0, take).map(deliveryView);
542
+ }
543
+ };
544
+ }
545
+ __name(memoryInbox, "memoryInbox");
546
+ function memoryConnections({ connections }) {
547
+ const findConnectionByAccount = /* @__PURE__ */ __name(async (channel, externalAccountId) => {
548
+ const row = [...connections.values()].find(
549
+ (candidate) => candidate.channel === channel && candidate.externalAccountId === externalAccountId
550
+ );
551
+ return row ? copy(row) : null;
552
+ }, "findConnectionByAccount");
553
+ return {
554
+ findConnectionByAccount,
555
+ async getConnection(tenantId, id) {
556
+ const row = connections.get(id);
557
+ return row && row.tenantId === tenantId ? copy(row) : null;
558
+ },
559
+ async listConnections(tenantId) {
560
+ return [...connections.values()].filter((row) => row.tenantId === tenantId).map(connectionView);
561
+ },
562
+ async saveConnection(input) {
563
+ const existing = [...connections.values()].find(
564
+ (candidate) => candidate.channel === input.channel && candidate.externalAccountId === input.externalAccountId
565
+ );
566
+ if (existing && existing.tenantId !== input.tenantId && existing.status !== "REVOKED") return null;
567
+ const row = {
568
+ id: existing?.id ?? randomUUID(),
569
+ ...input,
570
+ status: "CONNECTED",
571
+ statusReason: null,
572
+ revokedAt: null
573
+ };
574
+ connections.set(row.id, row);
575
+ return connectionView(row);
576
+ },
577
+ async setConnectionStatus(tenantId, id, patch) {
578
+ const row = connections.get(id);
579
+ if (!row || row.tenantId !== tenantId) return false;
580
+ connections.set(id, { ...row, ...patch });
581
+ return true;
582
+ }
583
+ };
584
+ }
585
+ __name(memoryConnections, "memoryConnections");
586
+ function memoryConversations({ conversations }) {
587
+ const findConversation = /* @__PURE__ */ __name(async (tenantId, channel, contactId) => {
588
+ const row = [...conversations.values()].find(
589
+ (candidate) => candidate.tenantId === tenantId && candidate.channel === channel && candidate.contactId === contactId
590
+ );
591
+ return row ? copy(row) : null;
592
+ }, "findConversation");
593
+ return {
594
+ findConversation,
595
+ async getConversation(tenantId, id) {
596
+ const row = conversations.get(id);
597
+ return row && row.tenantId === tenantId ? copy(row) : null;
598
+ },
599
+ async createConversation(input) {
600
+ const existing = await findConversation(input.tenantId, input.channel, input.contactId);
601
+ if (existing) return existing;
602
+ const row = {
603
+ id: randomUUID(),
604
+ ...input,
605
+ optedOutAt: input.optedOutAt ?? null,
606
+ summary: null,
607
+ summaryUpdatedAt: null,
608
+ createdAt: /* @__PURE__ */ new Date()
609
+ };
610
+ conversations.set(row.id, row);
611
+ return copy(row);
612
+ },
613
+ async updateConversation(tenantId, id, patch, guard) {
614
+ const row = conversations.get(id);
615
+ if (!row || row.tenantId !== tenantId) return null;
616
+ if (guard && !matchesGuard(row, guard)) return null;
617
+ const next = { ...row, ...patch };
618
+ conversations.set(id, next);
619
+ return copy(next);
620
+ }
621
+ };
622
+ }
623
+ __name(memoryConversations, "memoryConversations");
624
+ var sameTime = /* @__PURE__ */ __name((a, b) => a === null || b === null ? a === b : a.getTime() === b.getTime(), "sameTime");
625
+ var GUARDED_TIMES = ["lastInboundAt", "lastMessageAt", "optedOutAt"];
626
+ function matchesGuard(row, guard) {
627
+ if (guard.state !== void 0 && row.state !== guard.state) return false;
628
+ if (guard.stateNot !== void 0 && row.state === guard.stateNot) return false;
629
+ return GUARDED_TIMES.every((key) => {
630
+ const wanted = guard[key];
631
+ return wanted === void 0 || sameTime(row[key], wanted);
632
+ });
633
+ }
634
+ __name(matchesGuard, "matchesGuard");
635
+ function memoryMessages({ messages }) {
636
+ const findMessageByExternalId = /* @__PURE__ */ __name(async (channel, externalId) => {
637
+ const row = [...messages.values()].find((candidate) => candidate.channel === channel && candidate.externalId === externalId);
638
+ return row ? copy(row) : null;
639
+ }, "findMessageByExternalId");
640
+ return {
641
+ findMessageByExternalId,
642
+ async insertMessage(input) {
643
+ const existing = input.externalId === null ? null : await findMessageByExternalId(input.channel, input.externalId);
644
+ if (existing) return { created: false, message: existing };
645
+ const row = {
646
+ id: randomUUID(),
647
+ ...input,
648
+ transcript: null,
649
+ error: null,
650
+ sentAt: null,
651
+ deliveredAt: null,
652
+ readAt: null,
653
+ failedAt: null
654
+ };
655
+ messages.set(row.id, row);
656
+ return { created: true, message: copy(row) };
657
+ },
658
+ async updateMessage(tenantId, id, patch) {
659
+ const row = messages.get(id);
660
+ if (!row || row.tenantId !== tenantId) return null;
661
+ const taken = patch.externalId === void 0 ? null : await findMessageByExternalId(row.channel, patch.externalId);
662
+ if (taken && taken.id !== id) throw Object.assign(new Error("unique"), { code: "P2002" });
663
+ const next = { ...row, ...patch };
664
+ messages.set(id, next);
665
+ return copy(next);
666
+ },
667
+ async listMessages(tenantId, conversationId) {
668
+ return [...messages.values()].filter((row) => row.tenantId === tenantId && row.conversationId === conversationId).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()).map(copy);
669
+ },
670
+ async applyReceipt({ tenantId, channel, externalId, status, at, error }) {
671
+ const row = [...messages.values()].find(
672
+ (candidate) => candidate.tenantId === tenantId && candidate.channel === channel && candidate.externalId === externalId && candidate.direction === "OUTBOUND"
673
+ );
674
+ if (!row) return false;
675
+ const column = RECEIPT_COLUMN[status];
676
+ const stamp = row[column] === null;
677
+ const forward = DELIVERY_RANK[status] > DELIVERY_RANK[row.deliveryStatus];
678
+ messages.set(row.id, {
679
+ ...row,
680
+ ...stamp ? { [column]: at, ...error !== null ? { error } : {} } : {},
681
+ ...forward ? { deliveryStatus: status } : {}
682
+ });
683
+ return true;
684
+ }
685
+ };
686
+ }
687
+ __name(memoryMessages, "memoryMessages");
688
+ function purgeDeliveries({ deliveries }, { cutoff, maxAttempts, take }) {
689
+ const due = /* @__PURE__ */ __name((match) => [...deliveries.values()].filter((row) => row.receivedAt < cutoff && match(row)).sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime()).slice(0, take), "due");
690
+ const rows = [...due((row) => row.state === "PROCESSED"), ...due((row) => row.state === "FAILED" && row.attempts >= maxAttempts)];
691
+ for (const row of rows) deliveries.delete(row.id);
692
+ return rows.length;
693
+ }
694
+ __name(purgeDeliveries, "purgeDeliveries");
695
+ function purge({ conversations, messages }, { cutoff, take }) {
696
+ const expired = /* @__PURE__ */ __name((row) => row.lastMessageAt !== null && row.lastMessageAt < cutoff, "expired");
697
+ const due = [...conversations.values()].filter((row) => row.hasText && expired(row)).sort((a, b) => a.lastMessageAt.getTime() - b.lastMessageAt.getTime()).slice(0, take);
698
+ const ids = new Set(due.map((row) => row.id));
699
+ let purged = 0;
700
+ for (const row of messages.values()) {
701
+ if (!ids.has(row.conversationId) || row.createdAt > cutoff) continue;
702
+ messages.set(row.id, { ...row, body: null, options: null, transcript: null });
703
+ purged += 1;
704
+ }
705
+ for (const row of due) {
706
+ const current = conversations.get(row.id);
707
+ if (expired(current)) conversations.set(row.id, { ...current, hasText: false });
708
+ }
709
+ return { conversations: due.length, messages: purged };
710
+ }
711
+ __name(purge, "purge");
712
+
713
+ // src/core/prisma-store.ts
714
+ var UNIQUE_VIOLATION = "P2002";
715
+ var isUniqueViolation = /* @__PURE__ */ __name((error) => error?.code === UNIQUE_VIOLATION, "isUniqueViolation");
716
+ var CONNECTION_VIEW = {
717
+ id: true,
718
+ tenantId: true,
719
+ channel: true,
720
+ externalAccountId: true,
721
+ externalParentId: true,
722
+ displayAddress: true,
723
+ status: true,
724
+ statusReason: true,
725
+ connectedAt: true,
726
+ revokedAt: true
727
+ };
728
+ var DELIVERY_VIEW = {
729
+ id: true,
730
+ channel: true,
731
+ rawBody: true,
732
+ state: true,
733
+ attempts: true,
734
+ error: true,
735
+ receivedAt: true,
736
+ processedAt: true
737
+ };
738
+ var pickConversation = /* @__PURE__ */ __name((row) => ({
739
+ id: row.id,
740
+ tenantId: row.tenantId,
741
+ channel: row.channel,
742
+ contactId: row.contactId,
743
+ contactName: row.contactName,
744
+ connectionId: row.connectionId,
745
+ state: row.state,
746
+ lastInboundAt: row.lastInboundAt,
747
+ lastMessageAt: row.lastMessageAt,
748
+ optedOutAt: row.optedOutAt,
749
+ hasText: row.hasText,
750
+ summary: row.summary,
751
+ summaryUpdatedAt: row.summaryUpdatedAt,
752
+ createdAt: row.createdAt
753
+ }), "pickConversation");
754
+ function createPrismaMessagingStore(db) {
755
+ const client = typeof db === "function" ? db : async () => db;
756
+ return {
757
+ ...inboxOperations(client),
758
+ ...connectionOperations(client),
759
+ ...conversationOperations(client),
760
+ ...messageOperations(client),
761
+ purgeExpiredText: /* @__PURE__ */ __name((input) => purgeExpiredText(client, input), "purgeExpiredText"),
762
+ purgeExpiredDeliveries: /* @__PURE__ */ __name((input) => purgeExpiredDeliveries(client, input), "purgeExpiredDeliveries")
763
+ };
764
+ }
765
+ __name(createPrismaMessagingStore, "createPrismaMessagingStore");
766
+ function inboxOperations(client) {
767
+ return {
768
+ async recordDelivery({ channel, bodyHash: bodyHash2, rawBody, receivedAt }) {
769
+ const delegate = (await client()).messagingInboxDelivery;
770
+ const key = { channel_bodyHash: { channel, bodyHash: bodyHash2 } };
771
+ const existing = await delegate.findUnique({ where: key, select: { id: true } });
772
+ if (existing) return { id: existing.id, fresh: false };
773
+ try {
774
+ const row = await delegate.create({
775
+ data: { channel, bodyHash: bodyHash2, rawBody, receivedAt },
776
+ select: { id: true }
777
+ });
778
+ return { id: row.id, fresh: true };
779
+ } catch (error) {
780
+ if (!isUniqueViolation(error)) throw error;
781
+ const raced = await delegate.findUnique({ where: key, select: { id: true } });
782
+ return { id: raced.id, fresh: false };
783
+ }
784
+ },
785
+ async getDelivery(id) {
786
+ return await (await client()).messagingInboxDelivery.findUnique({
787
+ where: { id },
788
+ select: DELIVERY_VIEW
789
+ }) ?? null;
790
+ },
791
+ async settleDelivery(id, { state, error, at }) {
792
+ await (await client()).messagingInboxDelivery.updateMany({
793
+ where: { id },
794
+ data: { state, error, processedAt: at, attempts: { increment: 1 } }
795
+ });
796
+ },
797
+ async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {
798
+ return await (await client()).messagingInboxDelivery.findMany({
799
+ where: { state: { in: ["PENDING", "FAILED"] }, attempts: { lt: maxAttempts }, receivedAt: { lt: receivedBefore } },
800
+ orderBy: { receivedAt: "asc" },
801
+ take,
802
+ select: DELIVERY_VIEW
803
+ });
804
+ }
805
+ };
806
+ }
807
+ __name(inboxOperations, "inboxOperations");
808
+ function connectionOperations(client) {
809
+ const findConnectionByAccount = /* @__PURE__ */ __name(async (channel, externalAccountId) => await (await client()).messagingConnection.findUnique({
810
+ where: { channel_externalAccountId: { channel, externalAccountId } }
811
+ }) ?? null, "findConnectionByAccount");
812
+ return {
813
+ findConnectionByAccount,
814
+ async getConnection(tenantId, id) {
815
+ return await (await client()).messagingConnection.findFirst({ where: { id, tenantId } }) ?? null;
816
+ },
817
+ async listConnections(tenantId) {
818
+ return await (await client()).messagingConnection.findMany({
819
+ where: { tenantId },
820
+ orderBy: { connectedAt: "asc" },
821
+ select: CONNECTION_VIEW
822
+ });
823
+ },
824
+ async saveConnection(input) {
825
+ const delegate = (await client()).messagingConnection;
826
+ const data = { ...input, status: "CONNECTED", statusReason: null, revokedAt: null };
827
+ for (let attempt = 0; attempt < 2; attempt += 1) {
828
+ const existing = await findConnectionByAccount(input.channel, input.externalAccountId);
829
+ if (!existing) {
830
+ try {
831
+ return await delegate.create({ data, select: CONNECTION_VIEW });
832
+ } catch (error) {
833
+ if (!isUniqueViolation(error)) throw error;
834
+ continue;
835
+ }
836
+ }
837
+ const where = existing.tenantId === input.tenantId ? { id: existing.id, tenantId: input.tenantId } : { id: existing.id, status: "REVOKED" };
838
+ const updated = await delegate.updateMany({ where, data });
839
+ if (updated.count === 0) return null;
840
+ return await delegate.findUnique({ where: { id: existing.id }, select: CONNECTION_VIEW });
841
+ }
842
+ return null;
843
+ },
844
+ async setConnectionStatus(tenantId, id, patch) {
845
+ const result = await (await client()).messagingConnection.updateMany({ where: { id, tenantId }, data: patch });
846
+ return result.count > 0;
847
+ }
848
+ };
849
+ }
850
+ __name(connectionOperations, "connectionOperations");
851
+ function conversationOperations(client) {
852
+ const findConversation = /* @__PURE__ */ __name(async (tenantId, channel, contactId) => {
853
+ const row = await (await client()).messagingConversation.findUnique({
854
+ where: { tenantId_channel_contactId: { tenantId, channel, contactId } }
855
+ });
856
+ return row ? pickConversation(row) : null;
857
+ }, "findConversation");
858
+ return {
859
+ findConversation,
860
+ async getConversation(tenantId, id) {
861
+ const row = await (await client()).messagingConversation.findFirst({ where: { id, tenantId } });
862
+ return row ? pickConversation(row) : null;
863
+ },
864
+ async createConversation(input) {
865
+ try {
866
+ return pickConversation(await (await client()).messagingConversation.create({ data: input }));
867
+ } catch (error) {
868
+ if (!isUniqueViolation(error)) throw error;
869
+ const raced = await findConversation(input.tenantId, input.channel, input.contactId);
870
+ if (!raced) throw error;
871
+ return raced;
872
+ }
873
+ },
874
+ async updateConversation(tenantId, id, patch, guard) {
875
+ const delegate = (await client()).messagingConversation;
876
+ const result = await delegate.updateMany({ where: { id, tenantId, ...guardWhere(guard) }, data: patch });
877
+ if (result.count === 0) return null;
878
+ return pickConversation(await delegate.findUnique({ where: { id } }));
879
+ }
880
+ };
881
+ }
882
+ __name(conversationOperations, "conversationOperations");
883
+ function guardWhere(guard) {
884
+ if (!guard) return {};
885
+ const { state, stateNot, lastInboundAt, lastMessageAt, optedOutAt } = guard;
886
+ return {
887
+ ...state !== void 0 ? { state } : {},
888
+ ...stateNot !== void 0 ? { state: { not: stateNot } } : {},
889
+ ...lastInboundAt !== void 0 ? { lastInboundAt } : {},
890
+ ...lastMessageAt !== void 0 ? { lastMessageAt } : {},
891
+ ...optedOutAt !== void 0 ? { optedOutAt } : {}
892
+ };
893
+ }
894
+ __name(guardWhere, "guardWhere");
895
+ function messageOperations(client) {
896
+ const findMessageByExternalId = /* @__PURE__ */ __name(async (channel, externalId) => await (await client()).messagingMessage.findUnique({
897
+ where: { channel_externalId: { channel, externalId } }
898
+ }) ?? null, "findMessageByExternalId");
899
+ return {
900
+ findMessageByExternalId,
901
+ async insertMessage(input) {
902
+ try {
903
+ return { created: true, message: await (await client()).messagingMessage.create({ data: input }) };
904
+ } catch (error) {
905
+ if (!isUniqueViolation(error) || input.externalId === null) throw error;
906
+ const existing = await findMessageByExternalId(input.channel, input.externalId);
907
+ if (!existing) throw error;
908
+ return { created: false, message: existing };
909
+ }
910
+ },
911
+ async updateMessage(tenantId, id, patch) {
912
+ const delegate = (await client()).messagingMessage;
913
+ const result = await delegate.updateMany({ where: { id, tenantId }, data: patch });
914
+ if (result.count === 0) return null;
915
+ return await delegate.findUnique({ where: { id } });
916
+ },
917
+ async listMessages(tenantId, conversationId) {
918
+ return await (await client()).messagingMessage.findMany({
919
+ where: { tenantId, conversationId },
920
+ orderBy: { createdAt: "asc" }
921
+ });
922
+ },
923
+ applyReceipt: /* @__PURE__ */ __name((input) => applyReceipt(client, input), "applyReceipt")
924
+ };
925
+ }
926
+ __name(messageOperations, "messageOperations");
927
+ async function applyReceipt(client, input) {
928
+ const { tenantId, channel, externalId, status, at, error } = input;
929
+ const delegate = (await client()).messagingMessage;
930
+ const scope = { tenantId, channel, externalId, direction: "OUTBOUND" };
931
+ const found = await delegate.findFirst({ where: scope, select: { id: true } });
932
+ if (!found) return false;
933
+ const column = RECEIPT_COLUMN[status];
934
+ await delegate.updateMany({
935
+ where: { id: found.id, [column]: null },
936
+ data: { [column]: at, ...error !== null ? { error } : {} }
937
+ });
938
+ await delegate.updateMany({
939
+ where: { id: found.id, deliveryStatus: { in: statusesBelow(status) } },
940
+ data: { deliveryStatus: status }
941
+ });
942
+ return true;
943
+ }
944
+ __name(applyReceipt, "applyReceipt");
945
+ async function purgeExpiredText(client, { cutoff, take }) {
946
+ const db = await client();
947
+ const due = await db.messagingConversation.findMany({
948
+ where: { hasText: true, lastMessageAt: { lt: cutoff } },
949
+ orderBy: { lastMessageAt: "asc" },
950
+ take,
951
+ select: { id: true }
952
+ });
953
+ if (due.length === 0) return { conversations: 0, messages: 0 };
954
+ const ids = due.map((row) => row.id);
955
+ const purged = await db.messagingMessage.updateMany({
956
+ where: { conversationId: { in: ids }, createdAt: { lte: cutoff } },
957
+ data: { body: null, options: null, transcript: null }
958
+ });
959
+ await db.messagingConversation.updateMany({
960
+ where: { id: { in: ids }, lastMessageAt: { lt: cutoff } },
961
+ data: { hasText: false }
962
+ });
963
+ return { conversations: due.length, messages: purged.count };
964
+ }
965
+ __name(purgeExpiredText, "purgeExpiredText");
966
+ async function purgeExpiredDeliveries(client, { cutoff, maxAttempts, take }) {
967
+ const delegate = (await client()).messagingInboxDelivery;
968
+ const batches = [
969
+ { state: "PROCESSED", receivedAt: { lt: cutoff } },
970
+ { state: "FAILED", receivedAt: { lt: cutoff }, attempts: { gte: maxAttempts } }
971
+ ];
972
+ let deleted = 0;
973
+ for (const where of batches) {
974
+ const due = await delegate.findMany({ where, orderBy: { receivedAt: "asc" }, take, select: { id: true } });
975
+ if (due.length === 0) continue;
976
+ deleted += (await delegate.deleteMany({ where: { id: { in: due.map((row) => row.id) } } })).count;
977
+ }
978
+ return deleted;
979
+ }
980
+ __name(purgeExpiredDeliveries, "purgeExpiredDeliveries");
981
+ function statusesBelow(status) {
982
+ return Object.keys(DELIVERY_RANK).filter((candidate) => DELIVERY_RANK[candidate] < DELIVERY_RANK[status]);
983
+ }
984
+ __name(statusesBelow, "statusesBelow");
985
+ export {
986
+ ChannelSendFailure,
987
+ MESSAGING_DEFAULTS,
988
+ MessagingConnectError,
989
+ MessagingSendError,
990
+ OPEN_SEND_POLICY,
991
+ PROCESS_DELIVERY_JOB,
992
+ bodyHash,
993
+ createMemoryMessagingStore,
994
+ createMessagingEngine,
995
+ createPrismaMessagingStore,
996
+ isWindowOpen,
997
+ serviceWindowPolicy
998
+ };
999
+ //# sourceMappingURL=index.js.map