@molecule/api-resource-comment 1.4.1 → 1.6.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/README.md CHANGED
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-11-30T00:33:26.456Z
6
+ Generated: 2026-11-30T22:00:39.878Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-comment
@@ -45,7 +45,8 @@ import { routes, requestHandlerMap } from '@molecule/api-resource-comment'
45
45
  ## Installation
46
46
 
47
47
  ```bash
48
- npm install @molecule/api-resource-comment @molecule/api-database @molecule/api-i18n @molecule/api-logger zod
48
+ npm install @molecule/api-resource-comment @molecule/api-database @molecule/api-i18n @molecule/api-logger @molecule/api-rate-limit @molecule/api-resource express zod
49
+ npm install -D @types/express
49
50
  ```
50
51
 
51
52
  ## API
@@ -102,8 +103,10 @@ interface Comment {
102
103
  resourceType: string
103
104
  /** The ID of the resource this comment is attached to. */
104
105
  resourceId: string
105
- /** The ID of the user who created this comment. */
106
- userId: string
106
+ /** The ID of the user who created this comment, or `null` for guest comments. */
107
+ userId: string | null
108
+ /** Display name supplied for a guest comment, or `null` for authenticated comments. */
109
+ authorName?: string | null
107
110
  /** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
108
111
  author?: CommentAuthor | null
109
112
  /** The parent comment ID for threaded replies, or `null` for top-level comments. */
@@ -129,6 +132,8 @@ interface CreateCommentInput {
129
132
  body: string
130
133
  /** Optional parent comment ID for threaded replies. */
131
134
  parentId?: string
135
+ /** Display name when posting as an unauthenticated guest (ignored when signed in). */
136
+ authorName?: string
132
137
  }
133
138
  ```
134
139
 
@@ -153,6 +158,8 @@ interface PaginationOptions {
153
158
  limit?: number
154
159
  /** Number of results to skip. */
155
160
  offset?: number
161
+ /** Sort direction by creation time (`'asc'` or `'desc'`). */
162
+ order?: 'asc' | 'desc'
156
163
  }
157
164
  ```
158
165
 
@@ -418,7 +425,7 @@ result by `number` and read it back with `getCommentByNumber(number)`.
418
425
  function createNumberedComment(
419
426
  resourceType: string,
420
427
  resourceId: string,
421
- userId: string,
428
+ userId: string | null,
422
429
  data: CreateCommentInput,
423
430
  ): Promise<NumberedComment>
424
431
  ```
@@ -480,7 +487,7 @@ Both `__setup__` SQL files are required (`comments`, `comment_numbers`).
480
487
  function createComment(
481
488
  resourceType: string,
482
489
  resourceId: string,
483
- userId: string,
490
+ userId: string | null,
484
491
  data: CreateCommentInput,
485
492
  ): Promise<NumberedComment>
486
493
  ```
@@ -656,7 +663,11 @@ Schema for validating comment creation input.
656
663
 
657
664
  ```typescript
658
665
  const createCommentSchema: z.ZodObject<
659
- { body: z.ZodString; parentId: z.ZodOptional<z.ZodString> },
666
+ {
667
+ body: z.ZodString
668
+ parentId: z.ZodOptional<z.ZodString>
669
+ authorName: z.ZodOptional<z.ZodString>
670
+ },
660
671
  z.core.$strip
661
672
  >
662
673
  ```
@@ -678,7 +689,9 @@ Peer dependencies:
678
689
  - `@molecule/api-database` ^1.1.0
679
690
  - `@molecule/api-i18n` ^1.0.1
680
691
  - `@molecule/api-logger` ^1.0.1
681
- - `@molecule/api-resource` ^1.0.1 _(optional)_
692
+ - `@molecule/api-rate-limit` ^1.0.1
693
+ - `@molecule/api-resource` ^1.4.0
694
+ - `express` ^5.0.0
682
695
  - `zod` ^4.0.0
683
696
 
684
697
  ### Runtime Dependencies
@@ -686,7 +699,9 @@ Peer dependencies:
686
699
  - `@molecule/api-database`
687
700
  - `@molecule/api-i18n`
688
701
  - `@molecule/api-logger`
689
- - `@molecule/api-resource` _(optional)_
702
+ - `@molecule/api-rate-limit`
703
+ - `@molecule/api-resource`
704
+ - `express`
690
705
  - `zod`
691
706
 
692
707
  - **List endpoints return a PAGINATED envelope** `{ data, total, limit, offset }`, not a
package/dist/numbers.d.ts CHANGED
@@ -42,7 +42,7 @@ export declare function numberComment(commentId: string): Promise<number>;
42
42
  * @param data - The comment creation input.
43
43
  * @returns The created comment with its number.
44
44
  */
45
- export declare function createNumberedComment(resourceType: string, resourceId: string, userId: string, data: CreateCommentInput): Promise<NumberedComment>;
45
+ export declare function createNumberedComment(resourceType: string, resourceId: string, userId: string | null, data: CreateCommentInput): Promise<NumberedComment>;
46
46
  /**
47
47
  * The comment a number belongs to — the lookup behind an integer-addressed
48
48
  * route such as `DELETE /comments/:id`: find the comment here, then pass its
@@ -1 +1 @@
1
- {"version":3,"file":"numbers.d.ts","sourceRoot":"","sources":["../src/numbers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAK7D,qDAAqD;AACrD,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG;IACtC,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAQD;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,eAAe,CAAC,CAE1B;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAQxF;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAEhG"}
1
+ {"version":3,"file":"numbers.d.ts","sourceRoot":"","sources":["../src/numbers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAK7D,qDAAqD;AACrD,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG;IACtC,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAQD;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,eAAe,CAAC,CAE1B;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAQxF;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAEhG"}
@@ -0,0 +1,3 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
3
+ //# sourceMappingURL=scaffold-router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scaffold-router.d.ts","sourceRoot":"","sources":["../src/scaffold-router.ts"],"names":[],"mappings":"AAyCA,QAAA,MAAM,MAAM,4CAAW,CAAA;AA+NvB,eAAe,MAAM,CAAA"}
@@ -0,0 +1,194 @@
1
+ import { Router } from 'express';
2
+ import { consume as consumeRateLimit, hasProvider as hasRateLimitProvider, } from '@molecule/api-rate-limit';
3
+ import { getUserId, queryLimit, queryOffset, queryString, sendError, sendNotFound, sendServerError, sendUnauthorized, sendValidationError, } from '@molecule/api-resource';
4
+ import { canAccessCommentResource, CommentResourceAccessError, createComment, createCommentSchema, deleteComment, getCommentById, getCommentCount, getCommentsByResource, getReplies, updateComment, updateCommentSchema, } from '@molecule/api-resource-comment';
5
+ // Edit paths, allowlisted resource types, and JSON here. Comment services own
6
+ // persistence, sequential numbering, author hydration, and ownership checks.
7
+ // Fail-closed access: once any sibling resource registers a policy via
8
+ // registerResourceAccessPolicy() (e.g. articles.ts), unregistered resourceTypes
9
+ // and private/draft parents are refused with 404.
10
+ // Set ALLOW_GUEST_COMMENTS = true on public sites (e.g. blogs) so unauthenticated
11
+ // readers may post comments by supplying `authorName` (rate-limited; signed-in
12
+ // users always post under their account to prevent spoofing).
13
+ const ALLOW_GUEST_COMMENTS = false;
14
+ const RESOURCE_TYPE_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/i;
15
+ const router = Router();
16
+ /** Read an optional sort direction (`'asc'` or `'desc'`). */
17
+ function queryOrder(value) {
18
+ return value === 'asc' || value === 'desc' ? value : undefined;
19
+ }
20
+ /** Validate `resourceType` and `resourceId` path params. */
21
+ function resourceParams(req, res) {
22
+ const resourceType = queryString(req.params.resourceType);
23
+ const resourceId = queryString(req.params.resourceId);
24
+ if (!resourceType || !resourceId || !RESOURCE_TYPE_PATTERN.test(resourceType)) {
25
+ sendError(res, 400, 'comment.error.missingResource', 'Resource type and ID are required');
26
+ return null;
27
+ }
28
+ return { resourceType, resourceId };
29
+ }
30
+ /** Throttle comment creation when a rate-limit provider is bonded. */
31
+ async function rateLimitComments(req, res, next) {
32
+ if (!hasRateLimitProvider()) {
33
+ next();
34
+ return;
35
+ }
36
+ const key = `comments:create:${getUserId(res) ?? req.ip ?? 'unknown'}`;
37
+ const result = await consumeRateLimit(key);
38
+ if (!result.allowed) {
39
+ const retryAfter = result.retryAfter ?? Math.max(1, Math.ceil((result.resetAt.getTime() - Date.now()) / 1000));
40
+ res.set('Retry-After', String(retryAfter));
41
+ sendError(res, 429, 'rateLimit.error.tooManyRequests', 'Too many requests. Please try again later.');
42
+ return;
43
+ }
44
+ next();
45
+ }
46
+ router.post('/:resourceType/:resourceId/comments', rateLimitComments, async (req, res) => {
47
+ const userId = getUserId(res);
48
+ if (!userId && !ALLOW_GUEST_COMMENTS)
49
+ return sendUnauthorized(res);
50
+ const params = resourceParams(req, res);
51
+ if (!params)
52
+ return;
53
+ const parsed = createCommentSchema.safeParse(req.body);
54
+ if (!parsed.success) {
55
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues);
56
+ }
57
+ if (!userId && !parsed.data.authorName) {
58
+ return sendValidationError(res, 'comment.error.validationFailed', [
59
+ { path: ['authorName'], message: 'Name is required' },
60
+ ]);
61
+ }
62
+ try {
63
+ const comment = await createComment(params.resourceType, params.resourceId, userId, parsed.data);
64
+ res.status(201).json(comment);
65
+ }
66
+ catch (error) {
67
+ if (error instanceof CommentResourceAccessError)
68
+ return sendNotFound(res);
69
+ sendServerError(res, 'comment.error.createFailed', 'Failed to create comment', error, {
70
+ ...params,
71
+ userId,
72
+ });
73
+ }
74
+ });
75
+ router.get('/:resourceType/:resourceId/comments', async (req, res) => {
76
+ const params = resourceParams(req, res);
77
+ if (!params)
78
+ return;
79
+ try {
80
+ if (!(await canAccessCommentResource(params.resourceType, params.resourceId, 'read', getUserId(res) ?? undefined))) {
81
+ return sendNotFound(res);
82
+ }
83
+ res.json(await getCommentsByResource(params.resourceType, params.resourceId, {
84
+ limit: queryLimit(req.query.limit) ?? 20,
85
+ offset: queryOffset(req.query.offset) ?? 0,
86
+ order: queryOrder(req.query.order),
87
+ }));
88
+ }
89
+ catch (error) {
90
+ sendServerError(res, 'comment.error.listFailed', 'Failed to list comments', error, params);
91
+ }
92
+ });
93
+ router.get('/:resourceType/:resourceId/comments/count', async (req, res) => {
94
+ const params = resourceParams(req, res);
95
+ if (!params)
96
+ return;
97
+ try {
98
+ if (!(await canAccessCommentResource(params.resourceType, params.resourceId, 'read', getUserId(res) ?? undefined))) {
99
+ return sendNotFound(res);
100
+ }
101
+ const count = await getCommentCount(params.resourceType, params.resourceId);
102
+ res.json({ count });
103
+ }
104
+ catch (error) {
105
+ sendServerError(res, 'comment.error.countFailed', 'Failed to count comments', error, params);
106
+ }
107
+ });
108
+ router.get('/comments/:commentId', async (req, res) => {
109
+ const commentId = queryString(req.params.commentId);
110
+ if (!commentId)
111
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
112
+ try {
113
+ const comment = await getCommentById(commentId);
114
+ if (!comment)
115
+ return sendNotFound(res);
116
+ if (!(await canAccessCommentResource(comment.resourceType, comment.resourceId, 'read', getUserId(res) ?? undefined))) {
117
+ return sendNotFound(res);
118
+ }
119
+ res.json(comment);
120
+ }
121
+ catch (error) {
122
+ sendServerError(res, 'comment.error.readFailed', 'Failed to read comment', error, { commentId });
123
+ }
124
+ });
125
+ router.put('/comments/:commentId', async (req, res) => {
126
+ const userId = getUserId(res);
127
+ if (!userId)
128
+ return sendUnauthorized(res);
129
+ const commentId = queryString(req.params.commentId);
130
+ if (!commentId)
131
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
132
+ const parsed = updateCommentSchema.safeParse(req.body);
133
+ if (!parsed.success) {
134
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues);
135
+ }
136
+ try {
137
+ const updated = await updateComment(commentId, userId, parsed.data);
138
+ if (!updated) {
139
+ return sendError(res, 404, 'comment.error.notFoundOrForbidden', 'Comment not found or not owned by user');
140
+ }
141
+ res.json(updated);
142
+ }
143
+ catch (error) {
144
+ sendServerError(res, 'comment.error.updateFailed', 'Failed to update comment', error, {
145
+ commentId,
146
+ userId,
147
+ });
148
+ }
149
+ });
150
+ router.delete('/comments/:commentId', async (req, res) => {
151
+ const userId = getUserId(res);
152
+ if (!userId)
153
+ return sendUnauthorized(res);
154
+ const commentId = queryString(req.params.commentId);
155
+ if (!commentId)
156
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
157
+ try {
158
+ const deleted = await deleteComment(commentId, userId);
159
+ if (!deleted) {
160
+ return sendError(res, 404, 'comment.error.notFoundOrForbidden', 'Comment not found or not owned by user');
161
+ }
162
+ res.status(204).end();
163
+ }
164
+ catch (error) {
165
+ sendServerError(res, 'comment.error.deleteFailed', 'Failed to delete comment', error, {
166
+ commentId,
167
+ userId,
168
+ });
169
+ }
170
+ });
171
+ router.get('/comments/:commentId/replies', async (req, res) => {
172
+ const commentId = queryString(req.params.commentId);
173
+ if (!commentId)
174
+ return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required');
175
+ try {
176
+ const parent = await getCommentById(commentId);
177
+ if (!parent)
178
+ return sendNotFound(res);
179
+ if (!(await canAccessCommentResource(parent.resourceType, parent.resourceId, 'read', getUserId(res) ?? undefined))) {
180
+ return sendNotFound(res);
181
+ }
182
+ res.json(await getReplies(commentId, {
183
+ limit: queryLimit(req.query.limit) ?? 20,
184
+ offset: queryOffset(req.query.offset) ?? 0,
185
+ order: queryOrder(req.query.order),
186
+ }));
187
+ }
188
+ catch (error) {
189
+ sendServerError(res, 'comment.error.repliesFailed', 'Failed to list replies', error, {
190
+ commentId,
191
+ });
192
+ }
193
+ });
194
+ export default router;
package/dist/service.d.ts CHANGED
@@ -30,7 +30,7 @@ import type { Comment, CreateCommentInput, PaginatedResult, PaginationOptions, U
30
30
  * @throws {Error} When the comment could not be numbered; the comment row is
31
31
  * removed again so the caller is not told a create failed while it exists.
32
32
  */
33
- export declare function createComment(resourceType: string, resourceId: string, userId: string, data: CreateCommentInput): Promise<NumberedComment>;
33
+ export declare function createComment(resourceType: string, resourceId: string, userId: string | null, data: CreateCommentInput): Promise<NumberedComment>;
34
34
  /**
35
35
  * Retrieves paginated comments for a resource, ordered by creation date descending.
36
36
  * Only returns top-level comments (no replies).
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAqBH,OAAO,KAAK,EAAE,eAAe,EAAE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"}
package/dist/service.js CHANGED
@@ -18,12 +18,17 @@ async function withAuthors(comments) {
18
18
  const loader = globalThis[PUBLIC_PROFILES_KEY];
19
19
  if (!loader)
20
20
  return comments;
21
+ const userIds = comments
22
+ .map((comment) => comment.userId)
23
+ .filter((id) => Boolean(id));
24
+ if (userIds.length === 0)
25
+ return comments;
21
26
  try {
22
- const profiles = await loader(comments.map((comment) => comment.userId));
27
+ const profiles = await loader(userIds);
23
28
  if (profiles.size === 0)
24
29
  return comments;
25
30
  return comments.map((comment) => {
26
- const author = profiles.get(comment.userId);
31
+ const author = comment.userId ? profiles.get(comment.userId) : undefined;
27
32
  return author ? { ...comment, author } : comment;
28
33
  });
29
34
  }
@@ -64,6 +69,14 @@ async function withNumbers(comments) {
64
69
  * removed again so the caller is not told a create failed while it exists.
65
70
  */
66
71
  export async function createComment(resourceType, resourceId, userId, data) {
72
+ const trimmedBody = data.body.trim();
73
+ if (!trimmedBody) {
74
+ throw new Error('Comment body is required');
75
+ }
76
+ const guestName = userId ? null : (data.authorName?.trim() ?? '');
77
+ if (!userId && !guestName) {
78
+ throw new Error('Author name is required for guest comments');
79
+ }
67
80
  const hasPolicies = hasResourceAccessPolicies();
68
81
  const policy = getResourceAccessPolicy(resourceType);
69
82
  const execute = async () => {
@@ -85,8 +98,9 @@ export async function createComment(resourceType, resourceId, userId, data) {
85
98
  resourceType,
86
99
  resourceId,
87
100
  userId,
101
+ ...(guestName ? { authorName: guestName } : {}),
88
102
  parentId: data.parentId ?? null,
89
- body: data.body,
103
+ body: trimmedBody,
90
104
  editedAt: null,
91
105
  });
92
106
  const comment = result.data;
@@ -141,6 +155,7 @@ export async function createComment(resourceType, resourceId, userId, data) {
141
155
  export async function getCommentsByResource(resourceType, resourceId, options = {}) {
142
156
  const limit = options.limit ?? 20;
143
157
  const offset = options.offset ?? 0;
158
+ const direction = options.order === 'asc' ? 'asc' : 'desc';
144
159
  const where = [
145
160
  { field: 'resourceType', operator: '=', value: resourceType },
146
161
  { field: 'resourceId', operator: '=', value: resourceId },
@@ -149,7 +164,7 @@ export async function getCommentsByResource(resourceType, resourceId, options =
149
164
  const [data, total] = await Promise.all([
150
165
  findMany(TABLE, {
151
166
  where,
152
- orderBy: [{ field: 'createdAt', direction: 'desc' }],
167
+ orderBy: [{ field: 'createdAt', direction }],
153
168
  limit,
154
169
  offset,
155
170
  }),
@@ -182,10 +197,10 @@ export async function getCommentById(commentId) {
182
197
  */
183
198
  export async function updateComment(commentId, userId, data) {
184
199
  const existing = await findById(TABLE, commentId);
185
- if (!existing || existing.userId !== userId)
200
+ if (!existing || !existing.userId || existing.userId !== userId)
186
201
  return null;
187
202
  const result = await updateById(TABLE, commentId, {
188
- body: data.body,
203
+ body: data.body.trim(),
189
204
  editedAt: new Date().toISOString(),
190
205
  // Strictly later than the last write: an edit in the same millisecond as the create
191
206
  // still shows a changed updatedAt.
@@ -207,7 +222,7 @@ export async function updateComment(commentId, userId, data) {
207
222
  */
208
223
  export async function deleteComment(commentId, userId) {
209
224
  const existing = await findById(TABLE, commentId);
210
- if (!existing || existing.userId !== userId)
225
+ if (!existing || !existing.userId || existing.userId !== userId)
211
226
  return false;
212
227
  await deleteById(TABLE, commentId);
213
228
  return true;
@@ -223,11 +238,12 @@ export async function deleteComment(commentId, userId) {
223
238
  export async function getReplies(commentId, options = {}) {
224
239
  const limit = options.limit ?? 20;
225
240
  const offset = options.offset ?? 0;
241
+ const direction = options.order === 'desc' ? 'desc' : 'asc';
226
242
  const where = [{ field: 'parentId', operator: '=', value: commentId }];
227
243
  const [data, total] = await Promise.all([
228
244
  findMany(TABLE, {
229
245
  where,
230
- orderBy: [{ field: 'createdAt', direction: 'asc' }],
246
+ orderBy: [{ field: 'createdAt', direction }],
231
247
  limit,
232
248
  offset,
233
249
  }),
package/dist/types.d.ts CHANGED
@@ -31,8 +31,10 @@ export interface Comment {
31
31
  resourceType: string;
32
32
  /** The ID of the resource this comment is attached to. */
33
33
  resourceId: string;
34
- /** The ID of the user who created this comment. */
35
- userId: string;
34
+ /** The ID of the user who created this comment, or `null` for guest comments. */
35
+ userId: string | null;
36
+ /** Display name supplied for a guest comment, or `null` for authenticated comments. */
37
+ authorName?: string | null;
36
38
  /** Hydrated public author profile when `@molecule/api-resource-user` is loaded. */
37
39
  author?: CommentAuthor | null;
38
40
  /** The parent comment ID for threaded replies, or `null` for top-level comments. */
@@ -54,6 +56,8 @@ export interface CreateCommentInput {
54
56
  body: string;
55
57
  /** Optional parent comment ID for threaded replies. */
56
58
  parentId?: string;
59
+ /** Display name when posting as an unauthenticated guest (ignored when signed in). */
60
+ authorName?: string;
57
61
  }
58
62
  /**
59
63
  * Input for updating an existing comment.
@@ -70,6 +74,8 @@ export interface PaginationOptions {
70
74
  limit?: number;
71
75
  /** Number of results to skip. */
72
76
  offset?: number;
77
+ /** Sort direction by creation time (`'asc'` or `'desc'`). */
78
+ order?: 'asc' | 'desc';
73
79
  }
74
80
  /**
75
81
  * A paginated result set.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,iGAAiG;AACjG,MAAM,WAAW,aAAa;IAC5B,+BAA+B;IAC/B,EAAE,EAAE,MAAM,CAAA;IACV,qCAAqC;IACrC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,yCAAyC;IACzC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,sCAAsC;IACtC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;IAClB,uCAAuC;IACvC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,OAAO;IACtB,iCAAiC;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,4FAA4F;IAC5F,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,iFAAiF;IACjF,YAAY,EAAE,MAAM,CAAA;IACpB,0DAA0D;IAC1D,UAAU,EAAE,MAAM,CAAA;IAClB,mD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KAAK,CAAC,EAAE,KAAK,GAAG,MAAM,CAAA;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,6CAA6C;IAC7C,IAAI,EAAE,CAAC,EAAE,CAAA;IACT,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAA;IACb,0CAA0C;IAC1C,KAAK,EAAE,MAAM,CAAA;IACb,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAA;CACf"}
@@ -10,6 +10,7 @@ import { z } from 'zod';
10
10
  export declare const createCommentSchema: z.ZodObject<{
11
11
  body: z.ZodString;
12
12
  parentId: z.ZodOptional<z.ZodString>;
13
+ authorName: z.ZodOptional<z.ZodString>;
13
14
  }, z.core.$strip>;
14
15
  /**
15
16
  * Schema for validating comment update input.
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;iBAK9B,CAAA;AAEF;;GAEG;AACH,eAAO,MAAM,mBAAmB;;iBAG9B,CAAA"}
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;iBAO9B,CAAA;AAEF;;GAEG;AACH,eAAO,MAAM,mBAAmB;;iBAG9B,CAAA"}
@@ -8,15 +8,17 @@ import { z } from 'zod';
8
8
  * Schema for validating comment creation input.
9
9
  */
10
10
  export const createCommentSchema = z.object({
11
- /** The comment body text. Must be non-empty and at most 10,000 characters. */
12
- body: z.string().min(1).max(10_000),
11
+ /** The comment body text. Must be non-empty after trimming and at most 10,000 characters. */
12
+ body: z.string().trim().min(1).max(10_000),
13
13
  /** Optional parent comment ID for threaded replies. */
14
14
  parentId: z.string().uuid().optional(),
15
+ /** Display name for guest comments (ignored when authenticated to prevent spoofing). */
16
+ authorName: z.string().trim().min(1).max(120).optional(),
15
17
  });
16
18
  /**
17
19
  * Schema for validating comment update input.
18
20
  */
19
21
  export const updateCommentSchema = z.object({
20
- /** The updated comment body text. Must be non-empty and at most 10,000 characters. */
21
- body: z.string().min(1).max(10_000),
22
+ /** The updated comment body text. Must be non-empty after trimming and at most 10,000 characters. */
23
+ body: z.string().trim().min(1).max(10_000),
22
24
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource-comment",
3
- "version": "1.4.1",
3
+ "version": "1.6.0",
4
4
  "description": "Threaded comments on any resource with polymorphic attachment, pagination and sequential integer comment numbers (createNumberedComment)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -19,6 +19,7 @@
19
19
  "files": [
20
20
  "dist",
21
21
  "src/__setup__",
22
+ "src/scaffold-router.ts",
22
23
  "README.md"
23
24
  ],
24
25
  "keywords": [
@@ -31,7 +32,10 @@
31
32
  "devDependencies": {
32
33
  "@molecule/api-database": "1.2.2",
33
34
  "@molecule/api-database-sqlite": "1.4.4",
35
+ "@molecule/api-rate-limit": "1.0.4",
36
+ "@types/express": "5.0.6",
34
37
  "@types/node": "26.6.5",
38
+ "express": "5.3.0",
35
39
  "typescript": "6.0.3",
36
40
  "vitest": "4.1.12",
37
41
  "zod": "4.6.7"
@@ -40,14 +44,11 @@
40
44
  "@molecule/api-database": "^1.1.0",
41
45
  "@molecule/api-i18n": "^1.0.1",
42
46
  "@molecule/api-logger": "^1.0.1",
43
- "@molecule/api-resource": "^1.0.1",
47
+ "@molecule/api-rate-limit": "^1.0.1",
48
+ "@molecule/api-resource": "^1.4.0",
49
+ "express": "^5.0.0",
44
50
  "zod": "^4.0.0"
45
51
  },
46
- "peerDependenciesMeta": {
47
- "@molecule/api-resource": {
48
- "optional": true
49
- }
50
- },
51
52
  "repository": {
52
53
  "type": "git",
53
54
  "url": "https://github.com/molecule-dev/molecule.git",
@@ -2,7 +2,8 @@ CREATE TABLE IF NOT EXISTS "comments" (
2
2
  "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
3
3
  "resourceType" VARCHAR(255) NOT NULL,
4
4
  "resourceId" VARCHAR(255) NOT NULL,
5
- "userId" UUID NOT NULL,
5
+ "userId" UUID,
6
+ "authorName" VARCHAR(120),
6
7
  "parentId" UUID REFERENCES "comments"("id") ON DELETE CASCADE,
7
8
  "body" TEXT NOT NULL,
8
9
  "editedAt" TIMESTAMPTZ,
@@ -10,7 +11,6 @@ CREATE TABLE IF NOT EXISTS "comments" (
10
11
  "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT now()
11
12
  );
12
13
 
13
- CREATE INDEX IF NOT EXISTS "idx_comments_resource" ON "comments" ("resourceType", "resourceId");
14
14
  CREATE INDEX IF NOT EXISTS "idx_comments_resource_created" ON "comments" ("resourceType", "resourceId", "createdAt");
15
15
  CREATE INDEX IF NOT EXISTS "idx_comments_parent" ON "comments" ("parentId");
16
16
  CREATE INDEX IF NOT EXISTS "idx_comments_user" ON "comments" ("userId");
@@ -0,0 +1,265 @@
1
+ import { type NextFunction, type Request, type Response, Router } from 'express'
2
+
3
+ import {
4
+ consume as consumeRateLimit,
5
+ hasProvider as hasRateLimitProvider,
6
+ } from '@molecule/api-rate-limit'
7
+ import {
8
+ getUserId,
9
+ queryLimit,
10
+ queryOffset,
11
+ queryString,
12
+ sendError,
13
+ sendNotFound,
14
+ sendServerError,
15
+ sendUnauthorized,
16
+ sendValidationError,
17
+ } from '@molecule/api-resource'
18
+ import {
19
+ canAccessCommentResource,
20
+ CommentResourceAccessError,
21
+ createComment,
22
+ createCommentSchema,
23
+ deleteComment,
24
+ getCommentById,
25
+ getCommentCount,
26
+ getCommentsByResource,
27
+ getReplies,
28
+ updateComment,
29
+ updateCommentSchema,
30
+ } from '@molecule/api-resource-comment'
31
+
32
+ // Edit paths, allowlisted resource types, and JSON here. Comment services own
33
+ // persistence, sequential numbering, author hydration, and ownership checks.
34
+ // Fail-closed access: once any sibling resource registers a policy via
35
+ // registerResourceAccessPolicy() (e.g. articles.ts), unregistered resourceTypes
36
+ // and private/draft parents are refused with 404.
37
+ // Set ALLOW_GUEST_COMMENTS = true on public sites (e.g. blogs) so unauthenticated
38
+ // readers may post comments by supplying `authorName` (rate-limited; signed-in
39
+ // users always post under their account to prevent spoofing).
40
+ const ALLOW_GUEST_COMMENTS = false
41
+ const RESOURCE_TYPE_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/i
42
+ const router = Router()
43
+
44
+ /** Read an optional sort direction (`'asc'` or `'desc'`). */
45
+ function queryOrder(value: unknown): 'asc' | 'desc' | undefined {
46
+ return value === 'asc' || value === 'desc' ? value : undefined
47
+ }
48
+
49
+ /** Validate `resourceType` and `resourceId` path params. */
50
+ function resourceParams(
51
+ req: Request,
52
+ res: Response,
53
+ ): { resourceType: string; resourceId: string } | null {
54
+ const resourceType = queryString(req.params.resourceType)
55
+ const resourceId = queryString(req.params.resourceId)
56
+ if (!resourceType || !resourceId || !RESOURCE_TYPE_PATTERN.test(resourceType)) {
57
+ sendError(res, 400, 'comment.error.missingResource', 'Resource type and ID are required')
58
+ return null
59
+ }
60
+ return { resourceType, resourceId }
61
+ }
62
+
63
+ /** Throttle comment creation when a rate-limit provider is bonded. */
64
+ async function rateLimitComments(req: Request, res: Response, next: NextFunction): Promise<void> {
65
+ if (!hasRateLimitProvider()) {
66
+ next()
67
+ return
68
+ }
69
+ const key = `comments:create:${getUserId(res) ?? req.ip ?? 'unknown'}`
70
+ const result = await consumeRateLimit(key)
71
+ if (!result.allowed) {
72
+ const retryAfter =
73
+ result.retryAfter ?? Math.max(1, Math.ceil((result.resetAt.getTime() - Date.now()) / 1000))
74
+ res.set('Retry-After', String(retryAfter))
75
+ sendError(
76
+ res,
77
+ 429,
78
+ 'rateLimit.error.tooManyRequests',
79
+ 'Too many requests. Please try again later.',
80
+ )
81
+ return
82
+ }
83
+ next()
84
+ }
85
+
86
+ router.post('/:resourceType/:resourceId/comments', rateLimitComments, async (req, res) => {
87
+ const userId = getUserId(res)
88
+ if (!userId && !ALLOW_GUEST_COMMENTS) return sendUnauthorized(res)
89
+ const params = resourceParams(req, res)
90
+ if (!params) return
91
+
92
+ const parsed = createCommentSchema.safeParse(req.body)
93
+ if (!parsed.success) {
94
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues)
95
+ }
96
+ if (!userId && !parsed.data.authorName) {
97
+ return sendValidationError(res, 'comment.error.validationFailed', [
98
+ { path: ['authorName'], message: 'Name is required' },
99
+ ])
100
+ }
101
+
102
+ try {
103
+ const comment = await createComment(params.resourceType, params.resourceId, userId, parsed.data)
104
+ res.status(201).json(comment)
105
+ } catch (error) {
106
+ if (error instanceof CommentResourceAccessError) return sendNotFound(res)
107
+ sendServerError(res, 'comment.error.createFailed', 'Failed to create comment', error, {
108
+ ...params,
109
+ userId,
110
+ })
111
+ }
112
+ })
113
+
114
+ router.get('/:resourceType/:resourceId/comments', async (req, res) => {
115
+ const params = resourceParams(req, res)
116
+ if (!params) return
117
+ try {
118
+ if (
119
+ !(await canAccessCommentResource(
120
+ params.resourceType,
121
+ params.resourceId,
122
+ 'read',
123
+ getUserId(res) ?? undefined,
124
+ ))
125
+ ) {
126
+ return sendNotFound(res)
127
+ }
128
+ res.json(
129
+ await getCommentsByResource(params.resourceType, params.resourceId, {
130
+ limit: queryLimit(req.query.limit) ?? 20,
131
+ offset: queryOffset(req.query.offset) ?? 0,
132
+ order: queryOrder(req.query.order),
133
+ }),
134
+ )
135
+ } catch (error) {
136
+ sendServerError(res, 'comment.error.listFailed', 'Failed to list comments', error, params)
137
+ }
138
+ })
139
+
140
+ router.get('/:resourceType/:resourceId/comments/count', async (req, res) => {
141
+ const params = resourceParams(req, res)
142
+ if (!params) return
143
+ try {
144
+ if (
145
+ !(await canAccessCommentResource(
146
+ params.resourceType,
147
+ params.resourceId,
148
+ 'read',
149
+ getUserId(res) ?? undefined,
150
+ ))
151
+ ) {
152
+ return sendNotFound(res)
153
+ }
154
+ const count = await getCommentCount(params.resourceType, params.resourceId)
155
+ res.json({ count })
156
+ } catch (error) {
157
+ sendServerError(res, 'comment.error.countFailed', 'Failed to count comments', error, params)
158
+ }
159
+ })
160
+
161
+ router.get('/comments/:commentId', async (req, res) => {
162
+ const commentId = queryString(req.params.commentId)
163
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
164
+ try {
165
+ const comment = await getCommentById(commentId)
166
+ if (!comment) return sendNotFound(res)
167
+ if (
168
+ !(await canAccessCommentResource(
169
+ comment.resourceType,
170
+ comment.resourceId,
171
+ 'read',
172
+ getUserId(res) ?? undefined,
173
+ ))
174
+ ) {
175
+ return sendNotFound(res)
176
+ }
177
+ res.json(comment)
178
+ } catch (error) {
179
+ sendServerError(res, 'comment.error.readFailed', 'Failed to read comment', error, { commentId })
180
+ }
181
+ })
182
+
183
+ router.put('/comments/:commentId', async (req, res) => {
184
+ const userId = getUserId(res)
185
+ if (!userId) return sendUnauthorized(res)
186
+ const commentId = queryString(req.params.commentId)
187
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
188
+ const parsed = updateCommentSchema.safeParse(req.body)
189
+ if (!parsed.success) {
190
+ return sendValidationError(res, 'comment.error.validationFailed', parsed.error.issues)
191
+ }
192
+ try {
193
+ const updated = await updateComment(commentId, userId, parsed.data)
194
+ if (!updated) {
195
+ return sendError(
196
+ res,
197
+ 404,
198
+ 'comment.error.notFoundOrForbidden',
199
+ 'Comment not found or not owned by user',
200
+ )
201
+ }
202
+ res.json(updated)
203
+ } catch (error) {
204
+ sendServerError(res, 'comment.error.updateFailed', 'Failed to update comment', error, {
205
+ commentId,
206
+ userId,
207
+ })
208
+ }
209
+ })
210
+
211
+ router.delete('/comments/:commentId', async (req, res) => {
212
+ const userId = getUserId(res)
213
+ if (!userId) return sendUnauthorized(res)
214
+ const commentId = queryString(req.params.commentId)
215
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
216
+ try {
217
+ const deleted = await deleteComment(commentId, userId)
218
+ if (!deleted) {
219
+ return sendError(
220
+ res,
221
+ 404,
222
+ 'comment.error.notFoundOrForbidden',
223
+ 'Comment not found or not owned by user',
224
+ )
225
+ }
226
+ res.status(204).end()
227
+ } catch (error) {
228
+ sendServerError(res, 'comment.error.deleteFailed', 'Failed to delete comment', error, {
229
+ commentId,
230
+ userId,
231
+ })
232
+ }
233
+ })
234
+
235
+ router.get('/comments/:commentId/replies', async (req, res) => {
236
+ const commentId = queryString(req.params.commentId)
237
+ if (!commentId) return sendError(res, 400, 'comment.error.missingId', 'Comment ID is required')
238
+ try {
239
+ const parent = await getCommentById(commentId)
240
+ if (!parent) return sendNotFound(res)
241
+ if (
242
+ !(await canAccessCommentResource(
243
+ parent.resourceType,
244
+ parent.resourceId,
245
+ 'read',
246
+ getUserId(res) ?? undefined,
247
+ ))
248
+ ) {
249
+ return sendNotFound(res)
250
+ }
251
+ res.json(
252
+ await getReplies(commentId, {
253
+ limit: queryLimit(req.query.limit) ?? 20,
254
+ offset: queryOffset(req.query.offset) ?? 0,
255
+ order: queryOrder(req.query.order),
256
+ }),
257
+ )
258
+ } catch (error) {
259
+ sendServerError(res, 'comment.error.repliesFailed', 'Failed to list replies', error, {
260
+ commentId,
261
+ })
262
+ }
263
+ })
264
+
265
+ export default router