@meith/threads 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,27 @@
1
+ {
2
+ "name": "@meith/threads",
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/threads"
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/polls": "0.16.0",
23
+ "@meith/i18n": "0.16.0",
24
+ "@meith/core": "0.16.0",
25
+ "@meith/markdown": "0.16.0"
26
+ }
27
+ }
package/src/compose.ts ADDED
@@ -0,0 +1,220 @@
1
+ import { RateLimitedError, ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+ import { type NewPoll, type ValidatedPoll, validatePoll } from '@meith/polls'
4
+
5
+ export interface ForumPostingRules {
6
+ readonly id: number
7
+ readonly type: 'category' | 'forum' | 'link'
8
+ readonly isOpen: boolean
9
+ readonly allowThreads: boolean
10
+ readonly allowReplies: boolean
11
+ readonly allowPolls: boolean
12
+ readonly allowAttachments: boolean
13
+ readonly requiresPrefix: boolean
14
+ readonly moderateNewThreads: boolean
15
+ readonly moderateNewPosts: boolean
16
+ }
17
+
18
+ export interface ThreadAuthor {
19
+ readonly userId: number
20
+ readonly username: string
21
+ }
22
+
23
+ export interface AuthorRestriction {
24
+ readonly suspended: boolean
25
+ readonly moderated: boolean
26
+ }
27
+
28
+ export const UNRESTRICTED: AuthorRestriction = {
29
+ suspended: false,
30
+ moderated: false,
31
+ }
32
+
33
+ export interface ComposeThreadInput {
34
+ readonly title: string
35
+ readonly message: string
36
+ readonly prefixId: number | null
37
+ readonly subscribe: boolean
38
+ readonly poll?: NewPoll | undefined
39
+ readonly mayPostPoll?: boolean | undefined
40
+ readonly bypassesModeration: boolean
41
+ readonly heldAsNewMember: boolean
42
+ readonly requiresApproval: boolean
43
+ readonly bypassesFlood: boolean
44
+ readonly restriction?: AuthorRestriction | undefined
45
+ }
46
+
47
+ export interface NewThreadRecord {
48
+ readonly forumId: number
49
+ readonly title: string
50
+ readonly slug: string
51
+ readonly message: string
52
+ readonly prefixId: number | null
53
+ readonly authorUserId: number
54
+ readonly authorUsername: string
55
+ readonly visibility: 'visible' | 'unapproved'
56
+ readonly subscribe: boolean
57
+ readonly poll?: ValidatedPoll | undefined
58
+ readonly createdAt: Date
59
+ }
60
+
61
+ export interface CreatedThread {
62
+ readonly threadId: number
63
+ readonly postId: number
64
+ readonly slug: string
65
+ readonly visibility: 'visible' | 'unapproved'
66
+ }
67
+
68
+ export interface PrefixOption {
69
+ readonly id: number
70
+ readonly label: string
71
+ readonly token: string | null
72
+ }
73
+
74
+ export type ForumPostingTarget = ForumPostingRules & { readonly slug: string }
75
+
76
+ export interface ThreadWriteRepository {
77
+ postingRules(forumId: number): Promise<ForumPostingTarget | null>
78
+ create(record: NewThreadRecord): Promise<CreatedThread>
79
+
80
+ lastPostAt(userId: number): Promise<Date | null>
81
+
82
+ allowedPrefixIds(forumId: number): Promise<readonly number[]>
83
+
84
+ listPrefixes(forumId: number): Promise<readonly PrefixOption[]>
85
+ }
86
+
87
+ export interface ThreadComposerConfig {
88
+ readonly floodSeconds: number
89
+ readonly maxLength: number
90
+ }
91
+
92
+ export const TITLE_MIN = 3
93
+ export const TITLE_MAX = 120
94
+ export const MESSAGE_MIN = 2
95
+
96
+ export function threadSlug(title: string): string {
97
+ const slug = title
98
+ .toLowerCase()
99
+ .normalize('NFKD')
100
+ .replace(/[̀-ͯ]/g, '')
101
+ .replace(/[^a-z0-9]+/g, '-')
102
+ .replace(/^-+|-+$/g, '')
103
+ .slice(0, 60)
104
+ .replace(/-+$/g, '')
105
+
106
+ return slug.length > 0 ? slug : 'thread'
107
+ }
108
+
109
+ export class ThreadComposer {
110
+ private readonly threads: ThreadWriteRepository
111
+ private readonly config: ThreadComposerConfig
112
+ private readonly now: () => Date
113
+
114
+ constructor(deps: {
115
+ threads: ThreadWriteRepository
116
+ config: ThreadComposerConfig
117
+ now?: () => Date
118
+ }) {
119
+ this.threads = deps.threads
120
+ this.config = deps.config
121
+ this.now = deps.now ?? (() => new Date())
122
+ }
123
+
124
+ async create(
125
+ input: ComposeThreadInput,
126
+ author: ThreadAuthor,
127
+ forum: ForumPostingRules,
128
+ ): Promise<CreatedThread> {
129
+ const title = input.title.trim()
130
+ const message = input.message.trim()
131
+
132
+ if (forum.type === 'link') {
133
+ throw new ValidationError(msg('error.threads.threads-posted-here'))
134
+ }
135
+ if (!forum.isOpen || !forum.allowThreads) {
136
+ throw new ValidationError(msg('error.threads.forum-closed-new-threads'))
137
+ }
138
+
139
+ const restriction = input.restriction ?? UNRESTRICTED
140
+ if (restriction.suspended) {
141
+ throw new ValidationError(msg('error.threads.posting-privileges-currently-suspended'))
142
+ }
143
+
144
+ if (title.length < TITLE_MIN) {
145
+ throw new ValidationError(msg('error.threads.title-min', { min: TITLE_MIN }))
146
+ }
147
+ if (title.length > TITLE_MAX) {
148
+ throw new ValidationError(msg('error.threads.title-max', { max: TITLE_MAX }))
149
+ }
150
+ if (message.length < MESSAGE_MIN) {
151
+ throw new ValidationError(msg('error.threads.post-needs-message'))
152
+ }
153
+ if (message.length > this.config.maxLength) {
154
+ throw new ValidationError(msg('error.posts.post-length', { max: this.config.maxLength }))
155
+ }
156
+
157
+ const prefixId = await this.resolvePrefix(input.prefixId, forum)
158
+ const poll = input.poll === undefined ? undefined : validatePoll(input.poll, this.now())
159
+ if (poll !== undefined && (input.mayPostPoll !== true || !forum.allowPolls)) {
160
+ throw new ValidationError(msg('error.threads.attach-poll-forum'))
161
+ }
162
+
163
+ await this.enforceFlood(input, author)
164
+
165
+ const visibility =
166
+ ((forum.moderateNewThreads || input.requiresApproval) && !input.bypassesModeration) ||
167
+ input.heldAsNewMember ||
168
+ restriction.moderated
169
+ ? 'unapproved'
170
+ : 'visible'
171
+
172
+ return this.threads.create({
173
+ forumId: forum.id,
174
+ title,
175
+ slug: threadSlug(title),
176
+ message,
177
+ prefixId,
178
+ authorUserId: author.userId,
179
+ authorUsername: author.username,
180
+ visibility,
181
+ subscribe: input.subscribe,
182
+ poll,
183
+ createdAt: this.now(),
184
+ })
185
+ }
186
+
187
+ private async resolvePrefix(
188
+ prefixId: number | null,
189
+ forum: ForumPostingRules,
190
+ ): Promise<number | null> {
191
+ if (prefixId === null) {
192
+ if (forum.requiresPrefix) {
193
+ throw new ValidationError(msg('error.threads.forum-requires-prefix'))
194
+ }
195
+ return null
196
+ }
197
+
198
+ const allowed = await this.threads.allowedPrefixIds(forum.id)
199
+ if (!allowed.includes(prefixId)) {
200
+ throw new ValidationError(msg('error.threads.prefix-used-forum'))
201
+ }
202
+ return prefixId
203
+ }
204
+
205
+ private async enforceFlood(input: ComposeThreadInput, author: ThreadAuthor): Promise<void> {
206
+ if (this.config.floodSeconds <= 0 || input.bypassesFlood) return
207
+
208
+ const last = await this.threads.lastPostAt(author.userId)
209
+ if (last === null) return
210
+
211
+ const elapsed = (this.now().getTime() - last.getTime()) / 1000
212
+ if (elapsed >= this.config.floodSeconds) return
213
+
214
+ const wait = Math.max(1, Math.ceil(this.config.floodSeconds - elapsed))
215
+ throw new RateLimitedError(
216
+ wait,
217
+ `Please wait ${wait} more second${wait === 1 ? '' : 's'} before posting again.`,
218
+ )
219
+ }
220
+ }
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ export {
2
+ type AuthorRestriction,
3
+ type ComposeThreadInput,
4
+ type CreatedThread,
5
+ type ForumPostingRules,
6
+ type ForumPostingTarget,
7
+ MESSAGE_MIN,
8
+ type NewThreadRecord,
9
+ type PrefixOption,
10
+ type ThreadAuthor,
11
+ ThreadComposer,
12
+ type ThreadComposerConfig,
13
+ type ThreadWriteRepository,
14
+ TITLE_MAX,
15
+ TITLE_MIN,
16
+ threadSlug,
17
+ UNRESTRICTED,
18
+ } from './compose'
19
+ export type { ThreadLocation, ThreadRepository } from './ports'
20
+ export type { ReadState, ReadStateRepository } from './read-state'
21
+ export {
22
+ type ComposeReplyInput,
23
+ type CreatedReply,
24
+ type NewReplyRecord,
25
+ quotePrefill,
26
+ ReplyComposer,
27
+ type ReplyComposerConfig,
28
+ type ReplyTarget,
29
+ type ReplyWriteRepository,
30
+ } from './reply'
31
+ export type {
32
+ ThreadCursor,
33
+ ThreadLastPost,
34
+ ThreadListingRow,
35
+ ThreadPage,
36
+ ThreadSort,
37
+ } from './types'
package/src/ports.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { ContentScope, ThreadAuthorFilter } from '@meith/core'
2
+
3
+ import type { ThreadCursor, ThreadListingRow, ThreadPage, ThreadSort } from './types'
4
+
5
+ export interface ThreadLocation {
6
+ readonly forumId: number
7
+ readonly authorUserId: number | null
8
+ }
9
+
10
+ export interface ThreadRepository {
11
+ findById(
12
+ id: number,
13
+ scope: ContentScope,
14
+ authors: ThreadAuthorFilter,
15
+ ): Promise<ThreadListingRow | null>
16
+
17
+ locate(threadId: number): Promise<ThreadLocation | null>
18
+
19
+ listForum(
20
+ forumId: number,
21
+ options: {
22
+ readonly after?: ThreadCursor
23
+ readonly offset?: number
24
+ readonly limit: number
25
+ readonly scope: ContentScope
26
+ readonly authors: ThreadAuthorFilter
27
+ readonly sort?: ThreadSort
28
+ },
29
+ ): Promise<ThreadPage>
30
+ }
@@ -0,0 +1,11 @@
1
+ export interface ReadState {
2
+ readonly forumReadAt: ReadonlyMap<number, Date>
3
+ readonly threadLastPostId: ReadonlyMap<number, number>
4
+ readonly unreadForumIds: ReadonlySet<number>
5
+ }
6
+
7
+ export interface ReadStateRepository {
8
+ forUser(userId: number): Promise<ReadState>
9
+ markForumsRead(userId: number, forumIds: readonly number[], at: Date): Promise<void>
10
+ markThreadRead(userId: number, threadId: number, postId: number, at: Date): Promise<void>
11
+ }
package/src/reply.ts ADDED
@@ -0,0 +1,180 @@
1
+ import { RateLimitedError, ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+ import { quoteBlock } from '@meith/markdown'
4
+
5
+ import {
6
+ type AuthorRestriction,
7
+ type ForumPostingTarget,
8
+ MESSAGE_MIN,
9
+ type ThreadAuthor,
10
+ UNRESTRICTED,
11
+ } from './compose'
12
+
13
+ export interface ReplyTarget {
14
+ readonly threadId: number
15
+ readonly slug: string
16
+ readonly title: string
17
+ readonly authorUserId: number | null
18
+ readonly isLocked: boolean
19
+ readonly visibility: 'visible' | 'unapproved' | 'deleted'
20
+ readonly lastPostId: number | null
21
+ readonly replyCount: number
22
+ readonly forum: ForumPostingTarget
23
+ }
24
+
25
+ export interface ComposeReplyInput {
26
+ readonly message: string
27
+ readonly subscribe: boolean
28
+ readonly seenLastPostId: number | null
29
+ readonly bypassesModeration: boolean
30
+ readonly heldAsNewMember: boolean
31
+ readonly requiresApproval: boolean
32
+ readonly bypassesFlood: boolean
33
+ readonly bypassesLock: boolean
34
+ readonly restriction?: AuthorRestriction | undefined
35
+ }
36
+
37
+ export interface NewReplyRecord {
38
+ readonly threadId: number
39
+ readonly forumId: number
40
+ readonly threadTitle: string
41
+ readonly message: string
42
+ readonly authorUserId: number
43
+ readonly authorUsername: string
44
+ readonly visibility: 'visible' | 'unapproved'
45
+ readonly subscribe: boolean
46
+ readonly createdAt: Date
47
+ }
48
+
49
+ export interface CreatedReply {
50
+ readonly postId: number
51
+ readonly threadId: number
52
+ readonly slug: string
53
+ readonly visibility: 'visible' | 'unapproved'
54
+ readonly raced: boolean
55
+ readonly repliesBefore: number
56
+ }
57
+
58
+ export interface ReplyWriteRepository {
59
+ replyTarget(threadId: number): Promise<ReplyTarget | null>
60
+
61
+ createReply(record: NewReplyRecord): Promise<{ postId: number }>
62
+
63
+ lastPostAt(userId: number): Promise<Date | null>
64
+ }
65
+
66
+ export interface ReplyComposerConfig {
67
+ readonly floodSeconds: number
68
+ readonly maxLength: number
69
+ }
70
+
71
+ export class ReplyComposer {
72
+ private readonly posts: ReplyWriteRepository
73
+ private readonly config: ReplyComposerConfig
74
+ private readonly now: () => Date
75
+
76
+ constructor(deps: {
77
+ posts: ReplyWriteRepository
78
+ config: ReplyComposerConfig
79
+ now?: () => Date
80
+ }) {
81
+ this.posts = deps.posts
82
+ this.config = deps.config
83
+ this.now = deps.now ?? (() => new Date())
84
+ }
85
+
86
+ async create(
87
+ input: ComposeReplyInput,
88
+ author: ThreadAuthor,
89
+ target: ReplyTarget,
90
+ ): Promise<CreatedReply> {
91
+ const message = input.message.trim()
92
+
93
+ if (target.visibility !== 'visible') {
94
+ throw new ValidationError(msg('error.threads.thread-available'))
95
+ }
96
+ if (target.forum.type === 'link' || !target.forum.isOpen || !target.forum.allowReplies) {
97
+ throw new ValidationError(msg('error.threads.forum-closed-replies'))
98
+ }
99
+ if (target.isLocked && !input.bypassesLock) {
100
+ throw new ValidationError(msg('error.threads.thread-locked'))
101
+ }
102
+
103
+ const restriction = input.restriction ?? UNRESTRICTED
104
+ if (restriction.suspended) {
105
+ throw new ValidationError(msg('error.threads.posting-privileges-currently-suspended'))
106
+ }
107
+
108
+ if (message.length < MESSAGE_MIN) {
109
+ throw new ValidationError(msg('error.threads.post-needs-message'))
110
+ }
111
+ if (message.length > this.config.maxLength) {
112
+ throw new ValidationError(`A post may be at most ${this.config.maxLength} characters.`)
113
+ }
114
+
115
+ await this.enforceFlood(input, author)
116
+
117
+ const visibility =
118
+ ((target.forum.moderateNewPosts || input.requiresApproval) && !input.bypassesModeration) ||
119
+ input.heldAsNewMember ||
120
+ restriction.moderated
121
+ ? 'unapproved'
122
+ : 'visible'
123
+
124
+ const { postId } = await this.posts.createReply({
125
+ threadId: target.threadId,
126
+ forumId: target.forum.id,
127
+ threadTitle: target.title,
128
+ message,
129
+ authorUserId: author.userId,
130
+ authorUsername: author.username,
131
+ visibility,
132
+ subscribe: input.subscribe,
133
+ createdAt: this.now(),
134
+ })
135
+
136
+ const raced =
137
+ input.seenLastPostId !== null &&
138
+ target.lastPostId !== null &&
139
+ target.lastPostId !== input.seenLastPostId
140
+
141
+ return {
142
+ postId,
143
+ threadId: target.threadId,
144
+ slug: target.slug,
145
+ visibility,
146
+ raced,
147
+ repliesBefore: target.replyCount,
148
+ }
149
+ }
150
+
151
+ private async enforceFlood(input: ComposeReplyInput, author: ThreadAuthor): Promise<void> {
152
+ if (this.config.floodSeconds <= 0 || input.bypassesFlood) return
153
+
154
+ const last = await this.posts.lastPostAt(author.userId)
155
+ if (last === null) return
156
+
157
+ const elapsed = (this.now().getTime() - last.getTime()) / 1000
158
+ if (elapsed >= this.config.floodSeconds) return
159
+
160
+ const wait = Math.max(1, Math.ceil(this.config.floodSeconds - elapsed))
161
+ throw new RateLimitedError(
162
+ wait,
163
+ `Please wait ${wait} more second${wait === 1 ? '' : 's'} before posting again.`,
164
+ )
165
+ }
166
+ }
167
+
168
+ export function quotePrefill(quoted: {
169
+ readonly authorUsername: string
170
+ readonly message: string
171
+ readonly sourceHref?: string | null
172
+ readonly sourceLabel?: string
173
+ }): string {
174
+ return `${quoteBlock({
175
+ author: quoted.authorUsername,
176
+ markdown: quoted.message,
177
+ sourceHref: quoted.sourceHref ?? null,
178
+ ...(quoted.sourceLabel === undefined ? {} : { sourceLabel: quoted.sourceLabel }),
179
+ })}\n\n`
180
+ }
package/src/types.ts ADDED
@@ -0,0 +1,45 @@
1
+ export type ThreadSort = 'activity' | 'rating'
2
+
3
+ export interface ThreadLastPost {
4
+ readonly postId: number
5
+ readonly userId: number | null
6
+ readonly username: string
7
+ readonly at: Date
8
+ }
9
+
10
+ export interface ThreadListingRow {
11
+ readonly id: number
12
+ readonly forumId: number
13
+ readonly title: string
14
+ readonly slug: string
15
+ readonly prefix: {
16
+ readonly label: string
17
+ readonly token: string | null
18
+ } | null
19
+ readonly authorUserId: number | null
20
+ readonly authorUsername: string
21
+ readonly replyCount: number
22
+ readonly viewCount: number
23
+ readonly ratingTotal: number
24
+ readonly ratingCount: number
25
+ readonly visibility: 'visible' | 'unapproved' | 'deleted'
26
+ readonly isSticky: boolean
27
+ readonly isLocked: boolean
28
+ readonly isMoved: boolean
29
+ readonly lastPost: ThreadLastPost | null
30
+ readonly lastPostAt: Date
31
+ }
32
+
33
+ export interface ThreadCursor {
34
+ readonly sort: ThreadSort
35
+ readonly isSticky: boolean
36
+ readonly lastPostAt: Date
37
+ readonly ratingTotal: number
38
+ readonly ratingCount: number
39
+ readonly id: number
40
+ }
41
+
42
+ export interface ThreadPage {
43
+ readonly rows: readonly ThreadListingRow[]
44
+ readonly nextCursor: ThreadCursor | null
45
+ }