@terreno/comms 57.1.0 → 57.3.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/README.md +58 -0
  2. package/dist/adapters/expoPush.d.ts +54 -0
  3. package/dist/adapters/expoPush.js +400 -0
  4. package/dist/adapters/sendgrid.d.ts +3 -0
  5. package/dist/adapters/sendgrid.js +7 -1
  6. package/dist/adapters/twilioSms.d.ts +36 -0
  7. package/dist/adapters/twilioSms.js +232 -0
  8. package/dist/adapters/twilioVerify.d.ts +44 -0
  9. package/dist/adapters/twilioVerify.js +212 -0
  10. package/dist/commsApp.d.ts +4 -1
  11. package/dist/commsApp.js +28 -2
  12. package/dist/commsQuery.d.ts +30 -0
  13. package/dist/commsQuery.js +134 -0
  14. package/dist/commsRetry.d.ts +16 -0
  15. package/dist/commsRetry.js +79 -0
  16. package/dist/commsService.d.ts +11 -4
  17. package/dist/commsService.js +217 -47
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.js +3 -1
  20. package/dist/routes/commsDashboard.d.ts +11 -0
  21. package/dist/routes/commsDashboard.js +414 -0
  22. package/dist/templates.d.ts +9 -0
  23. package/dist/templates.js +34 -1
  24. package/dist/types.d.ts +11 -0
  25. package/dist/webhooks/sendgridWebhooks.d.ts +16 -0
  26. package/dist/webhooks/sendgridWebhooks.js +251 -0
  27. package/dist/webhooks/twilioWebhooks.d.ts +18 -0
  28. package/dist/webhooks/twilioWebhooks.js +175 -0
  29. package/package.json +27 -6
  30. package/src/adapters/expoPush.test.ts +585 -0
  31. package/src/adapters/expoPush.ts +304 -0
  32. package/src/adapters/sendgrid.ts +8 -0
  33. package/src/adapters/twilioSms.test.ts +374 -0
  34. package/src/adapters/twilioSms.ts +237 -0
  35. package/src/adapters/twilioVerify.test.ts +207 -0
  36. package/src/adapters/twilioVerify.ts +227 -0
  37. package/src/commsApp.test.ts +13 -0
  38. package/src/commsApp.ts +38 -3
  39. package/src/commsQuery.test.ts +165 -0
  40. package/src/commsQuery.ts +162 -0
  41. package/src/commsRetry.ts +87 -0
  42. package/src/commsService.test.ts +68 -0
  43. package/src/commsService.ts +177 -20
  44. package/src/index.ts +9 -2
  45. package/src/routes/commsDashboard.test.ts +310 -0
  46. package/src/routes/commsDashboard.ts +327 -0
  47. package/src/templates.test.ts +63 -1
  48. package/src/templates.ts +47 -0
  49. package/src/tests/bunSetup.ts +8 -0
  50. package/src/types.ts +13 -0
  51. package/src/webhooks/sendgridWebhooks.test.ts +520 -0
  52. package/src/webhooks/sendgridWebhooks.ts +166 -0
  53. package/src/webhooks/twilioWebhooks.test.ts +352 -0
  54. package/src/webhooks/twilioWebhooks.ts +154 -0
  55. package/dist/routes/commsExplorer.d.ts +0 -7
  56. package/dist/routes/commsExplorer.js +0 -147
  57. package/src/routes/commsExplorer.ts +0 -114
package/src/commsApp.ts CHANGED
@@ -1,14 +1,24 @@
1
- import {APIError, logger, type TerrenoPlugin} from "@terreno/api";
1
+ import {
2
+ type AdminContribution,
3
+ APIError,
4
+ logger,
5
+ type TerrenoPlugin,
6
+ type WebhooksApp,
7
+ } from "@terreno/api";
2
8
  import type express from "express";
3
9
 
4
10
  import {CommsService} from "./commsService";
5
11
  import {PushToken} from "./models/pushToken";
6
- import {addCommsExplorerRoute} from "./routes/commsExplorer";
12
+ import {addCommsDashboardRoutes} from "./routes/commsDashboard";
7
13
  import {addPushTokenRoutes} from "./routes/pushTokens";
8
14
  import type {CommsOptions} from "./types";
15
+ import {maybeRegisterSendGridCommsWebhooks} from "./webhooks/sendgridWebhooks";
16
+ import {maybeRegisterTwilioCommsWebhooks} from "./webhooks/twilioWebhooks";
9
17
 
10
18
  export interface CommsAppOptions extends CommsOptions {
11
19
  basePath?: string;
20
+ webhookPublicUrl?: string;
21
+ webhooks?: WebhooksApp;
12
22
  }
13
23
 
14
24
  let registeredCommsService: CommsService | undefined;
@@ -43,6 +53,31 @@ export class CommsApp implements TerrenoPlugin {
43
53
  });
44
54
 
45
55
  addPushTokenRoutes(app, {basePath: `${basePath}/pushTokens`, openApi});
46
- addCommsExplorerRoute(app, {openApi, path: `${basePath}/messages`});
56
+ addCommsDashboardRoutes(app, {basePath, openApi, service: this.service});
57
+ maybeRegisterTwilioCommsWebhooks({
58
+ basePath,
59
+ publicUrl: this.options.webhookPublicUrl,
60
+ service: this.service,
61
+ sms: this.options.sms,
62
+ webhooks: this.options.webhooks,
63
+ });
64
+ maybeRegisterSendGridCommsWebhooks({
65
+ basePath,
66
+ mail: this.options.mail,
67
+ service: this.service,
68
+ webhooks: this.options.webhooks,
69
+ });
70
+ }
71
+
72
+ adminContribution(): AdminContribution {
73
+ return {
74
+ customScreens: [
75
+ {
76
+ displayName: "Comms Dashboard",
77
+ icon: "paper-plane",
78
+ name: "comms",
79
+ },
80
+ ],
81
+ };
47
82
  }
48
83
  }
@@ -0,0 +1,165 @@
1
+ import {describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import {DateTime} from "luxon";
4
+ import mongoose from "mongoose";
5
+
6
+ import {
7
+ buildCommsMessageMatch,
8
+ defaultStatsRange,
9
+ parseCommsListFilters,
10
+ parseCommsListPagination,
11
+ parseRetryManyLimit,
12
+ } from "./commsQuery";
13
+
14
+ describe("parseCommsListFilters", () => {
15
+ it("trims strings and drops blank or non-string values", () => {
16
+ const filters = parseCommsListFilters({
17
+ channel: " mail ",
18
+ errorClass: "",
19
+ provider: ["sendgrid"],
20
+ q: " ",
21
+ status: "failed",
22
+ to: 1234,
23
+ });
24
+ assert.equal(filters.channel, "mail");
25
+ assert.equal(filters.status, "failed");
26
+ assert.isUndefined(filters.errorClass);
27
+ assert.isUndefined(filters.provider);
28
+ assert.isUndefined(filters.q);
29
+ assert.isUndefined(filters.to);
30
+ });
31
+ });
32
+
33
+ describe("parseCommsListPagination", () => {
34
+ it("defaults to page 1 with a 20 row limit", () => {
35
+ assert.deepEqual(parseCommsListPagination({}), {limit: 20, page: 1, skip: 0});
36
+ });
37
+
38
+ it("computes skip and clamps the limit to 100", () => {
39
+ assert.deepEqual(parseCommsListPagination({limit: "10", page: "3"}), {
40
+ limit: 10,
41
+ page: 3,
42
+ skip: 20,
43
+ });
44
+ assert.deepEqual(parseCommsListPagination({limit: "5000", page: "-4"}), {
45
+ limit: 100,
46
+ page: 1,
47
+ skip: 0,
48
+ });
49
+ });
50
+ });
51
+
52
+ describe("parseRetryManyLimit", () => {
53
+ it("falls back to the cap and clamps out-of-range values", () => {
54
+ assert.equal(parseRetryManyLimit(undefined), 100);
55
+ assert.equal(parseRetryManyLimit("not-a-number"), 100);
56
+ assert.equal(parseRetryManyLimit("250"), 100);
57
+ assert.equal(parseRetryManyLimit("0"), 1);
58
+ assert.equal(parseRetryManyLimit("25"), 25);
59
+ });
60
+ });
61
+
62
+ describe("defaultStatsRange", () => {
63
+ it("spans the trailing seven days", () => {
64
+ const {endDate, startDate} = defaultStatsRange();
65
+ assert.equal(Math.round(endDate.diff(startDate, "days").days), 7);
66
+ });
67
+ });
68
+
69
+ describe("buildCommsMessageMatch", () => {
70
+ it("always excludes soft-deleted rows", () => {
71
+ assert.deepEqual(buildCommsMessageMatch({}), {deleted: {$ne: true}});
72
+ });
73
+
74
+ it("maps scalar filters straight through", () => {
75
+ const match = buildCommsMessageMatch({
76
+ channel: "mail",
77
+ errorClass: "transient",
78
+ errorCode: "timeout",
79
+ provider: "sendgrid",
80
+ status: "failed",
81
+ templateId: "welcome",
82
+ to: "a***@example.com",
83
+ });
84
+ assert.equal(match.channel, "mail");
85
+ assert.equal(match.errorClass, "transient");
86
+ assert.equal(match.errorCode, "timeout");
87
+ assert.equal(match.provider, "sendgrid");
88
+ assert.equal(match.status, "failed");
89
+ assert.equal(match.templateId, "welcome");
90
+ assert.equal(match.to, "a***@example.com");
91
+ });
92
+
93
+ it("casts id filters and rejects malformed ones", () => {
94
+ const userId = new mongoose.Types.ObjectId().toString();
95
+ const retriedFromId = new mongoose.Types.ObjectId().toString();
96
+ const match = buildCommsMessageMatch({retriedFromId, userId});
97
+ assert.equal(String(match.userId), userId);
98
+ assert.equal(String(match.retriedFromId), retriedFromId);
99
+
100
+ assert.throws(() => buildCommsMessageMatch({userId: "nope"}), /Invalid userId/);
101
+ assert.throws(() => buildCommsMessageMatch({retriedFromId: "nope"}), /Invalid retriedFromId/);
102
+ });
103
+
104
+ it("builds created bounds from either end of the range", () => {
105
+ const startOnly = buildCommsMessageMatch({startDate: "2026-08-01T00:00:00.000Z"}) as {
106
+ created: {$gte?: Date; $lte?: Date};
107
+ };
108
+ assert.instanceOf(startOnly.created.$gte, Date);
109
+ assert.isUndefined(startOnly.created.$lte);
110
+
111
+ const endOnly = buildCommsMessageMatch({endDate: "2026-08-31T00:00:00.000Z"}) as {
112
+ created: {$gte?: Date; $lte?: Date};
113
+ };
114
+ assert.instanceOf(endOnly.created.$lte, Date);
115
+ assert.isUndefined(endOnly.created.$gte);
116
+ });
117
+
118
+ it("rejects invalid dates and inverted ranges", () => {
119
+ assert.throws(() => buildCommsMessageMatch({startDate: "yesterday"}), /Invalid startDate/);
120
+ assert.throws(() => buildCommsMessageMatch({endDate: "soon"}), /Invalid endDate/);
121
+ assert.throws(
122
+ () =>
123
+ buildCommsMessageMatch({
124
+ endDate: "2026-08-01T00:00:00.000Z",
125
+ startDate: "2026-08-31T00:00:00.000Z",
126
+ }),
127
+ /startDate must not be after endDate/
128
+ );
129
+ });
130
+
131
+ it("applies the default stats range only when both bounds are absent", () => {
132
+ const defaulted = buildCommsMessageMatch({}, {applyDefaultStatsRange: true}) as {
133
+ created: {$gte: Date; $lte: Date};
134
+ };
135
+ const spanDays = DateTime.fromJSDate(defaulted.created.$lte).diff(
136
+ DateTime.fromJSDate(defaulted.created.$gte),
137
+ "days"
138
+ ).days;
139
+ assert.equal(Math.round(spanDays), 7);
140
+
141
+ const explicit = buildCommsMessageMatch(
142
+ {startDate: "2026-08-01T00:00:00.000Z"},
143
+ {applyDefaultStatsRange: true}
144
+ ) as {created: {$gte: Date; $lte?: Date}};
145
+ assert.isUndefined(explicit.created.$lte);
146
+ });
147
+
148
+ it("searches subject, error, and recipient, escaping regex metacharacters", () => {
149
+ const match = buildCommsMessageMatch({q: "a.b*c"}) as {
150
+ $or: Array<Record<string, {$regex: string}>>;
151
+ };
152
+ assert.lengthOf(match.$or, 3);
153
+ assert.equal(match.$or[0].subject.$regex, "a\\.b\\*c");
154
+ assert.equal(match.$or[1].error.$regex, "a\\.b\\*c");
155
+ assert.equal(match.$or[2].to.$regex, "a\\.b\\*c");
156
+ });
157
+
158
+ it("adds a last-4 suffix clause for redacted destinations", () => {
159
+ const match = buildCommsMessageMatch({q: "1234"}) as {
160
+ $or: Array<Record<string, {$regex: string}>>;
161
+ };
162
+ assert.lengthOf(match.$or, 4);
163
+ assert.equal(match.$or[3].to.$regex, "1234$");
164
+ });
165
+ });
@@ -0,0 +1,162 @@
1
+ import {APIError} from "@terreno/api";
2
+ import {DateTime} from "luxon";
3
+ import mongoose from "mongoose";
4
+
5
+ export interface CommsListFilters {
6
+ channel?: string;
7
+ endDate?: string;
8
+ errorClass?: string;
9
+ errorCode?: string;
10
+ provider?: string;
11
+ q?: string;
12
+ retriedFromId?: string;
13
+ startDate?: string;
14
+ status?: string;
15
+ templateId?: string;
16
+ to?: string;
17
+ userId?: string;
18
+ }
19
+
20
+ export interface CommsListPagination {
21
+ limit: number;
22
+ page: number;
23
+ skip: number;
24
+ }
25
+
26
+ const DEFAULT_LIMIT = 20;
27
+ const MAX_LIMIT = 100;
28
+ const DEFAULT_STATS_DAYS = 7;
29
+
30
+ const escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
+
32
+ const queryString = (value: unknown): string | undefined => {
33
+ if (typeof value !== "string") {
34
+ return undefined;
35
+ }
36
+ const trimmed = value.trim();
37
+ return trimmed.length > 0 ? trimmed : undefined;
38
+ };
39
+
40
+ export const parseCommsListFilters = (source: Record<string, unknown>): CommsListFilters => ({
41
+ channel: queryString(source.channel),
42
+ endDate: queryString(source.endDate),
43
+ errorClass: queryString(source.errorClass),
44
+ errorCode: queryString(source.errorCode),
45
+ provider: queryString(source.provider),
46
+ q: queryString(source.q),
47
+ retriedFromId: queryString(source.retriedFromId),
48
+ startDate: queryString(source.startDate),
49
+ status: queryString(source.status),
50
+ templateId: queryString(source.templateId),
51
+ to: queryString(source.to),
52
+ userId: queryString(source.userId),
53
+ });
54
+
55
+ export const parseCommsListPagination = (source: Record<string, unknown>): CommsListPagination => {
56
+ const page = Math.max(1, Number.parseInt(String(source.page ?? ""), 10) || 1);
57
+ const limit = Math.min(
58
+ MAX_LIMIT,
59
+ Math.max(1, Number.parseInt(String(source.limit ?? ""), 10) || DEFAULT_LIMIT)
60
+ );
61
+ return {limit, page, skip: (page - 1) * limit};
62
+ };
63
+
64
+ export const parseRetryManyLimit = (value: unknown): number => {
65
+ const parsed = Number.parseInt(String(value ?? ""), 10);
66
+ if (Number.isNaN(parsed)) {
67
+ return MAX_LIMIT;
68
+ }
69
+ return Math.min(MAX_LIMIT, Math.max(1, parsed));
70
+ };
71
+
72
+ const parseIsoDate = (value: string, field: "startDate" | "endDate"): DateTime => {
73
+ const parsed = DateTime.fromISO(value, {zone: "utc"});
74
+ if (!parsed.isValid) {
75
+ throw new APIError({status: 400, title: `Invalid ${field} format`});
76
+ }
77
+ return parsed;
78
+ };
79
+
80
+ export const defaultStatsRange = (): {endDate: DateTime; startDate: DateTime} => {
81
+ const endDate = DateTime.utc();
82
+ return {endDate, startDate: endDate.minus({days: DEFAULT_STATS_DAYS})};
83
+ };
84
+
85
+ export const buildCommsMessageMatch = (
86
+ filters: CommsListFilters,
87
+ options?: {applyDefaultStatsRange?: boolean}
88
+ ): Record<string, unknown> => {
89
+ const match: Record<string, unknown> & {created?: {$gte?: Date; $lte?: Date}} = {
90
+ deleted: {$ne: true},
91
+ };
92
+
93
+ if (filters.channel) {
94
+ match.channel = filters.channel;
95
+ }
96
+ if (filters.provider) {
97
+ match.provider = filters.provider;
98
+ }
99
+ if (filters.status) {
100
+ match.status = filters.status;
101
+ }
102
+ if (filters.errorClass) {
103
+ match.errorClass = filters.errorClass;
104
+ }
105
+ if (filters.errorCode) {
106
+ match.errorCode = filters.errorCode;
107
+ }
108
+ if (filters.templateId) {
109
+ match.templateId = filters.templateId;
110
+ }
111
+ if (filters.to) {
112
+ match.to = filters.to;
113
+ }
114
+ if (filters.userId) {
115
+ if (!mongoose.isValidObjectId(filters.userId)) {
116
+ throw new APIError({status: 400, title: "Invalid userId"});
117
+ }
118
+ match.userId = new mongoose.Types.ObjectId(filters.userId);
119
+ }
120
+ if (filters.retriedFromId) {
121
+ if (!mongoose.isValidObjectId(filters.retriedFromId)) {
122
+ throw new APIError({status: 400, title: "Invalid retriedFromId"});
123
+ }
124
+ match.retriedFromId = new mongoose.Types.ObjectId(filters.retriedFromId);
125
+ }
126
+
127
+ let start = filters.startDate ? parseIsoDate(filters.startDate, "startDate") : undefined;
128
+ let end = filters.endDate ? parseIsoDate(filters.endDate, "endDate") : undefined;
129
+ if (options?.applyDefaultStatsRange && !start && !end) {
130
+ const range = defaultStatsRange();
131
+ start = range.startDate;
132
+ end = range.endDate;
133
+ }
134
+ if (start || end) {
135
+ match.created = {};
136
+ if (start) {
137
+ match.created.$gte = start.toJSDate();
138
+ }
139
+ if (end) {
140
+ match.created.$lte = end.toJSDate();
141
+ }
142
+ if (start && end && start.toMillis() > end.toMillis()) {
143
+ throw new APIError({status: 400, title: "startDate must not be after endDate"});
144
+ }
145
+ }
146
+
147
+ if (filters.q) {
148
+ const escaped = escapeRegex(filters.q);
149
+ const clauses: Record<string, unknown>[] = [
150
+ {subject: {$options: "i", $regex: escaped}},
151
+ {error: {$options: "i", $regex: escaped}},
152
+ {to: {$options: "i", $regex: escaped}},
153
+ ];
154
+ const last4 = filters.q.replace(/\s/g, "");
155
+ if (/^[A-Za-z0-9]{4}$/.test(last4)) {
156
+ clauses.push({to: {$options: "i", $regex: `${escapeRegex(last4)}$`}});
157
+ }
158
+ match.$or = clauses;
159
+ }
160
+
161
+ return match;
162
+ };
@@ -0,0 +1,87 @@
1
+ import {APIError} from "@terreno/api";
2
+ import {DateTime} from "luxon";
3
+
4
+ import type {CommsMessageDocument} from "./modelTypes";
5
+ import type {CommsChannel} from "./types";
6
+
7
+ export const COMMS_RETRY_NOT_RETRYABLE = "comms-retry-not-retryable";
8
+ export const COMMS_RETRY_PAYLOAD_EXPIRED = "comms-retry-payload-expired";
9
+ export const COMMS_RETRY_CHANNEL_UNCONFIGURED = "comms-retry-channel-unconfigured";
10
+
11
+ export interface CommsRetryBlock {
12
+ code: string;
13
+ title: string;
14
+ }
15
+
16
+ const RETRYABLE_STATUSES = new Set(["bounced", "failed"]);
17
+
18
+ export const isPayloadPresent = (message: CommsMessageDocument): boolean => {
19
+ if (message.payload === undefined || message.payload === null) {
20
+ return false;
21
+ }
22
+ if (message.payloadExpiresAt && DateTime.fromJSDate(message.payloadExpiresAt) <= DateTime.utc()) {
23
+ return false;
24
+ }
25
+ return true;
26
+ };
27
+
28
+ export const evaluateRetryBlock = ({
29
+ isChannelConfigured,
30
+ message,
31
+ }: {
32
+ isChannelConfigured: (channel: CommsChannel) => boolean;
33
+ message: CommsMessageDocument;
34
+ }): CommsRetryBlock | undefined => {
35
+ if (message.channel === "verification") {
36
+ return {
37
+ code: COMMS_RETRY_NOT_RETRYABLE,
38
+ title: "Verification messages are not retryable",
39
+ };
40
+ }
41
+ if (!RETRYABLE_STATUSES.has(message.status)) {
42
+ return {
43
+ code: COMMS_RETRY_NOT_RETRYABLE,
44
+ title: "Only failed or bounced messages can be retried",
45
+ };
46
+ }
47
+ if (message.errorClass === "permanent") {
48
+ return {
49
+ code: COMMS_RETRY_NOT_RETRYABLE,
50
+ title: "Permanent failures cannot be retried",
51
+ };
52
+ }
53
+ if (!isPayloadPresent(message)) {
54
+ return {
55
+ code: COMMS_RETRY_PAYLOAD_EXPIRED,
56
+ title: "Retained payload is missing or expired",
57
+ };
58
+ }
59
+ if (!isChannelConfigured(message.channel)) {
60
+ return {
61
+ code: COMMS_RETRY_CHANNEL_UNCONFIGURED,
62
+ title: "Comms channel is not configured",
63
+ };
64
+ }
65
+ return undefined;
66
+ };
67
+
68
+ export const throwRetryBlock = (block: CommsRetryBlock): never => {
69
+ throw new APIError({
70
+ code: block.code,
71
+ status: 400,
72
+ title: block.title,
73
+ });
74
+ };
75
+
76
+ export const serializeCommsMessage = (
77
+ message: CommsMessageDocument,
78
+ isChannelConfigured: (channel: CommsChannel) => boolean
79
+ ): Record<string, unknown> => {
80
+ const json = message.toJSON() as Record<string, unknown>;
81
+ const block = evaluateRetryBlock({isChannelConfigured, message});
82
+ return {
83
+ ...json,
84
+ retryable: !block,
85
+ retryDisabledReason: block?.title,
86
+ };
87
+ };
@@ -709,6 +709,39 @@ describe("CommsService", () => {
709
709
  const row = await CommsMessage.findExactlyOne({status: "cancelled"});
710
710
  assert.equal(row.attemptCount, 1);
711
711
  assert.equal((row.payload as {to?: string}).to, "person@example.com");
712
+ assert.equal(result.loggedMessageId, String(row._id));
713
+ });
714
+
715
+ it("attaches loggedMessageId when beforeSend cancels a push send", async (): Promise<void> => {
716
+ const userId = new mongoose.Types.ObjectId();
717
+ await PushToken.upsert(
718
+ {token: "ExponentPushToken[cancel]"},
719
+ {
720
+ active: true,
721
+ lastSeenAt: DateTime.utc().toJSDate(),
722
+ platform: "ios",
723
+ userId,
724
+ }
725
+ );
726
+ let sendCount = 0;
727
+ const service = new CommsService({
728
+ beforeSend: async (): Promise<{cancel: boolean}> => ({cancel: true}),
729
+ push: {
730
+ id: "cancel-push",
731
+ sendPush: async (): Promise<SendResult[]> => {
732
+ sendCount += 1;
733
+ return [{accepted: true}];
734
+ },
735
+ },
736
+ });
737
+
738
+ const results = await service.sendPushToUser({body: "Hello", title: "Title", userId});
739
+
740
+ assert.equal(sendCount, 0);
741
+ assert.equal(results.length, 1);
742
+ assert.isFalse(results[0]?.accepted);
743
+ const row = await CommsMessage.findExactlyOne({channel: "push", status: "cancelled"});
744
+ assert.equal(results[0]?.loggedMessageId, String(row._id));
712
745
  });
713
746
 
714
747
  it("lets beforeSend replace the outbound message", async (): Promise<void> => {
@@ -1244,6 +1277,41 @@ describe("CommsService", () => {
1244
1277
  warnSpy.mockRestore();
1245
1278
  });
1246
1279
 
1280
+ it("rethrows when applying a delivery event fails to save", async (): Promise<void> => {
1281
+ const warnSpy = spyOn(logger, "warn");
1282
+ const service = new CommsService({
1283
+ mail: {
1284
+ id: "event-mail-save-fail",
1285
+ sendMail: async (): Promise<SendResult> => ({
1286
+ accepted: true,
1287
+ providerMessageId: "mail-save-fail",
1288
+ }),
1289
+ },
1290
+ });
1291
+ await service.sendMail({subject: "Welcome", to: "person@example.com"});
1292
+ const saveSpy = spyOn(CommsMessage.prototype, "save").mockImplementation(
1293
+ async (): Promise<never> => {
1294
+ throw new Error("save failed");
1295
+ }
1296
+ );
1297
+ let threw = false;
1298
+ try {
1299
+ await service.recordDeliveryEvent({
1300
+ channel: "mail",
1301
+ providerMessageId: "mail-save-fail",
1302
+ status: "delivered",
1303
+ });
1304
+ } catch (error: unknown) {
1305
+ threw = error instanceof Error && error.message === "save failed";
1306
+ }
1307
+ saveSpy.mockRestore();
1308
+ assert.isTrue(threw);
1309
+ assert.isTrue(
1310
+ warnSpy.mock.calls.some((call) => String(call[0]).includes("Failed to apply delivery event"))
1311
+ );
1312
+ warnSpy.mockRestore();
1313
+ });
1314
+
1247
1315
  it("retries startVerification once on transient failure and never retries checkVerification", async (): Promise<void> => {
1248
1316
  let startCalls = 0;
1249
1317
  let checkCalls = 0;