@frigear-nu/inbox 0.0.0-stage → 0.0.1

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 (174) hide show
  1. package/README.md +39 -2
  2. package/dist/module.d.mts +452 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +242 -0
  5. package/dist/runtime/access.d.ts +1 -0
  6. package/dist/runtime/access.js +62 -0
  7. package/dist/runtime/app/components/InboxChannelSlideover.d.vue.ts +12 -0
  8. package/dist/runtime/app/components/InboxChannelSlideover.vue +171 -0
  9. package/dist/runtime/app/components/InboxChannelSlideover.vue.d.ts +12 -0
  10. package/dist/runtime/app/components/InboxComposer.d.vue.ts +12 -0
  11. package/dist/runtime/app/components/InboxComposer.vue +71 -0
  12. package/dist/runtime/app/components/InboxComposer.vue.d.ts +12 -0
  13. package/dist/runtime/app/components/InboxConversation.d.vue.ts +8 -0
  14. package/dist/runtime/app/components/InboxConversation.vue +82 -0
  15. package/dist/runtime/app/components/InboxConversation.vue.d.ts +8 -0
  16. package/dist/runtime/app/components/InboxHideSlideover.d.vue.ts +12 -0
  17. package/dist/runtime/app/components/InboxHideSlideover.vue +54 -0
  18. package/dist/runtime/app/components/InboxHideSlideover.vue.d.ts +12 -0
  19. package/dist/runtime/app/components/InboxMailboxSlideover.d.vue.ts +11 -0
  20. package/dist/runtime/app/components/InboxMailboxSlideover.vue +125 -0
  21. package/dist/runtime/app/components/InboxMailboxSlideover.vue.d.ts +11 -0
  22. package/dist/runtime/app/composables/index.d.ts +6 -0
  23. package/dist/runtime/app/composables/index.js +5 -0
  24. package/dist/runtime/app/composables/useInboxChannelActions.d.ts +15 -0
  25. package/dist/runtime/app/composables/useInboxChannelActions.js +45 -0
  26. package/dist/runtime/app/composables/useInboxLinks.d.ts +11 -0
  27. package/dist/runtime/app/composables/useInboxLinks.js +17 -0
  28. package/dist/runtime/app/composables/useInboxMailboxActions.d.ts +14 -0
  29. package/dist/runtime/app/composables/useInboxMailboxActions.js +47 -0
  30. package/dist/runtime/app/composables/useInboxThreadActions.d.ts +29 -0
  31. package/dist/runtime/app/composables/useInboxThreadActions.js +76 -0
  32. package/dist/runtime/app/composables/useInboxTranslate.d.ts +3 -0
  33. package/dist/runtime/app/composables/useInboxTranslate.js +7 -0
  34. package/dist/runtime/app/dashboard/InboxMine.d.vue.ts +3 -0
  35. package/dist/runtime/app/dashboard/InboxMine.vue +25 -0
  36. package/dist/runtime/app/dashboard/InboxMine.vue.d.ts +3 -0
  37. package/dist/runtime/app/dashboard/InboxUnassigned.d.vue.ts +3 -0
  38. package/dist/runtime/app/dashboard/InboxUnassigned.vue +25 -0
  39. package/dist/runtime/app/dashboard/InboxUnassigned.vue.d.ts +3 -0
  40. package/dist/runtime/app/pages/admin-settings.d.vue.ts +3 -0
  41. package/dist/runtime/app/pages/admin-settings.vue +161 -0
  42. package/dist/runtime/app/pages/admin-settings.vue.d.ts +3 -0
  43. package/dist/runtime/app/pages/admin-thread.d.vue.ts +3 -0
  44. package/dist/runtime/app/pages/admin-thread.vue +234 -0
  45. package/dist/runtime/app/pages/admin-thread.vue.d.ts +3 -0
  46. package/dist/runtime/app/pages/admin.d.vue.ts +3 -0
  47. package/dist/runtime/app/pages/admin.vue +211 -0
  48. package/dist/runtime/app/pages/admin.vue.d.ts +3 -0
  49. package/dist/runtime/channels/email.d.ts +2 -0
  50. package/dist/runtime/channels/email.js +8 -0
  51. package/dist/runtime/channels/form.d.ts +2 -0
  52. package/dist/runtime/channels/form.js +9 -0
  53. package/dist/runtime/channels/instagram.d.ts +2 -0
  54. package/dist/runtime/channels/instagram.js +5 -0
  55. package/dist/runtime/channels/messenger.d.ts +2 -0
  56. package/dist/runtime/channels/messenger.js +5 -0
  57. package/dist/runtime/channels/whatsapp.d.ts +2 -0
  58. package/dist/runtime/channels/whatsapp.js +5 -0
  59. package/dist/runtime/i18n/lang/da.json +247 -0
  60. package/dist/runtime/i18n/lang/en.json +247 -0
  61. package/dist/runtime/menus.d.ts +2 -0
  62. package/dist/runtime/menus.js +19 -0
  63. package/dist/runtime/server/db/schema.postgresql.d.ts +1216 -0
  64. package/dist/runtime/server/db/schema.postgresql.js +154 -0
  65. package/dist/runtime/server/db/schema.sqlite.d.ts +1294 -0
  66. package/dist/runtime/server/db/schema.sqlite.js +154 -0
  67. package/dist/runtime/server/plugins/forms.d.ts +2 -0
  68. package/dist/runtime/server/plugins/forms.js +55 -0
  69. package/dist/runtime/server/plugins/links.d.ts +2 -0
  70. package/dist/runtime/server/plugins/links.js +18 -0
  71. package/dist/runtime/server/plugins/notify.d.ts +2 -0
  72. package/dist/runtime/server/plugins/notify.js +24 -0
  73. package/dist/runtime/server/plugins/seed.d.ts +2 -0
  74. package/dist/runtime/server/plugins/seed.js +7 -0
  75. package/dist/runtime/server/plugins/teams.d.ts +2 -0
  76. package/dist/runtime/server/plugins/teams.js +3 -0
  77. package/dist/runtime/server/policies.d.ts +2 -0
  78. package/dist/runtime/server/policies.js +15 -0
  79. package/dist/runtime/server/routes/admin/audit.get.d.ts +2 -0
  80. package/dist/runtime/server/routes/admin/audit.get.js +43 -0
  81. package/dist/runtime/server/routes/admin/channel.delete.d.ts +2 -0
  82. package/dist/runtime/server/routes/admin/channel.delete.js +13 -0
  83. package/dist/runtime/server/routes/admin/channel.patch.d.ts +2 -0
  84. package/dist/runtime/server/routes/admin/channel.patch.js +24 -0
  85. package/dist/runtime/server/routes/admin/channels.get.d.ts +2 -0
  86. package/dist/runtime/server/routes/admin/channels.get.js +10 -0
  87. package/dist/runtime/server/routes/admin/channels.post.d.ts +2 -0
  88. package/dist/runtime/server/routes/admin/channels.post.js +21 -0
  89. package/dist/runtime/server/routes/admin/contact-erase.post.d.ts +2 -0
  90. package/dist/runtime/server/routes/admin/contact-erase.post.js +20 -0
  91. package/dist/runtime/server/routes/admin/contact-export.get.d.ts +2 -0
  92. package/dist/runtime/server/routes/admin/contact-export.get.js +41 -0
  93. package/dist/runtime/server/routes/admin/mailbox.delete.d.ts +2 -0
  94. package/dist/runtime/server/routes/admin/mailbox.delete.js +14 -0
  95. package/dist/runtime/server/routes/admin/mailbox.get.d.ts +2 -0
  96. package/dist/runtime/server/routes/admin/mailbox.get.js +9 -0
  97. package/dist/runtime/server/routes/admin/mailbox.patch.d.ts +2 -0
  98. package/dist/runtime/server/routes/admin/mailbox.patch.js +17 -0
  99. package/dist/runtime/server/routes/admin/mailboxes.get.d.ts +2 -0
  100. package/dist/runtime/server/routes/admin/mailboxes.get.js +5 -0
  101. package/dist/runtime/server/routes/admin/mailboxes.post.d.ts +2 -0
  102. package/dist/runtime/server/routes/admin/mailboxes.post.js +22 -0
  103. package/dist/runtime/server/routes/admin/summary.get.d.ts +2 -0
  104. package/dist/runtime/server/routes/admin/summary.get.js +19 -0
  105. package/dist/runtime/server/routes/admin/thread-assignees.get.d.ts +2 -0
  106. package/dist/runtime/server/routes/admin/thread-assignees.get.js +11 -0
  107. package/dist/runtime/server/routes/admin/thread-hide.post.d.ts +2 -0
  108. package/dist/runtime/server/routes/admin/thread-hide.post.js +23 -0
  109. package/dist/runtime/server/routes/admin/thread-messages.post.d.ts +2 -0
  110. package/dist/runtime/server/routes/admin/thread-messages.post.js +10 -0
  111. package/dist/runtime/server/routes/admin/thread-notes.post.d.ts +2 -0
  112. package/dist/runtime/server/routes/admin/thread-notes.post.js +10 -0
  113. package/dist/runtime/server/routes/admin/thread.get.d.ts +2 -0
  114. package/dist/runtime/server/routes/admin/thread.get.js +27 -0
  115. package/dist/runtime/server/routes/admin/thread.patch.d.ts +2 -0
  116. package/dist/runtime/server/routes/admin/thread.patch.js +23 -0
  117. package/dist/runtime/server/routes/admin/threads.get.d.ts +2 -0
  118. package/dist/runtime/server/routes/admin/threads.get.js +49 -0
  119. package/dist/runtime/server/routes/webhooks/channel.post.d.ts +2 -0
  120. package/dist/runtime/server/routes/webhooks/channel.post.js +11 -0
  121. package/dist/runtime/server/routes/webhooks/email.post.d.ts +2 -0
  122. package/dist/runtime/server/routes/webhooks/email.post.js +38 -0
  123. package/dist/runtime/server/routes/webhooks/meta.get.d.ts +2 -0
  124. package/dist/runtime/server/routes/webhooks/meta.get.js +19 -0
  125. package/dist/runtime/server/routes/webhooks/meta.post.d.ts +2 -0
  126. package/dist/runtime/server/routes/webhooks/meta.post.js +29 -0
  127. package/dist/runtime/server/search-index.d.ts +2 -0
  128. package/dist/runtime/server/search-index.js +7 -0
  129. package/dist/runtime/server/tasks/retention.d.ts +2 -0
  130. package/dist/runtime/server/tasks/retention.js +12 -0
  131. package/dist/runtime/server/utils/inbox-audit.d.ts +17 -0
  132. package/dist/runtime/server/utils/inbox-audit.js +35 -0
  133. package/dist/runtime/server/utils/inbox-channels.d.ts +42 -0
  134. package/dist/runtime/server/utils/inbox-channels.js +73 -0
  135. package/dist/runtime/server/utils/inbox-config.d.ts +12 -0
  136. package/dist/runtime/server/utils/inbox-config.js +8 -0
  137. package/dist/runtime/server/utils/inbox-dto.d.ts +19 -0
  138. package/dist/runtime/server/utils/inbox-dto.js +92 -0
  139. package/dist/runtime/server/utils/inbox-ingest.d.ts +43 -0
  140. package/dist/runtime/server/utils/inbox-ingest.js +136 -0
  141. package/dist/runtime/server/utils/inbox-integrations.d.ts +7 -0
  142. package/dist/runtime/server/utils/inbox-integrations.js +13 -0
  143. package/dist/runtime/server/utils/inbox-mailboxes.d.ts +14 -0
  144. package/dist/runtime/server/utils/inbox-mailboxes.js +27 -0
  145. package/dist/runtime/server/utils/inbox-registry.d.ts +7 -0
  146. package/dist/runtime/server/utils/inbox-registry.js +10 -0
  147. package/dist/runtime/server/utils/inbox-retention.d.ts +57 -0
  148. package/dist/runtime/server/utils/inbox-retention.js +167 -0
  149. package/dist/runtime/server/utils/inbox-schemas.d.ts +123 -0
  150. package/dist/runtime/server/utils/inbox-schemas.js +78 -0
  151. package/dist/runtime/server/utils/inbox-search.d.ts +8 -0
  152. package/dist/runtime/server/utils/inbox-search.js +2 -0
  153. package/dist/runtime/server/utils/inbox-seed.d.ts +9 -0
  154. package/dist/runtime/server/utils/inbox-seed.js +35 -0
  155. package/dist/runtime/server/utils/inbox-send.d.ts +25 -0
  156. package/dist/runtime/server/utils/inbox-send.js +84 -0
  157. package/dist/runtime/server/utils/inbox-tombstones.d.ts +25 -0
  158. package/dist/runtime/server/utils/inbox-tombstones.js +47 -0
  159. package/dist/runtime/server/utils/inbox-webhooks.d.ts +8 -0
  160. package/dist/runtime/server/utils/inbox-webhooks.js +10 -0
  161. package/dist/runtime/server/utils/inbox.d.ts +79 -0
  162. package/dist/runtime/server/utils/inbox.js +134 -0
  163. package/dist/runtime/utils/api.d.ts +40 -0
  164. package/dist/runtime/utils/api.js +43 -0
  165. package/dist/runtime/utils/index.d.ts +44 -0
  166. package/dist/runtime/utils/index.js +27 -0
  167. package/dist/runtime/utils/payloads.d.ts +99 -0
  168. package/dist/runtime/utils/payloads.js +173 -0
  169. package/dist/runtime/utils/registry.d.ts +17 -0
  170. package/dist/runtime/utils/registry.js +29 -0
  171. package/dist/runtime/utils/signature.d.ts +14 -0
  172. package/dist/runtime/utils/signature.js +16 -0
  173. package/dist/types.d.mts +7 -0
  174. package/package.json +118 -3
@@ -0,0 +1,92 @@
1
+ import { isoDate } from "@frigear-nu/module-kit/server";
2
+ import { readGrants } from "@frigear-nu/auth/grants";
3
+ export function toInboxMailboxDto(row) {
4
+ return {
5
+ id: row.id,
6
+ key: row.key,
7
+ ownerType: row.ownerType,
8
+ ownerId: row.ownerId ?? null,
9
+ name: row.name,
10
+ grants: readGrants(row.grants),
11
+ retentionDays: row.retentionDays ?? null,
12
+ createdAt: isoDate(row.createdAt),
13
+ updatedAt: isoDate(row.updatedAt)
14
+ };
15
+ }
16
+ export function toInboxChannelAccountDto(row, secretConfigured) {
17
+ return {
18
+ id: row.id,
19
+ mailboxId: row.mailboxId,
20
+ channel: row.channel,
21
+ address: row.address,
22
+ config: row.config ?? {},
23
+ secretRef: row.secretRef ?? null,
24
+ secretConfigured,
25
+ enabled: row.enabled,
26
+ createdAt: isoDate(row.createdAt),
27
+ updatedAt: isoDate(row.updatedAt)
28
+ };
29
+ }
30
+ export function toInboxContactDto(row, pii) {
31
+ return {
32
+ id: row.id,
33
+ channel: row.channel,
34
+ name: row.name ?? null,
35
+ erasedAt: isoDate(row.erasedAt),
36
+ ...pii ? { email: row.email ?? null, phone: row.phone ?? null, externalId: row.erasedAt ? null : row.externalId, userId: row.userId ?? null } : {}
37
+ };
38
+ }
39
+ export function toInboxContactDetails(row) {
40
+ return {
41
+ id: row.id,
42
+ channel: row.channel,
43
+ externalId: row.externalId,
44
+ name: row.name ?? null,
45
+ email: row.email ?? null,
46
+ phone: row.phone ?? null,
47
+ userId: row.userId ?? null
48
+ };
49
+ }
50
+ export function toInboxThreadDto(row) {
51
+ return {
52
+ id: row.id,
53
+ mailboxId: row.mailboxId,
54
+ contactId: row.contactId,
55
+ channelAccountId: row.channelAccountId ?? null,
56
+ channel: row.channel,
57
+ subject: row.subject ?? null,
58
+ status: row.status,
59
+ assigneeId: row.assigneeId ?? null,
60
+ hiddenBelow: row.hiddenBelow ?? null,
61
+ lastMessageAt: isoDate(row.lastMessageAt),
62
+ anonymisedAt: isoDate(row.anonymisedAt),
63
+ createdAt: isoDate(row.createdAt),
64
+ updatedAt: isoDate(row.updatedAt)
65
+ };
66
+ }
67
+ export function toInboxMessageDto(row, author = null, pii = false) {
68
+ return {
69
+ id: row.id,
70
+ threadId: row.threadId,
71
+ direction: row.direction,
72
+ authorId: row.authorId ?? null,
73
+ author,
74
+ body: row.body,
75
+ attachments: row.attachments ?? [],
76
+ ...pii ? { cc: row.cc?.length ? row.cc : null } : {},
77
+ contactId: row.contactId ?? null,
78
+ createdAt: isoDate(row.createdAt)
79
+ };
80
+ }
81
+ export function toInboxAuditDto(row, actor = null) {
82
+ return {
83
+ id: row.id,
84
+ threadId: row.threadId ?? null,
85
+ contactId: row.contactId ?? null,
86
+ actorId: row.actorId ?? null,
87
+ actor,
88
+ action: row.action,
89
+ data: row.data ?? null,
90
+ createdAt: isoDate(row.createdAt)
91
+ };
92
+ }
@@ -0,0 +1,43 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { InboxInboundMessage, InboxMessageDto, InboxThreadDto } from '../../../types.js';
3
+ import type { InboxChannelAccountRow } from './inbox-dto.js';
4
+ export type InboxReceiveResult = {
5
+ status: 'received';
6
+ thread: InboxThreadDto;
7
+ message: InboxMessageDto;
8
+ } | {
9
+ status: 'duplicate';
10
+ messageId: string;
11
+ } | {
12
+ status: 'ignored';
13
+ reason: 'no_account' | 'disabled' | 'removed';
14
+ };
15
+ /** Control characters (CR, LF, tabs, ...) become a space, so a subject can never carry a header line. */
16
+ export declare function inboxCleanText(value: string): string;
17
+ /** A stored subject: one line, at most 500 characters, `null` when empty. */
18
+ export declare function inboxCleanSubject(value: string | null | undefined): string | null;
19
+ /** The start of a message for the thread list. */
20
+ export declare function inboxPreview(body: string): string | null;
21
+ /** Addresses are compared lower case for email (and the form slug), as stored. */
22
+ export declare function inboxNormaliseAddress(channel: string, address: string): string;
23
+ /** The enabled account of a channel at `address` (or with `accountId`). */
24
+ export declare function inboxFindAccount(channel: string, ref: {
25
+ accountId?: string;
26
+ address?: string;
27
+ }): Promise<InboxChannelAccountRow | undefined>;
28
+ /**
29
+ * Stores an inbound message of `channel`: finds the account, the contact and the thread (`authenticated` decides
30
+ * whether it may join an existing one), stores the message once per
31
+ * provider id and channel account, reopens a closed or pending thread and fires `inbox:message:received` (and
32
+ * `inbox:thread:status-changed` when the status moved). A message delivered twice answers `duplicate`; one for an
33
+ * address no enabled account has answers `ignored`, and so does a replay of a message retention or an erase removed
34
+ * (`removed`, see `inboxTombstoneThreads`), so a provider stops retrying either.
35
+ */
36
+ export declare function inboxReceive(event: H3Event, channel: string, inbound: InboxInboundMessage, account?: InboxChannelAccountRow): Promise<InboxReceiveResult>;
37
+ /** Stores a batch of inbound messages one by one; a failure of one is logged and counted, the others still go in. */
38
+ export declare function inboxReceiveAll(event: H3Event, channel: string, messages: InboxInboundMessage[]): Promise<{
39
+ received: number;
40
+ duplicates: number;
41
+ ignored: number;
42
+ failed: number;
43
+ }>;
@@ -0,0 +1,136 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { and, desc, eq, inArray, isNull } from "drizzle-orm";
3
+ import { newId } from "@frigear-nu/module-kit/id";
4
+ import { inboxThreadSearchText } from "./inbox-search.js";
5
+ import { toInboxMessageDto, toInboxThreadDto } from "./inbox-dto.js";
6
+ export function inboxCleanText(value) {
7
+ return value.replace(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]+/g, " ").replace(/ {2,}/g, " ").trim();
8
+ }
9
+ export function inboxCleanSubject(value) {
10
+ return value ? inboxCleanText(value).slice(0, 500) || null : null;
11
+ }
12
+ export function inboxPreview(body) {
13
+ return inboxCleanText(body).slice(0, 160) || null;
14
+ }
15
+ export function inboxNormaliseAddress(channel, address) {
16
+ const trimmed = address.trim();
17
+ return channel === "email" || channel === "form" ? trimmed.toLowerCase() : trimmed;
18
+ }
19
+ export async function inboxFindAccount(channel, ref) {
20
+ if (ref.accountId) {
21
+ const [row2] = await db.select().from(schema.inboxChannelAccounts).where(and(eq(schema.inboxChannelAccounts.id, ref.accountId), eq(schema.inboxChannelAccounts.channel, channel))).limit(1);
22
+ return row2;
23
+ }
24
+ if (!ref.address) return void 0;
25
+ const [row] = await db.select().from(schema.inboxChannelAccounts).where(and(eq(schema.inboxChannelAccounts.channel, channel), eq(schema.inboxChannelAccounts.address, inboxNormaliseAddress(channel, ref.address)))).limit(1);
26
+ return row;
27
+ }
28
+ async function existingMessageId(channelAccountId, externalId) {
29
+ const [row] = await db.select({ id: schema.inboxMessages.id }).from(schema.inboxMessages).where(and(eq(schema.inboxMessages.channelAccountId, channelAccountId), eq(schema.inboxMessages.externalId, externalId))).limit(1);
30
+ return row?.id;
31
+ }
32
+ async function upsertContact(channel, input, authenticated) {
33
+ const where = and(eq(schema.inboxContacts.channel, channel), eq(schema.inboxContacts.externalId, input.externalId));
34
+ await db.insert(schema.inboxContacts).values({
35
+ id: newId("icn"),
36
+ channel,
37
+ externalId: input.externalId,
38
+ name: input.name ?? null,
39
+ email: input.email ?? null,
40
+ phone: input.phone ?? null,
41
+ userId: authenticated ? input.userId ?? null : null
42
+ }).onConflictDoNothing();
43
+ const [row] = await db.select().from(schema.inboxContacts).where(where).limit(1);
44
+ const changes = {};
45
+ if (input.name && input.name !== row.name && (authenticated || !row.name)) changes.name = input.name;
46
+ if (input.email && !row.email) changes.email = input.email;
47
+ if (input.phone && !row.phone) changes.phone = input.phone;
48
+ if (authenticated && input.userId && !row.userId) changes.userId = input.userId;
49
+ if (!Object.keys(changes).length) return row;
50
+ const [updated] = await db.update(schema.inboxContacts).set(changes).where(eq(schema.inboxContacts.id, row.id)).returning();
51
+ return updated;
52
+ }
53
+ async function threadFor(account, contact, inbound, authenticated, now) {
54
+ let joinLatest = authenticated;
55
+ if (authenticated && inbound.threadId) {
56
+ const [named] = await db.select().from(schema.inboxThreads).where(and(eq(schema.inboxThreads.id, inbound.threadId), eq(schema.inboxThreads.mailboxId, account.mailboxId))).limit(1);
57
+ if (named && (named.contactId === contact.id || await sameEmail(named.contactId, contact.email))) {
58
+ if (!named.anonymisedAt) return named;
59
+ joinLatest = false;
60
+ }
61
+ }
62
+ if (joinLatest) {
63
+ const [latest] = await db.select().from(schema.inboxThreads).where(and(eq(schema.inboxThreads.mailboxId, account.mailboxId), eq(schema.inboxThreads.contactId, contact.id), eq(schema.inboxThreads.channel, account.channel), inArray(schema.inboxThreads.status, ["open", "pending"]), isNull(schema.inboxThreads.anonymisedAt))).orderBy(desc(schema.inboxThreads.lastMessageAt)).limit(1);
64
+ if (latest) return latest;
65
+ }
66
+ const [created] = await db.insert(schema.inboxThreads).values({
67
+ id: newId("ibt"),
68
+ mailboxId: account.mailboxId,
69
+ contactId: contact.id,
70
+ channelAccountId: account.id,
71
+ channel: account.channel,
72
+ subject: inboxCleanSubject(inbound.subject),
73
+ searchText: inboxThreadSearchText({ subject: inboxCleanSubject(inbound.subject) }),
74
+ status: "open",
75
+ lastMessageAt: now
76
+ }).returning();
77
+ return created;
78
+ }
79
+ async function sameEmail(contactId, email) {
80
+ if (!email) return false;
81
+ const [row] = await db.select({ email: schema.inboxContacts.email }).from(schema.inboxContacts).where(eq(schema.inboxContacts.id, contactId)).limit(1);
82
+ return !!row?.email && row.email.toLowerCase() === email.toLowerCase();
83
+ }
84
+ export async function inboxReceive(event, channel, inbound, account) {
85
+ const target = account ?? await inboxFindAccount(channel, { accountId: inbound.accountId, address: inbound.address });
86
+ if (!target) return { status: "ignored", reason: "no_account" };
87
+ if (!target.enabled) return { status: "ignored", reason: "disabled" };
88
+ const externalId = `${channel}:${inbound.externalId}`;
89
+ const known = await existingMessageId(target.id, externalId);
90
+ if (known) return { status: "duplicate", messageId: known };
91
+ if (await inboxIsTombstoned(target.id, externalId)) return { status: "ignored", reason: "removed" };
92
+ const now = /* @__PURE__ */ new Date();
93
+ const authenticated = inbound.authenticated === true;
94
+ const contact = await upsertContact(channel, inbound.contact, authenticated);
95
+ const thread = await threadFor(target, contact, inbound, authenticated, now);
96
+ const [message] = await db.insert(schema.inboxMessages).values({
97
+ id: newId("ibm"),
98
+ threadId: thread.id,
99
+ direction: "in",
100
+ body: inbound.body,
101
+ attachments: inbound.attachments ?? [],
102
+ cc: inbound.cc?.length ? inbound.cc : null,
103
+ channelAccountId: target.id,
104
+ externalId,
105
+ // Who sent it: the thread may be another contact's (an email answer to a contact form thread).
106
+ contactId: contact.id,
107
+ authenticated,
108
+ createdAt: now,
109
+ createdAtMs: now.getTime()
110
+ }).onConflictDoNothing().returning();
111
+ if (!message) return { status: "duplicate", messageId: await existingMessageId(target.id, externalId) ?? "" };
112
+ const from = thread.status;
113
+ const to = "open";
114
+ const [updated] = await db.update(schema.inboxThreads).set({ lastMessageAt: now, status: to, preview: inboxPreview(inbound.body), ...!thread.subject && inbound.subject ? { subject: inboxCleanSubject(inbound.subject), searchText: inboxThreadSearchText({ subject: inboxCleanSubject(inbound.subject) }) } : {} }).where(eq(schema.inboxThreads.id, thread.id)).returning();
115
+ const threadDto = toInboxThreadDto(updated);
116
+ const messageDto = toInboxMessageDto(message);
117
+ const hooks = useNitroApp().hooks;
118
+ if (from !== to) await hooks.callHook("inbox:thread:status-changed", { event, thread: threadDto, from, to });
119
+ await hooks.callHook("inbox:message:received", { event, thread: threadDto, message: messageDto });
120
+ return { status: "received", thread: threadDto, message: messageDto };
121
+ }
122
+ export async function inboxReceiveAll(event, channel, messages) {
123
+ const counts = { received: 0, duplicates: 0, ignored: 0, failed: 0 };
124
+ for (const message of messages) {
125
+ try {
126
+ const result = await inboxReceive(event, channel, message);
127
+ if (result.status === "received") counts.received++;
128
+ else if (result.status === "duplicate") counts.duplicates++;
129
+ else counts.ignored++;
130
+ } catch (error) {
131
+ counts.failed++;
132
+ console.error(`[inbox] could not store a ${channel} message`, error);
133
+ }
134
+ }
135
+ return counts;
136
+ }
@@ -0,0 +1,7 @@
1
+ import type { H3Event } from 'h3';
2
+ /** Whether `userId` leads team `teamId` (`isTeamLead` of `@frigear-nu/teams`). */
3
+ export type InboxTeamLeadResolver = (event: H3Event, userId: string | number, teamId: string) => Promise<boolean>;
4
+ /** Set by the teams plugin. A host may set its own to decide who leads a team mailbox. */
5
+ export declare function setInboxTeamLeadResolver(resolver: InboxTeamLeadResolver | undefined): void;
6
+ /** Whether `userId` leads team `teamId`; always `false` without teams (or another resolver). */
7
+ export declare function inboxIsTeamLead(event: H3Event, userId: string | number, teamId: string): Promise<boolean>;
@@ -0,0 +1,13 @@
1
+ let teamLeadResolver;
2
+ export function setInboxTeamLeadResolver(resolver) {
3
+ teamLeadResolver = resolver;
4
+ }
5
+ export async function inboxIsTeamLead(event, userId, teamId) {
6
+ if (!teamLeadResolver) return false;
7
+ try {
8
+ return await teamLeadResolver(event, userId, teamId);
9
+ } catch (error) {
10
+ console.error("[inbox] the team lead check failed, the user is not treated as a lead", error);
11
+ return false;
12
+ }
13
+ }
@@ -0,0 +1,14 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { Grant } from '@frigear-nu/auth/grants';
3
+ /**
4
+ * The owner id of a new mailbox: none for the platform; for a team, a team `teams:owner:resolve` knows (Teams answers
5
+ * it), else 400.
6
+ */
7
+ export declare function inboxCheckMailboxOwner(event: H3Event, ownerType: 'platform' | 'team', ownerId: string | null): Promise<string | null>;
8
+ /**
9
+ * Who reads a mailbox besides staff: its grants (`@frigear-nu/auth`), checked by their kinds. A mailbox holds outsiders'
10
+ * messages, so a `public` grant and a `signed-in` grant (every user with an account) are refused, and a platform mailbox
11
+ * must name who reads it (an empty list would be staff only, which is never what a platform mailbox is for). A team
12
+ * mailbox may leave it empty: its leads read it.
13
+ */
14
+ export declare function inboxCheckMailboxGrants(event: H3Event, ownerType: string, value: readonly Grant[], stored?: unknown): Promise<Grant[]>;
@@ -0,0 +1,27 @@
1
+ import { PUBLIC_GRANT_KIND, SIGNED_IN_GRANT_KIND } from "@frigear-nu/auth/grants";
2
+ import { validationError } from "@frigear-nu/module-kit/server";
3
+ export async function inboxCheckMailboxOwner(event, ownerType, ownerId) {
4
+ if (ownerType === "platform") {
5
+ if (ownerId) throw validationError([{ path: ["ownerId"], message: "A platform mailbox has no owner id." }], "Unknown owner");
6
+ return null;
7
+ }
8
+ if (!ownerId) throw validationError([{ path: ["ownerId"], message: "Choose the team." }], "Unknown owner");
9
+ const ctx = { event, owner: { type: "team", id: ownerId }, label: null, exists: null };
10
+ await useNitroApp().hooks.callHook("teams:owner:resolve", ctx);
11
+ if (ctx.exists !== true) {
12
+ throw validationError([{ path: ["ownerId"], message: ctx.exists === false ? "This team does not exist." : "No installed module knows teams." }], "Unknown owner");
13
+ }
14
+ return ownerId;
15
+ }
16
+ export async function inboxCheckMailboxGrants(event, ownerType, value, stored) {
17
+ if (value.some((grant) => grant.kind === PUBLIC_GRANT_KIND)) {
18
+ throw validationError([{ path: ["grants"], message: "A mailbox cannot be public." }], "Invalid grants");
19
+ }
20
+ if (value.some((grant) => grant.kind === SIGNED_IN_GRANT_KIND)) {
21
+ throw validationError([{ path: ["grants"], message: "A mailbox cannot be open to every signed-in user: name the roles or teams that read it." }], "Invalid grants");
22
+ }
23
+ if (ownerType === "platform" && !value.length) {
24
+ throw validationError([{ path: ["grants"], message: "Name the roles or teams that read this mailbox." }], "Invalid grants");
25
+ }
26
+ return grantsValidate(event, value, { stored });
27
+ }
@@ -0,0 +1,7 @@
1
+ import type { InboxChannelAdapter, InboxChannelInfo } from '../../../types.js';
2
+ /** A registered channel, or `undefined`. */
3
+ export declare function inboxChannel(id: string): InboxChannelInfo | undefined;
4
+ /** Every registered channel. */
5
+ export declare function inboxChannels(): InboxChannelInfo[];
6
+ /** The adapter of a registered channel, or `undefined`. */
7
+ export declare function inboxChannelAdapter(id: string): InboxChannelAdapter | undefined;
@@ -0,0 +1,10 @@
1
+ import { adapters, channels } from "#inbox/server-registry";
2
+ export function inboxChannel(id) {
3
+ return Object.hasOwn(channels, id) ? channels[id] : void 0;
4
+ }
5
+ export function inboxChannels() {
6
+ return Object.values(channels);
7
+ }
8
+ export function inboxChannelAdapter(id) {
9
+ return Object.hasOwn(adapters, id) ? adapters[id] : void 0;
10
+ }
@@ -0,0 +1,57 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { InboxRetentionMode, InboxRetentionResult } from '../../../types.js';
3
+ import type { InboxContactRow, InboxThreadRow } from './inbox-dto.js';
4
+ import type { InboxTombstoneOptions } from './inbox-tombstones.js';
5
+ /**
6
+ * Blanks the messages of threads (D1-sized chunks) and closes them: bodies, attachments, cc recipients and provider ids
7
+ * (`erased:<message id>`) go, the subject and preview too. The threads stay, as a record that something was answered.
8
+ * The provider ids are tombstoned first, so a replayed webhook does not bring a message back (for good with
9
+ * `permanent`, as an erase does).
10
+ */
11
+ export declare function inboxAnonymiseThreads(threadIds: string[], now?: Date, options?: InboxTombstoneOptions): Promise<void>;
12
+ /**
13
+ * One retention run: the closed threads whose last message is older than their mailbox keeps them (its
14
+ * `retentionDays`, else `inbox.retention.days`) are deleted with their messages (`mode: 'delete'`; contacts left
15
+ * without a thread or message go too) or blanked (`mode: 'anonymise'`; contacts left with only anonymised threads are
16
+ * erased). At most `batch` threads per run, so a big backlog is worked off over several runs within D1's limits. The
17
+ * budget is shared fairly: each mailbox with a retention period gets an equal share first, and what the others left
18
+ * goes to the mailboxes with more to do, so one busy mailbox never starves the rest. `more` says whether a mailbox had
19
+ * more than it got. One audit entry per mailbox records what went. The provider ids of what went are tombstoned, so a
20
+ * replayed webhook is not stored again, and retention's tombstones older than `retention.tombstoneDays` are pruned
21
+ * (an erase's are kept). `mode` and `batch` override the configured ones (manual runs and tests).
22
+ */
23
+ export declare function inboxRunRetention(options?: {
24
+ now?: Date;
25
+ event?: H3Event;
26
+ mode?: InboxRetentionMode;
27
+ batch?: number;
28
+ }): Promise<InboxRetentionResult>;
29
+ /**
30
+ * What an export or an erase of a contact covers. A person can be several contacts (one per channel: the contact form,
31
+ * email, ...), so it is the contact and every other contact (not erased) with the same email address (`contactIds`);
32
+ * their own threads (`threads`); and the threads of other contacts they sent a message in (`foreign`, e.g. a reply by
33
+ * email filed under a form contact of another address), with those messages (`foreignMessageIds`).
34
+ */
35
+ export type InboxContactScope = {
36
+ contactIds: string[];
37
+ threads: InboxThreadRow[];
38
+ foreign: InboxThreadRow[];
39
+ foreignMessageIds: string[];
40
+ };
41
+ /** The contact and every other contact (not erased) that has its email address. */
42
+ export declare function inboxRelatedContactIds(contact: InboxContactRow): Promise<string[]>;
43
+ /** The scope of an export or erase of `contact` (see `InboxContactScope`), in D1-sized chunks. */
44
+ export declare function inboxContactScope(contact: InboxContactRow): Promise<InboxContactScope>;
45
+ /**
46
+ * Erases a contact (GDPR), with every other contact that has their email address (`inboxContactScope`): their names,
47
+ * emails, phones and channel ids are removed, every thread of theirs is closed with its messages blanked (bodies,
48
+ * attachments, provider ids), and the messages they sent in other contacts' threads are blanked too. The threads stay
49
+ * as a record that something was answered. The tombstones of everything they sent, also what retention removed
50
+ * earlier, are kept for good, so no replay brings it back. A later message from the same person starts a new contact.
51
+ * Form submissions and their files are kept by Forms and erased there. Pass `scope` when the caller already has it.
52
+ */
53
+ export declare function inboxEraseContact(contactId: string, now?: Date, scope?: InboxContactScope): Promise<{
54
+ threads: number;
55
+ messages: number;
56
+ contacts: number;
57
+ }>;
@@ -0,0 +1,167 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { and, asc, desc, eq, inArray, isNotNull, isNull, lt, ne, sql } from "drizzle-orm";
3
+ import { chunkParams } from "@frigear-nu/module-kit/server";
4
+ import { inboxThreadSearchText } from "./inbox-search.js";
5
+ const DAY_MS = 24 * 60 * 60 * 1e3;
6
+ export async function inboxAnonymiseThreads(threadIds, now = /* @__PURE__ */ new Date(), options = {}) {
7
+ await inboxTombstoneThreads(threadIds, now, options);
8
+ for (const chunk of chunkParams(threadIds)) {
9
+ await db.update(schema.inboxMessages).set({ body: "", attachments: [], cc: null, externalId: sql`'erased:' || ${schema.inboxMessages.id}` }).where(inArray(schema.inboxMessages.threadId, chunk));
10
+ await db.update(schema.inboxThreads).set({ subject: null, searchText: inboxThreadSearchText({ subject: null, anonymisedAt: now }), preview: null, status: "closed", anonymisedAt: now }).where(inArray(schema.inboxThreads.id, chunk));
11
+ }
12
+ }
13
+ async function eraseContactRows(contactIds, now) {
14
+ for (const id of contactIds) {
15
+ await db.update(schema.inboxContacts).set({ name: null, email: null, phone: null, userId: null, externalId: `erased:${id}`, erasedAt: now }).where(eq(schema.inboxContacts.id, id));
16
+ }
17
+ }
18
+ async function senderContactIds(threadIds) {
19
+ const ids = /* @__PURE__ */ new Set();
20
+ for (const chunk of chunkParams(threadIds)) {
21
+ const rows = await db.selectDistinct({ contactId: schema.inboxMessages.contactId }).from(schema.inboxMessages).where(and(inArray(schema.inboxMessages.threadId, chunk), isNotNull(schema.inboxMessages.contactId)));
22
+ for (const row of rows) if (row.contactId) ids.add(row.contactId);
23
+ }
24
+ return [...ids];
25
+ }
26
+ async function deleteThreads(threadIds, now) {
27
+ await inboxTombstoneThreads(threadIds, now);
28
+ for (const chunk of chunkParams(threadIds)) {
29
+ await db.delete(schema.inboxMessages).where(inArray(schema.inboxMessages.threadId, chunk));
30
+ await db.delete(schema.inboxThreads).where(inArray(schema.inboxThreads.id, chunk));
31
+ }
32
+ }
33
+ async function deleteOrphanContacts(contactIds) {
34
+ let deleted = 0;
35
+ for (const chunk of chunkParams([...new Set(contactIds)])) {
36
+ const used = new Set((await db.select({ contactId: schema.inboxThreads.contactId }).from(schema.inboxThreads).where(inArray(schema.inboxThreads.contactId, chunk))).map((row) => row.contactId));
37
+ for (const row of await db.selectDistinct({ contactId: schema.inboxMessages.contactId }).from(schema.inboxMessages).where(inArray(schema.inboxMessages.contactId, chunk))) {
38
+ if (row.contactId) used.add(row.contactId);
39
+ }
40
+ const orphans = chunk.filter((id) => !used.has(id));
41
+ if (!orphans.length) continue;
42
+ await db.delete(schema.inboxContacts).where(inArray(schema.inboxContacts.id, orphans));
43
+ deleted += orphans.length;
44
+ }
45
+ return deleted;
46
+ }
47
+ async function eraseFullyAnonymisedContacts(contactIds, now) {
48
+ const erase = [];
49
+ for (const chunk of chunkParams([...new Set(contactIds)])) {
50
+ const live = new Set((await db.select({ contactId: schema.inboxThreads.contactId }).from(schema.inboxThreads).where(and(inArray(schema.inboxThreads.contactId, chunk), isNull(schema.inboxThreads.anonymisedAt)))).map((row) => row.contactId));
51
+ const sent = await db.selectDistinct({ contactId: schema.inboxMessages.contactId }).from(schema.inboxMessages).innerJoin(schema.inboxThreads, eq(schema.inboxThreads.id, schema.inboxMessages.threadId)).where(and(inArray(schema.inboxMessages.contactId, chunk), isNull(schema.inboxThreads.anonymisedAt)));
52
+ for (const row of sent) if (row.contactId) live.add(row.contactId);
53
+ const candidates = chunk.filter((id) => !live.has(id));
54
+ if (!candidates.length) continue;
55
+ const open = await db.select({ id: schema.inboxContacts.id }).from(schema.inboxContacts).where(and(inArray(schema.inboxContacts.id, candidates), isNull(schema.inboxContacts.erasedAt)));
56
+ erase.push(...open.map((row) => row.id));
57
+ }
58
+ await eraseContactRows(erase, now);
59
+ return erase.length;
60
+ }
61
+ async function retainMailbox(mailbox, cutoff, mode, limit, now, result) {
62
+ const conditions = [eq(schema.inboxThreads.mailboxId, mailbox.id), eq(schema.inboxThreads.status, "closed"), lt(schema.inboxThreads.lastMessageAt, cutoff)];
63
+ if (mode === "anonymise") conditions.push(isNull(schema.inboxThreads.anonymisedAt));
64
+ const rows = await db.select({ id: schema.inboxThreads.id, contactId: schema.inboxThreads.contactId }).from(schema.inboxThreads).where(and(...conditions)).orderBy(asc(schema.inboxThreads.lastMessageAt)).limit(limit);
65
+ if (!rows.length) return 0;
66
+ const ids = rows.map((row) => row.id);
67
+ const contactIds = [...rows.map((row) => row.contactId), ...await senderContactIds(ids)];
68
+ if (mode === "anonymise") {
69
+ await inboxAnonymiseThreads(ids, now);
70
+ result.contacts += await eraseFullyAnonymisedContacts(contactIds, now);
71
+ } else {
72
+ await deleteThreads(ids, now);
73
+ result.contacts += await deleteOrphanContacts(contactIds);
74
+ }
75
+ return rows.length;
76
+ }
77
+ export async function inboxRunRetention(options = {}) {
78
+ const config = inboxConfig(options.event).retention;
79
+ const now = options.now ?? /* @__PURE__ */ new Date();
80
+ const mode = options.mode ?? config.mode;
81
+ const result = { mailboxes: 0, threads: 0, contacts: 0, mode, more: false };
82
+ const batch = Math.max(1, Math.floor(options.batch ?? config.batch));
83
+ const mailboxes = (await db.select().from(schema.inboxMailboxes).orderBy(asc(schema.inboxMailboxes.key))).map((mailbox) => ({ mailbox, days: mailbox.retentionDays ?? config.days })).filter((entry) => !!entry.days);
84
+ if (mailboxes.length) {
85
+ const share = Math.max(1, Math.floor(batch / mailboxes.length));
86
+ let budget = batch;
87
+ const done = /* @__PURE__ */ new Map();
88
+ const full = [];
89
+ for (const entry of mailboxes) {
90
+ if (budget <= 0) {
91
+ result.more = true;
92
+ break;
93
+ }
94
+ const limit = Math.min(share, budget);
95
+ const count = await retainMailbox(entry.mailbox, new Date(now.getTime() - entry.days * DAY_MS), mode, limit, now, result);
96
+ budget -= count;
97
+ if (count) done.set(entry.mailbox.id, count);
98
+ if (count === limit) full.push(entry);
99
+ }
100
+ for (const entry of full) {
101
+ if (budget <= 0) {
102
+ result.more = true;
103
+ break;
104
+ }
105
+ const count = await retainMailbox(entry.mailbox, new Date(now.getTime() - entry.days * DAY_MS), mode, budget, now, result);
106
+ if (count === budget) result.more = true;
107
+ budget -= count;
108
+ if (count) done.set(entry.mailbox.id, (done.get(entry.mailbox.id) ?? 0) + count);
109
+ }
110
+ for (const { mailbox, days } of mailboxes) {
111
+ const threads = done.get(mailbox.id);
112
+ if (!threads) continue;
113
+ result.threads += threads;
114
+ result.mailboxes++;
115
+ const before = new Date(now.getTime() - days * DAY_MS);
116
+ await inboxAudit(void 0, { action: "retention", actorId: null, mailboxId: mailbox.id, data: { mailboxId: mailbox.id, mode, threads, before: before.toISOString() } });
117
+ }
118
+ }
119
+ await inboxPruneTombstones(new Date(now.getTime() - Math.max(1, config.tombstoneDays) * DAY_MS));
120
+ return result;
121
+ }
122
+ export async function inboxRelatedContactIds(contact) {
123
+ const email = contact.email?.trim().toLowerCase() || (contact.channel === "email" && !contact.erasedAt ? contact.externalId.toLowerCase() : null);
124
+ if (!email) return [contact.id];
125
+ const rows = await db.select({ id: schema.inboxContacts.id }).from(schema.inboxContacts).where(and(eq(sql`lower(${schema.inboxContacts.email})`, email), isNull(schema.inboxContacts.erasedAt), ne(schema.inboxContacts.id, contact.id))).orderBy(asc(schema.inboxContacts.createdAt));
126
+ return [contact.id, ...rows.map((row) => row.id)];
127
+ }
128
+ export async function inboxContactScope(contact) {
129
+ const contactIds = await inboxRelatedContactIds(contact);
130
+ const threads = [];
131
+ const sent = [];
132
+ for (const chunk of chunkParams(contactIds)) {
133
+ threads.push(...await db.select().from(schema.inboxThreads).where(inArray(schema.inboxThreads.contactId, chunk)));
134
+ sent.push(...await db.select({ id: schema.inboxMessages.id, threadId: schema.inboxMessages.threadId }).from(schema.inboxMessages).where(inArray(schema.inboxMessages.contactId, chunk)));
135
+ }
136
+ threads.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
137
+ const own = new Set(threads.map((thread) => thread.id));
138
+ const foreignMessages = sent.filter((message) => !own.has(message.threadId));
139
+ const foreign = [];
140
+ for (const chunk of chunkParams([...new Set(foreignMessages.map((message) => message.threadId))])) {
141
+ foreign.push(...await db.select().from(schema.inboxThreads).where(inArray(schema.inboxThreads.id, chunk)));
142
+ }
143
+ foreign.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
144
+ return { contactIds, threads, foreign, foreignMessageIds: foreignMessages.map((message) => message.id) };
145
+ }
146
+ async function blankForeignMessages(messageIds, threadIds, now) {
147
+ await inboxTombstoneMessages(messageIds, now, { permanent: true });
148
+ for (const chunk of chunkParams(messageIds)) {
149
+ await db.update(schema.inboxMessages).set({ body: "", attachments: [], cc: null, externalId: sql`'erased:' || ${schema.inboxMessages.id}` }).where(inArray(schema.inboxMessages.id, chunk));
150
+ }
151
+ for (const threadId of threadIds) {
152
+ const [latest] = await db.select({ body: schema.inboxMessages.body }).from(schema.inboxMessages).where(and(eq(schema.inboxMessages.threadId, threadId), ne(schema.inboxMessages.direction, "note"))).orderBy(desc(schema.inboxMessages.createdAtMs)).limit(1);
153
+ await db.update(schema.inboxThreads).set({ preview: latest ? inboxPreview(latest.body) : null }).where(eq(schema.inboxThreads.id, threadId));
154
+ }
155
+ }
156
+ export async function inboxEraseContact(contactId, now = /* @__PURE__ */ new Date(), scope) {
157
+ if (!scope) {
158
+ const contact = await findInboxContact(contactId);
159
+ if (!contact) return { threads: 0, messages: 0, contacts: 0 };
160
+ scope = await inboxContactScope(contact);
161
+ }
162
+ await inboxKeepTombstonesOf(scope.contactIds);
163
+ await inboxAnonymiseThreads(scope.threads.map((thread) => thread.id), now, { permanent: true });
164
+ await blankForeignMessages(scope.foreignMessageIds, scope.foreign.map((thread) => thread.id), now);
165
+ await eraseContactRows(scope.contactIds, now);
166
+ return { threads: scope.threads.length, messages: scope.foreignMessageIds.length, contacts: scope.contactIds.length };
167
+ }