@meith/messages 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@meith/messages",
3
+ "version": "0.16.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/meith-dev/meith.git",
8
+ "directory": "packages/messages"
9
+ },
10
+ "type": "module",
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "files": [
14
+ "src",
15
+ "!src/**/*.test.*",
16
+ "!src/**/*.type-test.*"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "dependencies": {
22
+ "@meith/core": "0.16.0",
23
+ "@meith/markdown": "0.16.0",
24
+ "@meith/i18n": "0.16.0"
25
+ }
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ export {
2
+ type Draft,
3
+ MESSAGES_PAGE_SIZE,
4
+ type MessageAudit,
5
+ MessageService,
6
+ NO_MESSAGE_AUDIT,
7
+ type SendInput,
8
+ SUPPRESSED,
9
+ splitNames,
10
+ } from './service'
11
+ export {
12
+ BODY_MAX,
13
+ type FolderCounts,
14
+ MAX_RECIPIENTS,
15
+ MESSAGE_FOLDERS,
16
+ MESSAGE_ROLES,
17
+ type MessageCopy,
18
+ type MessageDetail,
19
+ type MessageFolder,
20
+ type MessageListRow,
21
+ type MessageNotifierPort,
22
+ type MessageParticipant,
23
+ type MessagePolicy,
24
+ type MessageRepository,
25
+ type MessageRole,
26
+ type PrivateMessage,
27
+ parseFolder,
28
+ type ResolvedRecipient,
29
+ SUBJECT_MAX,
30
+ } from './types'
package/src/service.ts ADDED
@@ -0,0 +1,425 @@
1
+ import { ForbiddenError, NotFoundError, ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+ import {
4
+ authorRef,
5
+ type BoardVocabulary,
6
+ CORE_RENDERING,
7
+ EMPTY_VOCABULARY,
8
+ type MarkdownPipeline,
9
+ quoteBlock,
10
+ renderThrough,
11
+ sourceAsMarkdown,
12
+ vocabularyOptions,
13
+ } from '@meith/markdown'
14
+
15
+ import {
16
+ BODY_MAX,
17
+ type FolderCounts,
18
+ MAX_RECIPIENTS,
19
+ type MessageDetail,
20
+ type MessageFolder,
21
+ type MessageListRow,
22
+ type MessageNotifierPort,
23
+ type MessagePolicy,
24
+ type MessageRepository,
25
+ type PrivateMessage,
26
+ type ResolvedRecipient,
27
+ SUBJECT_MAX,
28
+ } from './types'
29
+
30
+ export const MESSAGES_PAGE_SIZE = 25
31
+
32
+ export interface SendInput {
33
+ readonly authorUserId: number
34
+ readonly authorUsername: string
35
+ readonly to: string
36
+ readonly bcc?: string
37
+ readonly subject: string
38
+ readonly message: string
39
+ readonly receiptRequested?: boolean
40
+ readonly replyToId?: number | null
41
+ }
42
+
43
+ export interface Draft {
44
+ readonly to: string
45
+ readonly subject: string
46
+ readonly message: string
47
+ readonly replyToId: number | null
48
+ }
49
+
50
+ /**
51
+ * Where a plugin sees a private message. `before` may rewrite it or return null
52
+ * to drop it; `sent` is told what was stored.
53
+ */
54
+ export interface MessageAudit {
55
+ readonly before: (input: {
56
+ readonly senderId: number
57
+ readonly recipientIds: readonly number[]
58
+ readonly subject: string
59
+ readonly body: string
60
+ }) => Promise<{
61
+ readonly senderId: number
62
+ readonly recipientIds: readonly number[]
63
+ readonly subject: string
64
+ readonly body: string
65
+ } | null>
66
+ readonly sent: (input: {
67
+ readonly messageId: number
68
+ readonly recipientIds: readonly number[]
69
+ }) => Promise<void>
70
+ }
71
+
72
+ export const NO_MESSAGE_AUDIT: MessageAudit = {
73
+ before: async (input) => input,
74
+ sent: async () => {},
75
+ }
76
+
77
+ /**
78
+ * What `send` answers when a plugin suppressed the message. The sender is not
79
+ * told, which is the point: a spam filter that announces itself is a spam
80
+ * filter somebody tunes against.
81
+ */
82
+ export const SUPPRESSED = 0
83
+
84
+ export class MessageService {
85
+ private readonly repository: MessageRepository
86
+ private readonly policy: MessagePolicy
87
+ private readonly notifier: MessageNotifierPort | null
88
+ private readonly now: () => Date
89
+ private readonly vocabulary: () => Promise<BoardVocabulary>
90
+ private readonly rendering: MarkdownPipeline
91
+ private readonly audit: MessageAudit
92
+
93
+ constructor(deps: {
94
+ messages: MessageRepository
95
+ policy: MessagePolicy
96
+ notifier?: MessageNotifierPort | null
97
+ now?: () => Date
98
+ vocabulary?: () => Promise<BoardVocabulary>
99
+ rendering?: MarkdownPipeline
100
+ audit?: MessageAudit
101
+ }) {
102
+ this.repository = deps.messages
103
+ this.policy = deps.policy
104
+ this.notifier = deps.notifier ?? null
105
+ this.now = deps.now ?? (() => new Date())
106
+ this.vocabulary = deps.vocabulary ?? (async () => EMPTY_VOCABULARY)
107
+ this.rendering = deps.rendering ?? CORE_RENDERING
108
+ this.audit = deps.audit ?? NO_MESSAGE_AUDIT
109
+ }
110
+
111
+ async list(input: {
112
+ readonly userId: number
113
+ readonly folder: MessageFolder
114
+ readonly before?: number | undefined
115
+ readonly offset?: number | undefined
116
+ }): Promise<{ rows: readonly MessageListRow[]; nextBefore: number | null }> {
117
+ const rows = await this.repository.list({
118
+ userId: input.userId,
119
+ folder: input.folder,
120
+ limit: MESSAGES_PAGE_SIZE + 1,
121
+ before: input.before,
122
+ offset: input.offset,
123
+ })
124
+
125
+ const page = rows.slice(0, MESSAGES_PAGE_SIZE)
126
+ const last = page[page.length - 1]
127
+ return {
128
+ rows: page,
129
+ nextBefore: rows.length > MESSAGES_PAGE_SIZE && last !== undefined ? last.copyId : null,
130
+ }
131
+ }
132
+
133
+ counts(userId: number): Promise<FolderCounts> {
134
+ return this.repository.counts(userId)
135
+ }
136
+
137
+ async open(input: { messageId: number; userId: number }): Promise<MessageDetail> {
138
+ const detail = await this.repository.detail(input)
139
+ if (detail === null) throw new NotFoundError(msg('error.messages.such-message'))
140
+
141
+ const visible = this.visibleParticipants(detail, input.userId)
142
+
143
+ if (detail.copy.readAt === null && detail.copy.role !== 'author') {
144
+ const at = this.now()
145
+ await this.repository.setRead({ userId: input.userId, copyIds: [detail.copy.id], at })
146
+
147
+ if (detail.message.receiptRequested && detail.message.authorUserId !== null) {
148
+ await this.notify(() =>
149
+ this.notifier?.receiptRead({
150
+ userId: detail.message.authorUserId as number,
151
+ messageId: detail.message.id,
152
+ byUsername: visible.me,
153
+ subject: detail.message.subject,
154
+ }),
155
+ )
156
+ }
157
+
158
+ return { ...detail, copy: { ...detail.copy, readAt: at }, participants: visible.participants }
159
+ }
160
+
161
+ return { ...detail, participants: visible.participants }
162
+ }
163
+
164
+ private visibleParticipants(
165
+ detail: MessageDetail,
166
+ userId: number,
167
+ ): { participants: MessageDetail['participants']; me: string } {
168
+ const isAuthor = detail.message.authorUserId === userId
169
+ const me = detail.participants.find((p) => p.userId === userId)
170
+
171
+ return {
172
+ participants: detail.participants.filter(
173
+ (participant) => participant.role !== 'bcc' || isAuthor || participant.userId === userId,
174
+ ),
175
+ me: me?.username ?? '',
176
+ }
177
+ }
178
+
179
+ async send(input: SendInput): Promise<number> {
180
+ const subject = input.subject.trim()
181
+ const message = input.message.trim()
182
+
183
+ if (subject === '') throw new ValidationError(msg('error.messages.message-needs-subject'))
184
+ if (subject.length > SUBJECT_MAX) {
185
+ throw new ValidationError(msg('error.messages.subject-length', { max: SUBJECT_MAX }))
186
+ }
187
+ if (message === '') throw new ValidationError(msg('error.messages.message-needs-something'))
188
+ if (message.length > BODY_MAX) {
189
+ throw new ValidationError(msg('error.messages.body-length', { max: BODY_MAX }))
190
+ }
191
+
192
+ const resolved = await this.resolveRecipients(input)
193
+ await this.assertRoomFor(input.authorUserId, resolved)
194
+
195
+ const proposed = await this.audit.before({
196
+ senderId: input.authorUserId,
197
+ recipientIds: resolved.map((recipient) => recipient.userId as number),
198
+ subject,
199
+ body: message,
200
+ })
201
+ if (proposed === null) return SUPPRESSED
202
+
203
+ /*
204
+ * Only the recipients the board already resolved survive: a plugin may
205
+ * take one off the list, and cannot put one on it, because the addressees
206
+ * are the sender's choice and the board's check, not a plugin's.
207
+ */
208
+ const kept = new Set(proposed.recipientIds)
209
+ const recipients = resolved.filter((recipient) => kept.has(recipient.userId as number))
210
+ if (recipients.length === 0) return SUPPRESSED
211
+
212
+ const vocabulary = await this.vocabulary()
213
+ const rendered = await renderThrough(
214
+ this.rendering,
215
+ proposed.body,
216
+ { source: 'pm', viewer: authorRef(input.authorUserId) },
217
+ vocabularyOptions(vocabulary),
218
+ )
219
+ const at = this.now()
220
+
221
+ const messageId = await this.repository.send({
222
+ authorUserId: input.authorUserId,
223
+ authorUsername: input.authorUsername,
224
+ subject: proposed.subject,
225
+ message: proposed.body,
226
+ messageHtml: rendered.html,
227
+ renderVersion: rendered.version,
228
+ vocabVersion: vocabulary.revision,
229
+ replyToId: input.replyToId ?? null,
230
+ receiptRequested: input.receiptRequested === true,
231
+ recipients: recipients.map((r) => ({ userId: r.userId as number, bcc: r.bcc })),
232
+ at,
233
+ })
234
+
235
+ await this.audit.sent({
236
+ messageId,
237
+ recipientIds: recipients.map((recipient) => recipient.userId as number),
238
+ })
239
+
240
+ for (const recipient of recipients) {
241
+ await this.notify(() =>
242
+ this.notifier?.messageReceived({
243
+ userId: recipient.userId as number,
244
+ messageId,
245
+ fromUsername: input.authorUsername,
246
+ subject: proposed.subject,
247
+ }),
248
+ )
249
+ }
250
+
251
+ return messageId
252
+ }
253
+
254
+ private async resolveRecipients(input: SendInput): Promise<readonly ResolvedRecipient[]> {
255
+ const named = [
256
+ ...splitNames(input.to).map((name) => ({ name, bcc: false })),
257
+ ...splitNames(input.bcc ?? '').map((name) => ({ name, bcc: true })),
258
+ ]
259
+
260
+ if (named.length === 0)
261
+ throw new ValidationError(msg('error.messages.name-at-least-one-recipient'))
262
+
263
+ const seen = new Map<string, { name: string; bcc: boolean }>()
264
+ for (const entry of named) {
265
+ const key = entry.name.toLowerCase()
266
+ const existing = seen.get(key)
267
+ if (existing === undefined) seen.set(key, entry)
268
+ else if (!entry.bcc) seen.set(key, entry)
269
+ }
270
+
271
+ if (seen.size > MAX_RECIPIENTS) {
272
+ throw new ValidationError(
273
+ msg('error.messages.recipient-limit', { max: MAX_RECIPIENTS, count: seen.size }),
274
+ )
275
+ }
276
+
277
+ const resolved: ResolvedRecipient[] = []
278
+ for (const entry of seen.values()) {
279
+ const found = await this.policy.lookup(entry.name)
280
+ resolved.push({ name: entry.name, userId: found?.id ?? null, bcc: entry.bcc })
281
+ }
282
+
283
+ const unknown = resolved.filter((r) => r.userId === null).map((r) => r.name)
284
+ if (unknown.length > 0) {
285
+ throw new ValidationError(
286
+ msg('error.messages.unknown-recipients', {
287
+ count: unknown.length,
288
+ names: unknown.join(', '),
289
+ }),
290
+ )
291
+ }
292
+
293
+ if (resolved.some((r) => r.userId === input.authorUserId)) {
294
+ throw new ValidationError(msg('error.messages.send-message-yourself'))
295
+ }
296
+
297
+ return resolved
298
+ }
299
+
300
+ private async assertRoomFor(
301
+ authorUserId: number,
302
+ recipients: readonly ResolvedRecipient[],
303
+ ): Promise<void> {
304
+ const ids = [authorUserId, ...recipients.map((r) => r.userId as number)]
305
+ const [stored, limits] = await Promise.all([
306
+ this.repository.storedCounts(ids),
307
+ Promise.all(ids.map(async (id) => [id, await this.policy.limitsFor(id)] as const)),
308
+ ])
309
+
310
+ const limitById = new Map(limits)
311
+
312
+ const senderLimit = limitById.get(authorUserId)
313
+ if (senderLimit !== undefined && isFull(senderLimit.quota, stored.get(authorUserId) ?? 0)) {
314
+ throw new ForbiddenError(msg('error.messages.message-store-full-delete-some'))
315
+ }
316
+
317
+ const full: string[] = []
318
+ const closed: string[] = []
319
+ for (const recipient of recipients) {
320
+ const limit = limitById.get(recipient.userId as number)
321
+ if (limit === undefined) continue
322
+
323
+ const blocked =
324
+ this.policy.blocks === undefined
325
+ ? false
326
+ : await this.policy.blocks(recipient.userId as number, authorUserId)
327
+
328
+ if (!limit.canReceive || blocked) closed.push(recipient.name)
329
+ else if (isFull(limit.quota, stored.get(recipient.userId as number) ?? 0)) {
330
+ full.push(recipient.name)
331
+ }
332
+ }
333
+
334
+ if (closed.length > 0) {
335
+ throw new ForbiddenError(
336
+ msg('error.messages.recipients-closed', { names: closed.join(', ') }),
337
+ )
338
+ }
339
+ if (full.length > 0) {
340
+ throw new ForbiddenError(
341
+ msg('error.messages.recipients-full', { count: full.length, names: full.join(', ') }),
342
+ )
343
+ }
344
+ }
345
+
346
+ markRead(userId: number, copyIds: readonly number[]): Promise<number> {
347
+ return this.repository.setRead({ userId, copyIds, at: this.now() })
348
+ }
349
+
350
+ markUnread(userId: number, copyIds: readonly number[]): Promise<number> {
351
+ return this.repository.setRead({ userId, copyIds, at: null })
352
+ }
353
+
354
+ move(userId: number, copyIds: readonly number[], folder: MessageFolder): Promise<number> {
355
+ return this.repository.move({ userId, copyIds, folder })
356
+ }
357
+
358
+ remove(userId: number, copyIds: readonly number[]): Promise<number> {
359
+ return this.repository.remove({ userId, copyIds })
360
+ }
361
+
362
+ emptyTrash(userId: number): Promise<number> {
363
+ return this.repository.emptyFolder({ userId, folder: 'trash' })
364
+ }
365
+
366
+ async replyDraft(input: { messageId: number; userId: number }): Promise<Draft> {
367
+ const detail = await this.repository.detail(input)
368
+ if (detail === null) throw new NotFoundError(msg('error.messages.such-message'))
369
+
370
+ return {
371
+ to: detail.message.authorUsername,
372
+ subject: prefixed('Re: ', detail.message.subject),
373
+ message: quoted(detail.message),
374
+ replyToId: detail.message.id,
375
+ }
376
+ }
377
+
378
+ async forwardDraft(input: { messageId: number; userId: number }): Promise<Draft> {
379
+ const detail = await this.repository.detail(input)
380
+ if (detail === null) throw new NotFoundError(msg('error.messages.such-message'))
381
+
382
+ return {
383
+ to: '',
384
+ subject: prefixed('Fw: ', detail.message.subject),
385
+ message: quoted(detail.message),
386
+ replyToId: null,
387
+ }
388
+ }
389
+
390
+ forReport(messageId: number): Promise<PrivateMessage | null> {
391
+ return this.repository.forReport(messageId)
392
+ }
393
+
394
+ private async notify(run: () => Promise<void> | undefined): Promise<void> {
395
+ try {
396
+ await run()
397
+ } catch {
398
+ /* ignore */
399
+ }
400
+ }
401
+ }
402
+
403
+ function isFull(quota: number, stored: number): boolean {
404
+ return quota > 0 && stored >= quota
405
+ }
406
+
407
+ export function splitNames(raw: string): readonly string[] {
408
+ return raw
409
+ .split(/[,;\n]/)
410
+ .map((name) => name.trim())
411
+ .filter((name) => name !== '')
412
+ }
413
+
414
+ function prefixed(prefix: string, subject: string): string {
415
+ const already = subject.slice(0, prefix.length).toLowerCase() === prefix.toLowerCase()
416
+ const next = already ? subject : `${prefix}${subject}`
417
+ return next.slice(0, SUBJECT_MAX)
418
+ }
419
+
420
+ function quoted(message: PrivateMessage): string {
421
+ return `${quoteBlock({
422
+ author: message.authorUsername,
423
+ markdown: sourceAsMarkdown(message.message, message.bodyFormat),
424
+ })}\n\n`
425
+ }
package/src/types.ts ADDED
@@ -0,0 +1,150 @@
1
+ export const MESSAGE_FOLDERS = ['inbox', 'sent', 'trash'] as const
2
+ export type MessageFolder = (typeof MESSAGE_FOLDERS)[number]
3
+
4
+ export const MESSAGE_ROLES = ['author', 'to', 'bcc'] as const
5
+ export type MessageRole = (typeof MESSAGE_ROLES)[number]
6
+
7
+ export function parseFolder(value: string): MessageFolder | null {
8
+ return MESSAGE_FOLDERS.includes(value as MessageFolder) ? (value as MessageFolder) : null
9
+ }
10
+
11
+ export const SUBJECT_MAX = 200
12
+ export const BODY_MAX = 20_000
13
+ export const MAX_RECIPIENTS = 10
14
+
15
+ export interface PrivateMessage {
16
+ readonly id: number
17
+ readonly authorUserId: number | null
18
+ readonly authorUsername: string
19
+ readonly subject: string
20
+ readonly message: string
21
+ readonly messageHtml: string | null
22
+ readonly renderVersion: number
23
+ readonly bodyFormat: number
24
+ readonly vocabVersion: number
25
+ readonly replyToId: number | null
26
+ readonly receiptRequested: boolean
27
+ readonly sentAt: Date
28
+ }
29
+
30
+ export interface MessageCopy {
31
+ readonly id: number
32
+ readonly messageId: number
33
+ readonly ownerUserId: number
34
+ readonly folder: MessageFolder
35
+ readonly role: MessageRole
36
+ readonly readAt: Date | null
37
+ }
38
+
39
+ export interface MessageListRow {
40
+ readonly copyId: number
41
+ readonly messageId: number
42
+ readonly folder: MessageFolder
43
+ readonly role: MessageRole
44
+ readonly subject: string
45
+ readonly sentAt: Date
46
+ readonly readAt: Date | null
47
+ readonly counterparties: readonly string[]
48
+ readonly moreCounterparties: number
49
+ }
50
+
51
+ export interface MessageParticipant {
52
+ readonly userId: number
53
+ readonly username: string
54
+ readonly role: MessageRole
55
+ readonly readAt: Date | null
56
+ }
57
+
58
+ export interface MessageDetail {
59
+ readonly message: PrivateMessage
60
+ readonly copy: MessageCopy
61
+ readonly participants: readonly MessageParticipant[]
62
+ }
63
+
64
+ export interface FolderCounts {
65
+ readonly inbox: number
66
+ readonly sent: number
67
+ readonly trash: number
68
+ readonly unread: number
69
+ readonly stored: number
70
+ }
71
+
72
+ export interface ResolvedRecipient {
73
+ readonly name: string
74
+ readonly userId: number | null
75
+ readonly bcc: boolean
76
+ }
77
+
78
+ export interface MessagePolicy {
79
+ lookup(username: string): Promise<{ id: number; username: string } | null>
80
+ limitsFor(userId: number): Promise<{ quota: number; canReceive: boolean }>
81
+
82
+ blocks?(ownerUserId: number, senderUserId: number): Promise<boolean>
83
+ }
84
+
85
+ export interface MessageRepository {
86
+ list(input: {
87
+ readonly userId: number
88
+ readonly folder: MessageFolder
89
+ readonly limit: number
90
+ readonly before?: number | undefined
91
+ readonly offset?: number | undefined
92
+ }): Promise<readonly MessageListRow[]>
93
+
94
+ counts(userId: number): Promise<FolderCounts>
95
+
96
+ storedCounts(userIds: readonly number[]): Promise<ReadonlyMap<number, number>>
97
+
98
+ detail(input: {
99
+ readonly messageId: number
100
+ readonly userId: number
101
+ }): Promise<MessageDetail | null>
102
+
103
+ send(input: {
104
+ readonly authorUserId: number
105
+ readonly authorUsername: string
106
+ readonly subject: string
107
+ readonly message: string
108
+ readonly messageHtml: string
109
+ readonly renderVersion: number
110
+ readonly vocabVersion: number
111
+ readonly replyToId: number | null
112
+ readonly receiptRequested: boolean
113
+ readonly recipients: readonly { userId: number; bcc: boolean }[]
114
+ readonly at: Date
115
+ }): Promise<number>
116
+
117
+ setRead(input: {
118
+ readonly userId: number
119
+ readonly copyIds: readonly number[]
120
+ readonly at: Date | null
121
+ }): Promise<number>
122
+
123
+ move(input: {
124
+ readonly userId: number
125
+ readonly copyIds: readonly number[]
126
+ readonly folder: MessageFolder
127
+ }): Promise<number>
128
+
129
+ remove(input: { readonly userId: number; readonly copyIds: readonly number[] }): Promise<number>
130
+
131
+ emptyFolder(input: { readonly userId: number; readonly folder: MessageFolder }): Promise<number>
132
+
133
+ forReport(messageId: number): Promise<PrivateMessage | null>
134
+ }
135
+
136
+ export interface MessageNotifierPort {
137
+ messageReceived(input: {
138
+ readonly userId: number
139
+ readonly messageId: number
140
+ readonly fromUsername: string
141
+ readonly subject: string
142
+ }): Promise<void>
143
+
144
+ receiptRead(input: {
145
+ readonly userId: number
146
+ readonly messageId: number
147
+ readonly byUsername: string
148
+ readonly subject: string
149
+ }): Promise<void>
150
+ }