@remit/mailbox-service 0.0.112 → 0.0.114

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 (270) hide show
  1. package/dist/account-credentials.d.ts +83 -0
  2. package/dist/account-credentials.js +104 -0
  3. package/dist/attribute-mapper.d.ts +36 -0
  4. package/dist/attribute-mapper.js +119 -0
  5. package/dist/body-parse.d.ts +28 -0
  6. package/{src/body-parse.ts → dist/body-parse.js} +18 -26
  7. package/dist/body-part-mapper.d.ts +92 -0
  8. package/dist/body-part-mapper.js +301 -0
  9. package/dist/body-sync-queue.d.ts +59 -0
  10. package/dist/body-sync-queue.js +56 -0
  11. package/dist/body-sync-terminal.d.ts +58 -0
  12. package/dist/body-sync-terminal.js +95 -0
  13. package/dist/body-sync.d.ts +351 -0
  14. package/dist/body-sync.js +1204 -0
  15. package/dist/calendar-parts.d.ts +23 -0
  16. package/dist/calendar-parts.js +18 -0
  17. package/dist/classification-backfill.d.ts +91 -0
  18. package/dist/classification-backfill.js +180 -0
  19. package/dist/classify-message.d.ts +31 -0
  20. package/dist/classify-message.js +89 -0
  21. package/dist/connection-factory.d.ts +54 -0
  22. package/dist/connection-factory.js +54 -0
  23. package/dist/connection-test.d.ts +41 -0
  24. package/dist/connection-test.js +152 -0
  25. package/dist/external-move.d.ts +94 -0
  26. package/dist/external-move.js +173 -0
  27. package/dist/filter-operations.d.ts +42 -0
  28. package/dist/filter-operations.js +211 -0
  29. package/dist/filters/filter-config.d.ts +14 -0
  30. package/dist/filters/filter-config.js +10 -0
  31. package/{src/filters/list-id.ts → dist/filters/list-id.d.ts} +2 -16
  32. package/dist/filters/list-id.js +26 -0
  33. package/dist/filters/match.d.ts +69 -0
  34. package/dist/filters/match.js +165 -0
  35. package/dist/filters/pipeline.d.ts +64 -0
  36. package/dist/filters/pipeline.js +100 -0
  37. package/{src/flag-push-terminal.ts → dist/flag-push-terminal.d.ts} +16 -72
  38. package/dist/flag-push-terminal.js +63 -0
  39. package/dist/flag-push.d.ts +69 -0
  40. package/dist/flag-push.js +111 -0
  41. package/dist/flag-queue.d.ts +175 -0
  42. package/dist/flag-queue.js +291 -0
  43. package/dist/folder-operations.d.ts +39 -0
  44. package/dist/folder-operations.js +112 -0
  45. package/dist/folder-placement.d.ts +13 -0
  46. package/dist/folder-placement.js +23 -0
  47. package/dist/heuristics/authenticationResults.d.ts +10 -0
  48. package/dist/heuristics/authenticationResults.js +187 -0
  49. package/dist/heuristics/classifyByHeaders.d.ts +82 -0
  50. package/dist/heuristics/classifyByHeaders.js +365 -0
  51. package/dist/heuristics/classifyPlacement.d.ts +67 -0
  52. package/dist/heuristics/classifyPlacement.js +153 -0
  53. package/dist/heuristics/machineSenders.d.ts +21 -0
  54. package/{src/heuristics/machineSenders.ts → dist/heuristics/machineSenders.js} +34 -40
  55. package/dist/heuristics/senderMismatch.d.ts +81 -0
  56. package/dist/heuristics/senderMismatch.js +192 -0
  57. package/dist/heuristics/socialDomains.d.ts +14 -0
  58. package/{src/heuristics/socialDomains.ts → dist/heuristics/socialDomains.js} +9 -9
  59. package/dist/heuristics/transactionalDomains.d.ts +18 -0
  60. package/{src/heuristics/transactionalDomains.ts → dist/heuristics/transactionalDomains.js} +8 -8
  61. package/dist/imapflow-connection.d.ts +377 -0
  62. package/dist/imapflow-connection.js +1147 -0
  63. package/dist/index.d.ts +63 -0
  64. package/dist/index.js +65 -0
  65. package/dist/list-id-backfill.d.ts +83 -0
  66. package/dist/list-id-backfill.js +132 -0
  67. package/dist/mailbox-cursor-rebuild.d.ts +74 -0
  68. package/dist/mailbox-cursor-rebuild.js +71 -0
  69. package/{src/mailbox-cursor.ts → dist/mailbox-cursor.d.ts} +20 -98
  70. package/dist/mailbox-cursor.js +102 -0
  71. package/dist/mailbox-intent.d.ts +41 -0
  72. package/{src/mailbox-intent.ts → dist/mailbox-intent.js} +38 -64
  73. package/dist/mailbox-management.d.ts +240 -0
  74. package/dist/mailbox-management.js +576 -0
  75. package/dist/mailbox-presence.d.ts +52 -0
  76. package/{src/mailbox-presence.ts → dist/mailbox-presence.js} +19 -30
  77. package/dist/mailbox-queue.d.ts +129 -0
  78. package/dist/mailbox-queue.js +216 -0
  79. package/dist/mailbox-sync.d.ts +93 -0
  80. package/dist/mailbox-sync.js +490 -0
  81. package/dist/mailbox-upstream.d.ts +38 -0
  82. package/{src/mailbox-upstream.ts → dist/mailbox-upstream.js} +37 -47
  83. package/dist/message-category.d.ts +51 -0
  84. package/{src/message-category.ts → dist/message-category.js} +28 -71
  85. package/dist/message-move.d.ts +285 -0
  86. package/dist/message-move.js +858 -0
  87. package/dist/message-parser.d.ts +14 -0
  88. package/dist/message-parser.js +17 -0
  89. package/{src/message-presence.ts → dist/message-presence.d.ts} +1 -13
  90. package/dist/message-presence.js +29 -0
  91. package/dist/message-read.d.ts +51 -0
  92. package/dist/message-read.js +31 -0
  93. package/dist/message-sync.d.ts +345 -0
  94. package/dist/message-sync.js +1358 -0
  95. package/dist/mime-walker.d.ts +102 -0
  96. package/dist/mime-walker.js +198 -0
  97. package/dist/organize-job.d.ts +20 -0
  98. package/dist/organize-job.js +37 -0
  99. package/dist/outbox-attachment-content.d.ts +37 -0
  100. package/dist/outbox-attachment-content.js +50 -0
  101. package/dist/outbox-attachment-filename.d.ts +19 -0
  102. package/dist/outbox-attachment-filename.js +64 -0
  103. package/dist/outbox-attachment.d.ts +148 -0
  104. package/dist/outbox-attachment.js +273 -0
  105. package/dist/outbox-queue.d.ts +73 -0
  106. package/dist/outbox-queue.js +280 -0
  107. package/{src/outbox-status.ts → dist/outbox-status.d.ts} +1 -6
  108. package/dist/outbox-status.js +18 -0
  109. package/dist/ownership.d.ts +24 -0
  110. package/dist/ownership.js +83 -0
  111. package/dist/placement-move-terminal.d.ts +67 -0
  112. package/dist/placement-move-terminal.js +88 -0
  113. package/dist/placement-move.d.ts +83 -0
  114. package/dist/placement-move.js +216 -0
  115. package/{src/placement-settled.ts → dist/placement-settled.d.ts} +13 -68
  116. package/dist/placement-settled.js +75 -0
  117. package/dist/quarantine.d.ts +95 -0
  118. package/dist/quarantine.js +131 -0
  119. package/dist/refusal.d.ts +31 -0
  120. package/dist/refusal.js +3 -0
  121. package/{src/restore-source-placement.ts → dist/restore-source-placement.d.ts} +29 -97
  122. package/dist/restore-source-placement.js +79 -0
  123. package/dist/search-text-backfill.d.ts +15 -0
  124. package/dist/search-text-backfill.js +33 -0
  125. package/dist/snippet.d.ts +61 -0
  126. package/dist/snippet.js +129 -0
  127. package/dist/spam-report.d.ts +86 -0
  128. package/dist/spam-report.js +241 -0
  129. package/dist/sync-warning.d.ts +21 -0
  130. package/dist/sync-warning.js +26 -0
  131. package/dist/sync-watermarks.d.ts +138 -0
  132. package/dist/sync-watermarks.js +205 -0
  133. package/dist/test-helpers/fake-imap.d.ts +151 -0
  134. package/dist/test-helpers/fake-imap.js +508 -0
  135. package/dist/test-helpers/folder-roles.d.ts +34 -0
  136. package/dist/test-helpers/folder-roles.js +47 -0
  137. package/dist/test-helpers/mime-tree-generator.d.ts +82 -0
  138. package/dist/test-helpers/mime-tree-generator.js +329 -0
  139. package/dist/test-helpers/test-store.d.ts +69 -0
  140. package/dist/test-helpers/test-store.js +193 -0
  141. package/dist/text/normalizer.d.ts +20 -0
  142. package/dist/text/normalizer.js +102 -0
  143. package/dist/thread-message-rows.d.ts +69 -0
  144. package/dist/thread-message-rows.js +40 -0
  145. package/dist/thread-root.d.ts +7 -0
  146. package/dist/thread-root.js +25 -0
  147. package/dist/types.d.ts +343 -0
  148. package/dist/types.js +19 -0
  149. package/package.json +86 -88
  150. package/src/account-credentials.ts +0 -210
  151. package/src/attribute-mapper.test.ts +0 -104
  152. package/src/attribute-mapper.ts +0 -148
  153. package/src/body-parse.test.ts +0 -55
  154. package/src/body-part-mapper.property.test.ts +0 -354
  155. package/src/body-part-mapper.ts +0 -410
  156. package/src/body-sync-queue.test.ts +0 -64
  157. package/src/body-sync-queue.ts +0 -131
  158. package/src/body-sync-terminal.test.ts +0 -148
  159. package/src/body-sync-terminal.ts +0 -174
  160. package/src/body-sync.test.ts +0 -925
  161. package/src/body-sync.ts +0 -1891
  162. package/src/calendar-parts.ts +0 -41
  163. package/src/classification-backfill.test.ts +0 -285
  164. package/src/classification-backfill.ts +0 -363
  165. package/src/classify-message.test.ts +0 -142
  166. package/src/classify-message.ts +0 -116
  167. package/src/connection-factory.ts +0 -102
  168. package/src/connection-test.ts +0 -208
  169. package/src/credentials.test.ts +0 -181
  170. package/src/external-move.test.ts +0 -262
  171. package/src/external-move.ts +0 -285
  172. package/src/filter-operations.test.ts +0 -319
  173. package/src/filter-operations.ts +0 -377
  174. package/src/filter-update.test.ts +0 -313
  175. package/src/filters/filter-config.test.ts +0 -87
  176. package/src/filters/filter-config.ts +0 -34
  177. package/src/filters/list-id.test.ts +0 -50
  178. package/src/filters/match.test.ts +0 -392
  179. package/src/filters/match.ts +0 -225
  180. package/src/filters/pipeline.test.ts +0 -199
  181. package/src/filters/pipeline.ts +0 -170
  182. package/src/flag-push.test.ts +0 -112
  183. package/src/flag-push.ts +0 -198
  184. package/src/flag-queue.test.ts +0 -197
  185. package/src/flag-queue.ts +0 -509
  186. package/src/folder-operations.test.ts +0 -273
  187. package/src/folder-operations.ts +0 -217
  188. package/src/folder-placement.ts +0 -56
  189. package/src/forwarded-message.test.ts +0 -122
  190. package/src/heuristics/authenticationResults.test.ts +0 -189
  191. package/src/heuristics/authenticationResults.ts +0 -212
  192. package/src/heuristics/classifyByHeaders.test.ts +0 -889
  193. package/src/heuristics/classifyByHeaders.ts +0 -467
  194. package/src/heuristics/classifyPlacement.test.ts +0 -366
  195. package/src/heuristics/classifyPlacement.ts +0 -211
  196. package/src/heuristics/classifyRealMail.test.ts +0 -242
  197. package/src/heuristics/machineSenders.test.ts +0 -101
  198. package/src/heuristics/senderMismatch.test.ts +0 -346
  199. package/src/heuristics/senderMismatch.ts +0 -259
  200. package/src/imapflow-connect-retry.test.ts +0 -97
  201. package/src/imapflow-connection.test.ts +0 -503
  202. package/src/imapflow-connection.ts +0 -1476
  203. package/src/index.ts +0 -397
  204. package/src/list-id-backfill.test.ts +0 -207
  205. package/src/list-id-backfill.ts +0 -274
  206. package/src/mailbox-cursor-rebuild.test.ts +0 -171
  207. package/src/mailbox-cursor-rebuild.ts +0 -146
  208. package/src/mailbox-cursor.test.ts +0 -141
  209. package/src/mailbox-delete-intent.test.ts +0 -119
  210. package/src/mailbox-management.test.ts +0 -243
  211. package/src/mailbox-management.ts +0 -838
  212. package/src/mailbox-presence.test.ts +0 -74
  213. package/src/mailbox-queue.ts +0 -397
  214. package/src/mailbox-rename-intent.test.ts +0 -220
  215. package/src/mailbox-rename-subtree.test.ts +0 -287
  216. package/src/mailbox-sync.test.ts +0 -286
  217. package/src/mailbox-sync.ts +0 -724
  218. package/src/message-move.test.ts +0 -726
  219. package/src/message-move.ts +0 -1518
  220. package/src/message-parser.ts +0 -26
  221. package/src/message-presence.test.ts +0 -50
  222. package/src/message-read.ts +0 -87
  223. package/src/message-save-retry.test.ts +0 -90
  224. package/src/message-sync-flags.test.ts +0 -167
  225. package/src/message-sync.test.ts +0 -762
  226. package/src/message-sync.ts +0 -2133
  227. package/src/mime-walker.test.ts +0 -311
  228. package/src/mime-walker.ts +0 -306
  229. package/src/organize-job.ts +0 -93
  230. package/src/outbox-attachment-content.test.ts +0 -153
  231. package/src/outbox-attachment-content.ts +0 -104
  232. package/src/outbox-attachment-filename.test.ts +0 -132
  233. package/src/outbox-attachment-filename.ts +0 -76
  234. package/src/outbox-attachment.test.ts +0 -626
  235. package/src/outbox-attachment.ts +0 -536
  236. package/src/outbox-failed-recovery.test.ts +0 -299
  237. package/src/outbox-queue.test.ts +0 -315
  238. package/src/outbox-queue.ts +0 -525
  239. package/src/ownership.ts +0 -140
  240. package/src/placement-move-terminal.ts +0 -145
  241. package/src/placement-move.ts +0 -363
  242. package/src/placement-settled.test.ts +0 -147
  243. package/src/placement.test.ts +0 -404
  244. package/src/quarantine.test.ts +0 -133
  245. package/src/quarantine.ts +0 -229
  246. package/src/refusal.ts +0 -29
  247. package/src/snippet.test.ts +0 -213
  248. package/src/snippet.ts +0 -152
  249. package/src/spam-report.test.ts +0 -329
  250. package/src/spam-report.ts +0 -357
  251. package/src/sync-warning.test.ts +0 -213
  252. package/src/sync-warning.ts +0 -56
  253. package/src/sync-watermarks.test.ts +0 -409
  254. package/src/sync-watermarks.ts +0 -319
  255. package/src/system-flag-wire-format.test.ts +0 -77
  256. package/src/test-helpers/fake-imap.ts +0 -690
  257. package/src/test-helpers/folder-roles.ts +0 -66
  258. package/src/test-helpers/mime-tree-generator.ts +0 -461
  259. package/src/test-helpers/test-queue.ts +0 -56
  260. package/src/test-helpers/test-store.ts +0 -299
  261. package/src/text/normalizer.test.ts +0 -223
  262. package/src/text/normalizer.ts +0 -140
  263. package/src/thread-message-rows.ts +0 -77
  264. package/src/thread-root.test.ts +0 -29
  265. package/src/thread-root.ts +0 -51
  266. package/src/types/mailparser-augment.d.ts +0 -23
  267. package/src/types/natural-porter-stemmer.d.ts +0 -50
  268. package/src/types/stopword.d.ts +0 -69
  269. package/src/types.ts +0 -371
  270. package/tsconfig.json +0 -8
@@ -1,299 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import type {
6
- AccountItem,
7
- CreateMessageInput,
8
- CreateThreadMessageInput,
9
- MailboxItem,
10
- MailboxSpecialUseValue,
11
- MessageItem,
12
- ThreadMessageItem,
13
- } from "@remit/data-ports";
14
- import { AccountAuthType, ConnectionState } from "@remit/domain-enums";
15
- import {
16
- createSqliteRepositories,
17
- openSqliteDatabases,
18
- } from "@remit/drizzle-service";
19
- import { applyShippedMigrations } from "@remit/drizzle-service/test-sqlite";
20
- import type { StorageService } from "@remit/storage-service";
21
- import { createFilesystemStorageService } from "@remit/storage-service/filesystem";
22
- import Database from "better-sqlite3";
23
- import { MessageSyncService } from "../message-sync.js";
24
- import { SyncWarningService } from "../sync-warning.js";
25
- import type { FakeImapServer } from "./fake-imap.js";
26
-
27
- export {
28
- captureQueue,
29
- type QueueCapture,
30
- type QueuedEvent,
31
- } from "./test-queue.js";
32
-
33
- const UPLOAD_URLS = {
34
- origin: "https://reader.test",
35
- signingSecret: "test-signing-secret",
36
- };
37
-
38
- /**
39
- * The store the app opens: the committed migrations applied to a file, then
40
- * that file opened the way the app opens it — as the app, mail and search
41
- * database at once — with every repo the app composes.
42
- * Storage made from it lives in the same directory and goes with it.
43
- */
44
- let migrated: string | undefined;
45
-
46
- const migratedTemplate = (): string => {
47
- if (migrated) return migrated;
48
- const dir = mkdtempSync(join(tmpdir(), "mbx-template-"));
49
- const filename = join(dir, "template.sqlite");
50
- const migrating = new Database(filename);
51
- migrating.pragma("synchronous = OFF");
52
- applyShippedMigrations(migrating);
53
- migrating.close();
54
- process.once("exit", () => rmSync(dir, { recursive: true, force: true }));
55
- migrated = filename;
56
- return filename;
57
- };
58
-
59
- export const openStore = async () => {
60
- const dir = mkdtempSync(join(tmpdir(), "mbx-store-"));
61
- const filename = join(dir, "store.sqlite");
62
- copyFileSync(migratedTemplate(), filename);
63
- const { close, ...databases } = await openSqliteDatabases({
64
- app: filename,
65
- mail: filename,
66
- search: filename,
67
- });
68
- let storages = 0;
69
- return {
70
- ...createSqliteRepositories(databases),
71
- storage: (): StorageService =>
72
- createFilesystemStorageService(
73
- join(dir, `storage-${++storages}`),
74
- UPLOAD_URLS,
75
- ),
76
- brokenStorage: (): StorageService => {
77
- const root = join(dir, `broken-${++storages}`);
78
- writeFileSync(root, "");
79
- return createFilesystemStorageService(root);
80
- },
81
- close: async () => {
82
- await close();
83
- rmSync(dir, { recursive: true, force: true });
84
- },
85
- };
86
- };
87
-
88
- export type Store = Awaited<ReturnType<typeof openStore>>;
89
-
90
- export const seedAccount = async (
91
- store: Store,
92
- overrides: Partial<AccountItem> = {},
93
- ): Promise<AccountItem> => {
94
- const config = await store.accountConfig.create({
95
- accountConfigId: overrides.accountConfigId,
96
- userId: "user-1",
97
- name: "Me",
98
- });
99
- return store.account.create({
100
- username: "me@example.com",
101
- email: "me@example.com",
102
- authType: AccountAuthType.Password,
103
- passwordHash: '{"ciphertext":"x"}',
104
- imapHost: "imap.example.com",
105
- imapPort: 993,
106
- imapTls: true,
107
- imapStartTls: false,
108
- isActive: true,
109
- connectionState: ConnectionState.Authenticated,
110
- ...overrides,
111
- accountConfigId: config.accountConfigId,
112
- });
113
- };
114
-
115
- export const seedMailbox = async (
116
- store: Store,
117
- account: Pick<AccountItem, "accountId">,
118
- fullPath: string,
119
- options: {
120
- specialUse?: MailboxSpecialUseValue;
121
- overrides?: Partial<MailboxItem>;
122
- } = {},
123
- ): Promise<MailboxItem> => {
124
- const created = await store.mailbox.create({
125
- accountId: account.accountId,
126
- namespacePrefix: "",
127
- hierarchyDelimiter: "/",
128
- fullPath,
129
- uidValidity: 7,
130
- uidNext: 1,
131
- highestModseq: "0",
132
- messageCount: 0,
133
- unseenCount: 0,
134
- deletedCount: 0,
135
- totalSize: 0,
136
- lastSyncUid: 0,
137
- highWaterMarkUid: 0,
138
- lastMessageSyncAt: 0,
139
- ...(options.specialUse ? { specialUse: [options.specialUse] } : {}),
140
- ...options.overrides,
141
- });
142
- if (created.outcome !== "Created") {
143
- throw new Error(`${fullPath} already exists`);
144
- }
145
- if (options.specialUse) {
146
- await store.mailboxSpecialUse.create(
147
- created.mailbox.mailboxId,
148
- options.specialUse,
149
- );
150
- }
151
- return created.mailbox;
152
- };
153
-
154
- export interface SeededMessage {
155
- message: MessageItem;
156
- threadMessage: ThreadMessageItem;
157
- }
158
-
159
- export const seedMessage = async (
160
- store: Store,
161
- account: Pick<AccountItem, "accountConfigId">,
162
- mailbox: Pick<MailboxItem, "mailboxId">,
163
- uid: number,
164
- overrides: {
165
- message?: Partial<CreateMessageInput>;
166
- threadMessage?: Partial<CreateThreadMessageInput>;
167
- } = {},
168
- ): Promise<SeededMessage> => {
169
- const messageId = overrides.message?.messageId ?? randomUUID();
170
- const message = await store.message.create({
171
- messageId,
172
- mailboxId: mailbox.mailboxId,
173
- uid,
174
- sequenceNumber: uid,
175
- rfc822Size: 100,
176
- internalDate: 1_700_000_000_000 + uid,
177
- envelopeId: randomUUID(),
178
- rootBodyPartId: randomUUID(),
179
- status: "active",
180
- syncStatus: "synced",
181
- ...overrides.message,
182
- });
183
- const threadMessage = await store.threadMessage.create({
184
- accountConfigId: account.accountConfigId,
185
- threadId: messageId,
186
- messageId,
187
- mailboxId: message.mailboxId,
188
- uid: message.uid,
189
- referenceOrder: 0,
190
- internalDate: message.internalDate,
191
- sentDate: message.internalDate,
192
- isRead: false,
193
- isDeleted: false,
194
- hasAttachment: false,
195
- hasStars: false,
196
- ...overrides.threadMessage,
197
- });
198
- return { message, threadMessage };
199
- };
200
-
201
- export const silentLog = {
202
- info: () => {},
203
- warn: () => {},
204
- error: () => {},
205
- debug: () => {},
206
- };
207
-
208
- export const syncFolder = async (
209
- store: Store,
210
- account: Pick<AccountItem, "accountId" | "accountConfigId">,
211
- mailbox: Pick<MailboxItem, "mailboxId">,
212
- imap: FakeImapServer,
213
- ): Promise<string[]> => {
214
- const connection = imap.connection();
215
- const service = new MessageSyncService(
216
- { getConnection: () => connection, close: async () => {} },
217
- store.mailbox,
218
- store.mailboxSpecialUse,
219
- store.message,
220
- store.envelope,
221
- store.address,
222
- store.threadMessage,
223
- new SyncWarningService(store.syncWarning),
224
- silentLog,
225
- store.flagPush,
226
- store.messageFlag,
227
- );
228
- const synced: string[] = [];
229
- for (;;) {
230
- const result = await service.syncMessages(
231
- mailbox.mailboxId,
232
- account.accountId,
233
- account.accountConfigId,
234
- );
235
- synced.push(...result.syncedMessageIds);
236
- if (!result.hasMore) return synced;
237
- }
238
- };
239
-
240
- export const messageAtUid = async (
241
- store: Store,
242
- mailbox: Pick<MailboxItem, "mailboxId">,
243
- uid: number,
244
- ): Promise<MessageItem> => {
245
- const found = (await store.message.listAllByMailbox(mailbox.mailboxId)).find(
246
- (message) => message.uid === uid,
247
- );
248
- if (!found) throw new Error(`no message at uid ${uid}`);
249
- return found;
250
- };
251
-
252
- export const arriveAt = async (
253
- store: Store,
254
- imap: FakeImapServer,
255
- account: Pick<AccountItem, "accountId" | "accountConfigId">,
256
- mailbox: Pick<MailboxItem, "mailboxId" | "fullPath">,
257
- raw: Buffer,
258
- ): Promise<string> => {
259
- const uid = imap.deliver(mailbox.fullPath, raw);
260
- await syncFolder(store, account, mailbox, imap);
261
- return (await messageAtUid(store, mailbox, uid)).messageId;
262
- };
263
-
264
- export const storeBody = async (
265
- store: Store,
266
- storage: StorageService,
267
- account: Pick<AccountItem, "accountId" | "accountConfigId">,
268
- messageId: string,
269
- raw: Buffer,
270
- ): Promise<void> => {
271
- const ref = await storage.storeMessageBody({
272
- accountConfigId: account.accountConfigId,
273
- accountId: account.accountId,
274
- messageId,
275
- content: raw,
276
- });
277
- await store.message.update(messageId, { bodyStorageKey: ref.uri });
278
- };
279
-
280
- /**
281
- * Another writer landing between a service's read and its write: `action` runs,
282
- * for real, the next time `method` is called on `target`, and the call then
283
- * proceeds as normal.
284
- */
285
- export const beforeNext = <T extends object, K extends keyof T>(
286
- target: T,
287
- method: K,
288
- action: () => Promise<unknown>,
289
- ): void => {
290
- const original = target[method] as unknown as (...args: unknown[]) => unknown;
291
- let pending = true;
292
- target[method] = (async (...args: unknown[]) => {
293
- if (pending) {
294
- pending = false;
295
- await action();
296
- }
297
- return original.apply(target, args);
298
- }) as T[K];
299
- };
@@ -1,223 +0,0 @@
1
- import assert from "node:assert";
2
- import { describe, it } from "node:test";
3
- import { createTextNormalizer } from "./normalizer.js";
4
-
5
- describe("TextNormalizer", () => {
6
- const normalizer = createTextNormalizer();
7
-
8
- describe("detectLanguage", () => {
9
- it("detects English text", () => {
10
- const text =
11
- "The quick brown fox jumps over the lazy dog. This is a sample English text.";
12
- assert.strictEqual(normalizer.detectLanguage(text), "en");
13
- });
14
-
15
- it("detects German text", () => {
16
- const text =
17
- "Der schnelle braune Fuchs springt über den faulen Hund. Dies ist ein deutscher Text.";
18
- assert.strictEqual(normalizer.detectLanguage(text), "de");
19
- });
20
-
21
- it("detects French text", () => {
22
- const text =
23
- "Le renard brun rapide saute par-dessus le chien paresseux. Ceci est un texte français.";
24
- assert.strictEqual(normalizer.detectLanguage(text), "fr");
25
- });
26
-
27
- it("detects Spanish text", () => {
28
- const text =
29
- "El rápido zorro marrón salta sobre el perro perezoso. Este es un texto en español.";
30
- assert.strictEqual(normalizer.detectLanguage(text), "es");
31
- });
32
-
33
- it("detects Italian text", () => {
34
- const text =
35
- "La volpe marrone veloce salta sopra il cane pigro. Questo è un testo italiano.";
36
- assert.strictEqual(normalizer.detectLanguage(text), "it");
37
- });
38
-
39
- it("detects Portuguese text", () => {
40
- const text =
41
- "A rápida raposa marrom salta sobre o cão preguiçoso. Este é um texto em português.";
42
- assert.strictEqual(normalizer.detectLanguage(text), "pt");
43
- });
44
-
45
- it("detects Dutch text", () => {
46
- const text =
47
- "De snelle bruine vos springt over de luie hond. Dit is een Nederlandse tekst.";
48
- assert.strictEqual(normalizer.detectLanguage(text), "nl");
49
- });
50
-
51
- it("defaults to English for short text", () => {
52
- const text = "Hello";
53
- assert.strictEqual(normalizer.detectLanguage(text), "en");
54
- });
55
-
56
- it("defaults to English for empty text", () => {
57
- assert.strictEqual(normalizer.detectLanguage(""), "en");
58
- });
59
- });
60
-
61
- describe("tokenize", () => {
62
- it("tokenizes text into words", () => {
63
- const text = "Hello, World! How are you?";
64
- assert.deepStrictEqual(normalizer.tokenize(text), [
65
- "hello",
66
- "world",
67
- "how",
68
- "are",
69
- "you",
70
- ]);
71
- });
72
-
73
- it("handles Unicode characters", () => {
74
- const text = "Réunion demain café";
75
- assert.deepStrictEqual(normalizer.tokenize(text), [
76
- "réunion",
77
- "demain",
78
- "café",
79
- ]);
80
- });
81
-
82
- it("handles German umlauts", () => {
83
- const text = "Besprechung über München";
84
- assert.deepStrictEqual(normalizer.tokenize(text), [
85
- "besprechung",
86
- "über",
87
- "münchen",
88
- ]);
89
- });
90
-
91
- it("normalizes whitespace", () => {
92
- const text = " multiple spaces\n\ttabs ";
93
- assert.deepStrictEqual(normalizer.tokenize(text), [
94
- "multiple",
95
- "spaces",
96
- "tabs",
97
- ]);
98
- });
99
- });
100
-
101
- describe("stem", () => {
102
- it("stems English words", () => {
103
- assert.strictEqual(normalizer.stem("running", "en"), "run");
104
- assert.strictEqual(normalizer.stem("jumps", "en"), "jump");
105
- assert.strictEqual(normalizer.stem("connected", "en"), "connect");
106
- });
107
-
108
- it("stems German words", () => {
109
- // German Porter stemmer has different rules than English
110
- // Just verify it returns a string and doesn't throw
111
- const result1 = normalizer.stem("verbindung", "de");
112
- const result2 = normalizer.stem("laufend", "de");
113
- assert.ok(typeof result1 === "string");
114
- assert.ok(typeof result2 === "string");
115
- // The stemmer should at least return something
116
- assert.ok(result1.length > 0);
117
- assert.ok(result2.length > 0);
118
- });
119
-
120
- it("stems French words", () => {
121
- assert.strictEqual(normalizer.stem("réunion", "fr"), "réunion");
122
- assert.strictEqual(normalizer.stem("connexion", "fr"), "connexion");
123
- });
124
-
125
- it("defaults to English stemmer for unknown language", () => {
126
- assert.strictEqual(normalizer.stem("running"), "run");
127
- });
128
- });
129
-
130
- describe("removeStopwords", () => {
131
- it("removes English stopwords", () => {
132
- const words = ["the", "quick", "brown", "fox", "is", "running"];
133
- const result = normalizer.removeStopwords(words, "en");
134
- assert.ok(!result.includes("the"));
135
- assert.ok(!result.includes("is"));
136
- assert.ok(result.includes("quick"));
137
- assert.ok(result.includes("brown"));
138
- assert.ok(result.includes("fox"));
139
- assert.ok(result.includes("running"));
140
- });
141
-
142
- it("removes German stopwords", () => {
143
- const words = ["der", "schnelle", "fuchs", "ist", "braun"];
144
- const result = normalizer.removeStopwords(words, "de");
145
- assert.ok(!result.includes("der"));
146
- assert.ok(!result.includes("ist"));
147
- assert.ok(result.includes("schnelle"));
148
- assert.ok(result.includes("fuchs"));
149
- });
150
-
151
- it("removes French stopwords", () => {
152
- const words = ["le", "renard", "est", "rapide"];
153
- const result = normalizer.removeStopwords(words, "fr");
154
- assert.ok(!result.includes("le"));
155
- assert.ok(!result.includes("est"));
156
- assert.ok(result.includes("renard"));
157
- assert.ok(result.includes("rapide"));
158
- });
159
-
160
- it("removes Dutch stopwords", () => {
161
- const words = ["de", "snelle", "vos", "is", "bruin"];
162
- const result = normalizer.removeStopwords(words, "nl");
163
- assert.ok(!result.includes("de"));
164
- assert.ok(!result.includes("is"));
165
- assert.ok(result.includes("snelle"));
166
- assert.ok(result.includes("vos"));
167
- });
168
- });
169
-
170
- describe("normalize", () => {
171
- it("normalizes English text with stemming and stopword removal", () => {
172
- const text = "The quick brown fox is running quickly";
173
- const result = normalizer.normalize(text, { language: "en" });
174
- // Should remove "the" and "is", stem "running" and "quickly"
175
- assert.ok(!result.includes("the "));
176
- assert.ok(!result.includes(" is "));
177
- assert.ok(result.includes("quick"));
178
- assert.ok(result.includes("run"));
179
- });
180
-
181
- it("normalizes German text", () => {
182
- const text = "Der schnelle braune Fuchs ist laufend";
183
- const result = normalizer.normalize(text, { language: "de" });
184
- assert.ok(!result.includes("der "));
185
- assert.ok(!result.includes(" ist "));
186
- });
187
-
188
- it("normalizes without stemming when disabled", () => {
189
- const text = "running quickly";
190
- const result = normalizer.normalize(text, {
191
- language: "en",
192
- stem: false,
193
- removeStopwords: false,
194
- });
195
- assert.strictEqual(result, "running quickly");
196
- });
197
-
198
- it("handles Unicode text", () => {
199
- const text = "Réunion à Paris demain";
200
- const result = normalizer.normalize(text, { language: "fr" });
201
- assert.ok(result.includes("réunion"));
202
- assert.ok(result.includes("pari"));
203
- assert.ok(result.includes("demain"));
204
- });
205
-
206
- it("deduplicates consecutive words", () => {
207
- const text = "hello hello world world world";
208
- const result = normalizer.normalize(text, {
209
- language: "en",
210
- stem: false,
211
- removeStopwords: false,
212
- });
213
- assert.strictEqual(result, "hello world");
214
- });
215
-
216
- it("defaults to English when language not specified", () => {
217
- const text = "The quick brown fox";
218
- const result = normalizer.normalize(text);
219
- // "the" should be removed as English stopword
220
- assert.ok(!result.includes("the "));
221
- });
222
- });
223
- });
@@ -1,140 +0,0 @@
1
- /**
2
- * Multilingual text normalizer for email processing.
3
- *
4
- * Uses franc for language detection, natural for stemming,
5
- * and stopword for stopword removal.
6
- */
7
-
8
- /// <reference path="../types/natural-porter-stemmer.d.ts" />
9
- import { franc } from "franc";
10
- // Import each Porter stemmer file directly instead of the `natural` package
11
- // root or its `stemmers` submodule barrel: the root barrel
12
- // (`natural/lib/natural/index.js`) loads WordNet and the Brill POS tagger,
13
- // which pull in `mongoose` and — via its Postgres storage plugin —
14
- // `pg`/`dotenv` (`dotenv.config()` at module scope on every cold start, see
15
- // #1244/#1247); the `stemmers` barrel is CJS and unconditionally requires
16
- // every stemmer it lists, including Japanese (which drags in its own
17
- // tokenizer) and Indonesian, neither used here. This module only needs the
18
- // seven Porter stemmers below — see
19
- // ../types/natural-porter-stemmer.d.ts for their (hand-written, since
20
- // `natural` ships none for individual files) type declarations.
21
- import PorterStemmer from "natural/lib/natural/stemmers/porter_stemmer.js";
22
- import PorterStemmerDe from "natural/lib/natural/stemmers/porter_stemmer_de.js";
23
- import PorterStemmerEs from "natural/lib/natural/stemmers/porter_stemmer_es.js";
24
- import PorterStemmerFr from "natural/lib/natural/stemmers/porter_stemmer_fr.js";
25
- import PorterStemmerIt from "natural/lib/natural/stemmers/porter_stemmer_it.js";
26
- import PorterStemmerNl from "natural/lib/natural/stemmers/porter_stemmer_nl.js";
27
- import PorterStemmerPt from "natural/lib/natural/stemmers/porter_stemmer_pt.js";
28
- import { deu, eng, fra, ita, nld, por, removeStopwords, spa } from "stopword";
29
-
30
- export type SupportedLanguage = "en" | "de" | "fr" | "es" | "it" | "nl" | "pt";
31
-
32
- export interface NormalizeOptions {
33
- language?: SupportedLanguage;
34
- stem?: boolean;
35
- removeStopwords?: boolean;
36
- }
37
-
38
- export interface TextNormalizer {
39
- detectLanguage(text: string): SupportedLanguage;
40
- normalize(text: string, options?: NormalizeOptions): string;
41
- tokenize(text: string): string[];
42
- stem(word: string, language?: SupportedLanguage): string;
43
- removeStopwords(words: string[], language?: SupportedLanguage): string[];
44
- }
45
-
46
- // ISO 639-3 (franc) → ISO 639-1 (our SupportedLanguage)
47
- const iso3ToIso1: Record<string, SupportedLanguage> = {
48
- eng: "en",
49
- deu: "de",
50
- fra: "fr",
51
- nld: "nl",
52
- spa: "es",
53
- ita: "it",
54
- por: "pt",
55
- };
56
-
57
- // Restrict franc to only detect languages we can stem
58
- const supportedIso3 = Object.keys(iso3ToIso1);
59
-
60
- const stemmers: Record<SupportedLanguage, { stem: (word: string) => string }> =
61
- {
62
- en: PorterStemmer,
63
- de: PorterStemmerDe,
64
- fr: PorterStemmerFr,
65
- es: PorterStemmerEs,
66
- it: PorterStemmerIt,
67
- nl: PorterStemmerNl,
68
- pt: PorterStemmerPt,
69
- };
70
-
71
- const stopwordLists: Record<SupportedLanguage, string[]> = {
72
- en: eng,
73
- de: deu,
74
- fr: fra,
75
- es: spa,
76
- it: ita,
77
- nl: nld,
78
- pt: por,
79
- };
80
-
81
- export const createTextNormalizer = (): TextNormalizer => ({
82
- detectLanguage: (text) => {
83
- // Use franc with trigram analysis, restricted to supported languages
84
- const detected = franc(text, { only: supportedIso3, minLength: 10 });
85
-
86
- // Map to our language codes, default to English
87
- return iso3ToIso1[detected] ?? "en";
88
- },
89
-
90
- normalize: (text, options = {}) => {
91
- const {
92
- language = "en",
93
- stem = true,
94
- removeStopwords: removeStop = true,
95
- } = options;
96
-
97
- // Normalize unicode and lowercase
98
- let normalized = text.normalize("NFKC").toLowerCase();
99
-
100
- // Keep Unicode letters and numbers, remove punctuation
101
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, " ");
102
-
103
- // Tokenize
104
- let words = normalized.split(/\s+/).filter((w) => w.length > 0);
105
-
106
- // Remove stopwords
107
- if (removeStop) {
108
- const list = stopwordLists[language] ?? eng;
109
- words = removeStopwords(words, list);
110
- }
111
-
112
- // Stem
113
- if (stem) {
114
- const stemmer = stemmers[language] ?? stemmers.en;
115
- words = words.map((w) => stemmer.stem(w));
116
- }
117
-
118
- // Dedupe consecutive words
119
- return words.filter((w, i, arr) => i === 0 || w !== arr[i - 1]).join(" ");
120
- },
121
-
122
- tokenize: (text) => {
123
- return text
124
- .normalize("NFKC")
125
- .toLowerCase()
126
- .replace(/[^\p{L}\p{N}\s]/gu, " ")
127
- .split(/\s+/)
128
- .filter((w) => w.length > 0);
129
- },
130
-
131
- stem: (word, language = "en") => {
132
- const stemmer = stemmers[language] ?? stemmers.en;
133
- return stemmer.stem(word.toLowerCase());
134
- },
135
-
136
- removeStopwords: (words, language = "en") => {
137
- const list = stopwordLists[language] ?? eng;
138
- return removeStopwords(words, list);
139
- },
140
- });