@respectify/astro 1.0.2 → 1.1.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
@@ -20,6 +20,7 @@ Built for production — powers [nickhodges.com](https://nickhodges.com) as a li
20
20
  - **Never touches your schema** — the package ships table definitions and drizzle-kit migrations; you decide when they run
21
21
  - **Self-contained CSS** — no Tailwind required; customize via CSS variables
22
22
  - **Fail-closed** — rejects comments when Respectify is unavailable
23
+ - **Free plan aware** — revisions don't use up free comments; when the free plan runs out, comments go through unmoderated and you are told, not your commenters
23
24
 
24
25
  ## Requirements
25
26
 
@@ -261,7 +262,7 @@ respectify({
261
262
  });
262
263
  ```
263
264
 
264
- The runtime module takes the store and the two optional post functions:
265
+ The runtime module takes the store, the two optional post functions, and two optional callbacks for the site owner:
265
266
 
266
267
  ```ts
267
268
  export default defineRespectifyRuntime({
@@ -272,6 +273,10 @@ export default defineRespectifyRuntime({
272
273
  // fetch getPostUrl. Useful for staged/preview/auth-gated content, or when the URL isn't
273
274
  // live yet right after deploy. Takes priority over getPostUrl.
274
275
  getPostContent: async (slug) => loadPostBody(slug),
276
+ // The free plan is used up: comments are now published unmoderated. Tell yourself.
277
+ onModerationStopped: async ({ reason, upgradeUrl, message, postSlug }) => sendAlert(message),
278
+ // A comment is waiting in your store with approved: false (see "Free plan" below)
279
+ onHeldForReview: async ({ reason, comment }) => sendAlert(`Comment ${comment.id} awaits review`),
275
280
  });
276
281
  ```
277
282
 
@@ -325,6 +330,18 @@ Spam, off-topic (`blockOffTopic`) and dogwhistle (`blockDogwhistles`) rejections
325
330
 
326
331
  `exceeds_tolerance` decides whether a comment has a problem at all, because it reflects your site's comment-health tolerances (any item below its minimum, or severe toxicity); `toxicity_score` does not, so it only chooses between warning and blocking. `thresholds.autoApprove` applies only when the API returns a comment score without `exceeds_tolerance` (an API older than tolerances), where the previous bands are used. The returned `exceedsTolerance` field carries the verdict.
327
332
 
333
+ ### Free plan: revisions, running out, and held comments
334
+
335
+ A free Respectify account gets 200 comments for life. The integration handles the three things that follow from that; a paid account never sees any of them.
336
+
337
+ **Revisions are free.** When a comment is sent back to the commenter, the API returns a revision token and `comments.submit` passes it to the browser (`revisionToken` on the unpublished result). The bundled form keeps it in a hidden field and sends it back with the revised comment, so the revision is not counted as a new comment. A comment gets five attempts: the original and four revisions. The token belongs to that one comment and that one form; it is never stored on the server. If you write your own form, send `revisionToken` back in the next `comments.submit` for the same comment and drop it once the comment is published or held.
338
+
339
+ **When the free plan is used up**, Respectify stops assessing comments. The comment the commenter just wrote is published as it is, like any approved comment, and the commenter sees the ordinary success message (without a score). The published result carries `unmoderated: true`, and the `respectify:comment-published` event's detail carries `unmoderated`, so a site can style such comments if it wants. You are told, not your commenters: the integration logs at error level with the upgrade URL on every unmoderated comment, and calls `onModerationStopped({ reason: 'free_allowance_exhausted', upgradeUrl, message, postSlug })` from your runtime module if you set it. Add credit at the upgrade URL and moderation resumes on the next comment. The ordinary insufficient-balance error on a paid account is unchanged: comments are rejected as "temporarily unavailable", as before.
340
+
341
+ **When a comment has used all five attempts**, it is neither published nor rejected: it is stored with `approved: false` for you to review, the commenter is told "Thanks, your comment has been sent to the moderators for review." (`comments.submit` returns `{ success: true, approved: false, heldForReview: true, message }`), and `onHeldForReview({ reason: 'revision_limit_reached', comment })` is called if you set it. No schema change is needed: `approved` has always been a column, `listApproved` has always filtered on it, and the integration never used to store unapproved comments, so an `approved = false` row is, by definition, one waiting for you. Set `approved` to true to publish it, or delete it. Replies to a held comment are refused until it is approved, as for any unapproved comment.
342
+
343
+ The form's `respectify:comment-held` event fires when a comment is held; the comment list does not change.
344
+
328
345
  ### Admin delete (optional)
329
346
 
330
347
  Set `enableDelete` on `CommentSection` and implement auth so `context.locals.isAuthenticated` is true. See the [Nick-Blog](https://github.com/NickHodges/Nick-Blog) repo for a full admin auth example.
@@ -336,6 +353,8 @@ Visitor submits comment
336
353
  → Astro Action (comments.submit)
337
354
  → Respectify megacall (configured checks: spam, score, relevance, dogwhistle, …)
338
355
  → If approved: store.create() saves it through your ICommentStore
356
+ → If sent back for revision: the browser keeps the revision token for the resubmission
357
+ → If held for review (free plan, fifth attempt): store.create() saves it with approved: false
339
358
  → Client refreshes comment list via GET /api/respectify/comments (store.listApproved())
340
359
  ```
341
360
 
@@ -13,6 +13,9 @@ const { postSlug } = Astro.props;
13
13
  </p>
14
14
 
15
15
  <form class="rf-comments__form" data-post-slug={postSlug} id="rf-comment-form">
16
+ <!-- On the free plan, the token the last unpublished submission returned; resent so a revision is not counted as a new comment -->
17
+ <input id="rf-revision-token" name="revisionToken" type="hidden" value="" />
18
+
16
19
  <div class="rf-comments__field">
17
20
  <label class="rf-comments__label" for="rf-author">
18
21
  Name <span class="rf-comments__required">*</span>
@@ -58,8 +61,9 @@ const { postSlug } = Astro.props;
58
61
  const messageEl = document.getElementById('rf-form-message');
59
62
  const submitButton = document.getElementById('rf-submit-button') as HTMLButtonElement | null;
60
63
  const buttonText = document.getElementById('rf-button-text');
64
+ const revisionTokenInput = document.getElementById('rf-revision-token') as HTMLInputElement | null;
61
65
 
62
- if (form && messageEl && submitButton && buttonText) {
66
+ if (form && messageEl && submitButton && buttonText && revisionTokenInput) {
63
67
  const postSlug = form.dataset.postSlug || '';
64
68
 
65
69
  form.addEventListener('submit', async (e) => {
@@ -70,6 +74,7 @@ const { postSlug } = Astro.props;
70
74
  buttonText.textContent = 'Analyzing with Respectify AI...';
71
75
 
72
76
  const formData = new FormData(form);
77
+ const revisionToken = revisionTokenInput.value || undefined;
73
78
 
74
79
  try {
75
80
  const { data, error } = await actions.comments.submit({
@@ -77,6 +82,7 @@ const { postSlug } = Astro.props;
77
82
  author: formData.get('author') as string,
78
83
  email: (formData.get('email') as string) || undefined,
79
84
  content: formData.get('content') as string,
85
+ ...(revisionToken ? { revisionToken } : {}),
80
86
  });
81
87
 
82
88
  messageEl.classList.remove('rf-comments__hidden', 'rf-comments__message--success', 'rf-comments__message--warning', 'rf-comments__message--error');
@@ -93,12 +99,24 @@ const { postSlug } = Astro.props;
93
99
  messageEl.classList.add('rf-comments__message--success');
94
100
  messageEl.appendChild(createTextDiv(`✓ ${data.message}`, 'rf-comments__message-title'));
95
101
  messageEl.appendChild(createTextDiv(data.feedback, 'rf-comments__message-body'));
96
- if (data.score !== undefined) {
102
+ // An unmoderated comment has no real score to show
103
+ if (data.score !== undefined && !data.unmoderated) {
97
104
  messageEl.appendChild(createTextDiv(`Respectfulness score: ${(data.score * 100).toFixed(0)}%`, 'rf-comments__message-score'));
98
105
  }
99
106
  form.reset();
100
- window.dispatchEvent(new CustomEvent('respectify:comment-published', { detail: { postSlug } }));
107
+ revisionTokenInput.value = '';
108
+ window.dispatchEvent(
109
+ new CustomEvent('respectify:comment-published', { detail: { postSlug, unmoderated: data.unmoderated } }),
110
+ );
111
+ } else if (data.heldForReview) {
112
+ messageEl.classList.add('rf-comments__message--success');
113
+ messageEl.appendChild(createTextDiv(`✓ ${data.message}`, 'rf-comments__message-title'));
114
+ form.reset();
115
+ revisionTokenInput.value = '';
116
+ window.dispatchEvent(new CustomEvent('respectify:comment-held', { detail: { postSlug } }));
101
117
  } else {
118
+ // Keep the token for the revised resubmission; it belongs to this comment only
119
+ revisionTokenInput.value = data.revisionToken ?? '';
102
120
  messageEl.classList.add('rf-comments__message--warning');
103
121
  messageEl.appendChild(createTextDiv('Comment needs improvement', 'rf-comments__message-title'));
104
122
  messageEl.appendChild(createTextDiv(data.feedback || 'Your comment did not meet our respectfulness standards.', 'rf-comments__message-body'));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@respectify/astro",
3
- "version": "1.0.2",
4
- "description": "Respectify-powered commenting for Astro \u2014 AI moderation, spam filtering, and beautiful UX out of the box.",
3
+ "version": "1.1.0",
4
+ "description": "Respectify-powered commenting for Astro — AI moderation, spam filtering, and beautiful UX out of the box.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Respectify",
@@ -53,7 +53,7 @@
53
53
  ],
54
54
  "peerDependencies": {
55
55
  "@libsql/client": ">=0.10.0",
56
- "@respectify/client": "^0.7.0",
56
+ "@respectify/client": "^0.8.0",
57
57
  "astro": "^5.0.0 || ^6.0.0 || ^7.0.0",
58
58
  "drizzle-orm": "^0.45.0",
59
59
  "pg": "^8.0.0",
@@ -84,7 +84,7 @@
84
84
  "devDependencies": {
85
85
  "@electric-sql/pglite": "0.5.8",
86
86
  "@libsql/client": "^0.18.0",
87
- "@respectify/client": "^0.7.0",
87
+ "@respectify/client": "^0.8.0",
88
88
  "astro": "^6.0.4",
89
89
  "drizzle-kit": "^0.31.11",
90
90
  "drizzle-orm": "^0.45.4",
package/src/actions.ts CHANGED
@@ -1,11 +1,21 @@
1
1
  import { defineAction, ActionError, type ActionAPIContext } from 'astro:actions';
2
2
  import { z } from 'astro/zod';
3
3
  import { analyzeComment } from './lib/service';
4
+ import { logger } from './lib/logger';
5
+ import { HELD_FOR_REVIEW_MESSAGE } from './lib/messages';
4
6
  import { checkRateLimit } from './lib/rate-limit';
5
7
  import { getIntegrationOptions } from './runtime-config';
6
8
  import { getRespectifyRuntime } from './runtime';
7
9
  import { COMMENT_LIMITS } from './store/limits';
8
10
  import { CommentValidationError } from './store/schemas';
11
+ import type { CommentRecord, NewComment } from './store/types';
12
+ import type { AnalyzeCommentOptions } from './types';
13
+
14
+ /**
15
+ * A revision token as the API issues it: URL-safe base64 characters. The pattern keeps
16
+ * anything else out of the request header the token is sent back in.
17
+ */
18
+ const REVISION_TOKEN_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
9
19
 
10
20
  /** Input to `comments.submit`. Uses Astro's Zod (3 on Astro 5, 4 on Astro 6+), so only API both share. */
11
21
  export const submitCommentInput = z.object({
@@ -14,6 +24,8 @@ export const submitCommentInput = z.object({
14
24
  email: z.string().email().max(COMMENT_LIMITS.emailMax).optional(),
15
25
  content: z.string().min(1).max(COMMENT_LIMITS.contentMax),
16
26
  parentId: z.number().int().positive().optional(),
27
+ /** The token a previous, unpublished submission of this comment returned (see `SubmitCommentResult`) */
28
+ revisionToken: z.string().regex(REVISION_TOKEN_PATTERN).optional(),
17
29
  });
18
30
 
19
31
  /** Input to `comments.delete`. */
@@ -26,19 +38,41 @@ export type DeleteCommentInput = z.infer<typeof deleteCommentInput>;
26
38
 
27
39
  export type SubmitCommentResult =
28
40
  | {
41
+ /** Not published: the commenter can revise and resubmit */
29
42
  success: false;
30
43
  approved: false;
44
+ heldForReview: false;
31
45
  feedback: string;
32
46
  suggestion: string | undefined;
33
47
  suspectedSpam: boolean;
34
48
  score: number;
49
+ /**
50
+ * On the free plan, send this back as `revisionToken` when the commenter resubmits the
51
+ * revised comment, so the revision is not counted as a new comment. Keep it with the
52
+ * form; it belongs to this comment only. Absent for paid accounts.
53
+ */
54
+ revisionToken?: string;
35
55
  }
36
56
  | {
57
+ /** Stored for the site owner to review, neither published nor rejected */
58
+ success: true;
59
+ approved: false;
60
+ heldForReview: true;
61
+ message: string;
62
+ }
63
+ | {
64
+ /** Published */
37
65
  success: true;
38
66
  approved: true;
67
+ heldForReview: false;
39
68
  feedback: string;
40
69
  score: number;
41
70
  message: string;
71
+ /**
72
+ * True when Respectify did not assess this comment because the account's free plan is
73
+ * used up. The comment is published all the same; a site can style it differently.
74
+ */
75
+ unmoderated: boolean;
42
76
  };
43
77
 
44
78
  /** The client's address, or a shared bucket when the adapter or rendering mode does not expose one. */
@@ -67,7 +101,7 @@ async function loadReplyTarget(parentId: number, postSlug: string): Promise<stri
67
101
  * @throws ActionError TOO_MANY_REQUESTS, or BAD_REQUEST for an invalid parent or comment
68
102
  */
69
103
  export async function submitComment(
70
- { postSlug, author, email, content, parentId }: SubmitCommentInput,
104
+ { postSlug, author, email, content, parentId, revisionToken }: SubmitCommentInput,
71
105
  context: Pick<ActionAPIContext, 'clientAddress'>,
72
106
  ): Promise<SubmitCommentResult> {
73
107
  const { rateLimit } = getIntegrationOptions();
@@ -79,37 +113,68 @@ export async function submitComment(
79
113
  }
80
114
 
81
115
  const replyToComment = parentId === undefined ? undefined : await loadReplyTarget(parentId, postSlug);
82
- const analysis = await analyzeComment(content, postSlug, { replyToComment });
116
+ const analyzeOptions: AnalyzeCommentOptions = { replyToComment };
117
+ if (revisionToken !== undefined) analyzeOptions.revisionToken = revisionToken;
118
+ const analysis = await analyzeComment(content, postSlug, analyzeOptions);
119
+
120
+ if (analysis.heldForReview) {
121
+ const comment = await storeComment({ postSlug, author, email, content, parentId, approved: false });
122
+ await notifyHeldForReview(comment);
123
+ return { success: true, approved: false, heldForReview: true, message: HELD_FOR_REVIEW_MESSAGE };
124
+ }
83
125
 
84
126
  if (!analysis.approved) {
85
127
  return {
86
128
  success: false,
87
129
  approved: false,
130
+ heldForReview: false,
88
131
  feedback: analysis.feedback,
89
132
  suggestion: analysis.suggestion,
90
133
  suspectedSpam: analysis.suspectedSpam === true,
91
134
  score: analysis.score,
135
+ ...(analysis.revisionToken === undefined ? {} : { revisionToken: analysis.revisionToken }),
92
136
  };
93
137
  }
94
138
 
95
- try {
96
- await getRespectifyRuntime().store.create({ postSlug, author, email, content, parentId, approved: true });
97
- } catch (error) {
98
- if (error instanceof CommentValidationError) {
99
- throw new ActionError({ code: 'BAD_REQUEST', message: error.message });
100
- }
101
- throw error;
102
- }
139
+ await storeComment({ postSlug, author, email, content, parentId, approved: true });
103
140
 
104
141
  return {
105
142
  success: true,
106
143
  approved: true,
144
+ heldForReview: false,
107
145
  feedback: analysis.feedback,
108
146
  score: analysis.score,
109
147
  message: 'Comment published successfully!',
148
+ unmoderated: analysis.moderationSkipped !== undefined,
110
149
  };
111
150
  }
112
151
 
152
+ /**
153
+ * Store a comment through the runtime's store.
154
+ * @throws ActionError BAD_REQUEST when the store rejects the comment
155
+ */
156
+ async function storeComment(comment: NewComment): Promise<CommentRecord> {
157
+ try {
158
+ return await getRespectifyRuntime().store.create(comment);
159
+ } catch (error) {
160
+ if (error instanceof CommentValidationError) {
161
+ throw new ActionError({ code: 'BAD_REQUEST', message: error.message });
162
+ }
163
+ throw error;
164
+ }
165
+ }
166
+
167
+ /** Tell the site owner a comment awaits their review, when the runtime asks to be told. */
168
+ async function notifyHeldForReview(comment: CommentRecord): Promise<void> {
169
+ const { onHeldForReview } = getRespectifyRuntime();
170
+ if (!onHeldForReview) return;
171
+ try {
172
+ await onHeldForReview({ reason: 'revision_limit_reached', comment });
173
+ } catch (error) {
174
+ logger.error('onHeldForReview failed', { commentId: comment.id, error });
175
+ }
176
+ }
177
+
113
178
  /**
114
179
  * Delete a comment. Only for an authenticated admin.
115
180
  * @throws ActionError UNAUTHORIZED when not logged in, NOT_FOUND when there is no such comment
@@ -19,5 +19,5 @@ export function defineRespectifyRuntime(runtime: RespectifyRuntime): RespectifyR
19
19
  return runtime;
20
20
  }
21
21
 
22
- export type { RespectifyRuntime } from './types';
22
+ export type { RespectifyRuntime, ModerationStoppedEvent, HeldForReviewEvent } from './types';
23
23
  export type { ICommentStore, CommentRecord, NewComment, PublicComment } from './store/types';
package/src/index.ts CHANGED
@@ -109,6 +109,11 @@ export type {
109
109
  RespectifyClientConfig,
110
110
  RespectifyMegacallConfig,
111
111
  AnalyzeCommentOptions,
112
+ ModerationSkipped,
113
+ ModerationStoppedEvent,
114
+ ModerationStoppedReason,
115
+ HeldForReviewEvent,
116
+ HeldForReviewReason,
112
117
  } from './types';
113
118
  export type { ICommentStore, CommentRecord, NewComment, PublicComment } from './store/types';
114
119
  export { CommentValidationError, newCommentSchema } from './store/schemas';
@@ -0,0 +1,2 @@
1
+ /** What the commenter is told when their comment is stored for the site owner to review. */
2
+ export const HELD_FOR_REVIEW_MESSAGE = 'Thanks, your comment has been sent to the moderators for review.';
@@ -4,13 +4,17 @@ import { RESPECTIFY_API_KEY, RESPECTIFY_EMAIL } from 'astro:env/server';
4
4
  import {
5
5
  RespectifyClient,
6
6
  AuthenticationError,
7
+ FreeAllowanceExhaustedError,
7
8
  PaymentRequiredError,
9
+ RateLimitedError,
8
10
  RespectifyError,
11
+ RevisionLimitReachedError,
9
12
  type MegacallOptions,
10
13
  type MegaCallResult,
11
14
  } from '@respectify/client';
12
15
  import { getRespectifyRuntime } from '../runtime';
13
16
  import { logger } from './logger';
17
+ import { HELD_FOR_REVIEW_MESSAGE } from './messages';
14
18
  import type { AnalyzeCommentOptions, RespectifyAnalysisResult } from '../types';
15
19
 
16
20
  let client: RespectifyClient | null = null;
@@ -210,8 +214,16 @@ export async function analyzeComment(
210
214
  megacallOptions.tolerances = tolerances;
211
215
  }
212
216
 
213
- const result = await respectifyClient.megacall(megacallOptions);
217
+ // A revised resubmission carries the token its previous analysis returned
218
+ if (options.revisionToken !== undefined) {
219
+ megacallOptions.revisionToken = options.revisionToken;
220
+ }
221
+
222
+ const { result, revisionToken } = await respectifyClient.megacallWithMeta(megacallOptions);
214
223
  const showFeedback = config.moderation.showFeedbackToUser !== false;
224
+ // Free-plan accounts get a token to send back with a revision; paid accounts get none
225
+ const tokenField: Pick<RespectifyAnalysisResult, 'revisionToken'> =
226
+ revisionToken === undefined ? {} : { revisionToken };
215
227
 
216
228
  if (result.spam_check?.is_spam) {
217
229
  return {
@@ -221,6 +233,7 @@ export async function analyzeComment(
221
233
  isSpam: true,
222
234
  suspectedSpam: false,
223
235
  spamConfidence: result.spam_check.confidence,
236
+ ...tokenField,
224
237
  };
225
238
  }
226
239
 
@@ -246,6 +259,7 @@ export async function analyzeComment(
246
259
  feedback: config.feedback.offTopic ?? 'This comment appears to be off-topic.',
247
260
  suggestion: showFeedback ? on_topic.reasoning || banned_topics.reasoning : undefined,
248
261
  ...spamFields,
262
+ ...tokenField,
249
263
  };
250
264
  }
251
265
  }
@@ -258,6 +272,7 @@ export async function analyzeComment(
258
272
  feedback: config.feedback.dogwhistle ?? 'This comment was blocked due to policy violations.',
259
273
  suggestion: showFeedback ? result.dogwhistle_check.detection.reasoning : undefined,
260
274
  ...spamFields,
275
+ ...tokenField,
261
276
  };
262
277
  }
263
278
 
@@ -279,6 +294,7 @@ export async function analyzeComment(
279
294
  approved,
280
295
  feedback,
281
296
  ...spamFields,
297
+ ...tokenField,
282
298
  };
283
299
  if (exceedsTolerance !== undefined) analysisResult.exceedsTolerance = exceedsTolerance;
284
300
  if (result.comment_score?.health_score !== undefined) analysisResult.healthScore = result.comment_score.health_score;
@@ -289,10 +305,31 @@ export async function analyzeComment(
289
305
 
290
306
  return analysisResult;
291
307
  } catch (error) {
308
+ if (error instanceof FreeAllowanceExhaustedError) {
309
+ return publishUnmoderated(config, error, postSlug);
310
+ }
311
+
312
+ if (error instanceof RevisionLimitReachedError) {
313
+ // The comment cannot be revised again through the API: a person decides instead
314
+ logger.info('Respectify revision limit reached; holding the comment for review', { postSlug });
315
+ return {
316
+ score: 0,
317
+ approved: false,
318
+ heldForReview: true,
319
+ feedback: HELD_FOR_REVIEW_MESSAGE,
320
+ };
321
+ }
322
+
292
323
  if (error instanceof AuthenticationError) {
293
324
  logger.error('Respectify authentication failed', { error });
294
325
  } else if (error instanceof PaymentRequiredError) {
295
326
  logger.error('Respectify subscription required', { error });
327
+ } else if (error instanceof RateLimitedError) {
328
+ logger.error('Respectify rate limit reached', {
329
+ errorCode: error.errorCode,
330
+ retryAfterSeconds: error.retryAfterSeconds,
331
+ message: error.message,
332
+ });
296
333
  } else if (error instanceof RespectifyError) {
297
334
  logger.error('Respectify API error', { statusCode: error.statusCode, message: error.message });
298
335
  } else {
@@ -306,3 +343,41 @@ export async function analyzeComment(
306
343
  };
307
344
  }
308
345
  }
346
+
347
+ /**
348
+ * The account's free plan is used up, so Respectify no longer assesses comments. The comment
349
+ * is approved as it is (the commenter sees the ordinary approval), and the site owner is told
350
+ * through the log and the runtime's `onModerationStopped`.
351
+ */
352
+ async function publishUnmoderated(
353
+ config: RespectifyConfig,
354
+ error: FreeAllowanceExhaustedError,
355
+ postSlug: string | undefined,
356
+ ): Promise<RespectifyAnalysisResult> {
357
+ logger.error('Respectify moderation stopped: the free plan is used up. Comments are being published unmoderated.', {
358
+ upgradeUrl: error.upgradeUrl,
359
+ message: error.message,
360
+ postSlug,
361
+ });
362
+
363
+ const { onModerationStopped } = getRespectifyRuntime();
364
+ if (onModerationStopped) {
365
+ try {
366
+ await onModerationStopped({
367
+ reason: 'free_allowance_exhausted',
368
+ upgradeUrl: error.upgradeUrl,
369
+ message: error.message,
370
+ postSlug,
371
+ });
372
+ } catch (callbackError) {
373
+ logger.error('onModerationStopped failed', { error: callbackError });
374
+ }
375
+ }
376
+
377
+ return {
378
+ score: config.thresholds.autoApprove,
379
+ approved: true,
380
+ feedback: config.feedback.approved,
381
+ moderationSkipped: { reason: 'free_allowance_exhausted', upgradeUrl: error.upgradeUrl },
382
+ };
383
+ }
package/src/runtime.ts CHANGED
@@ -24,5 +24,7 @@ export function getRespectifyRuntime(): ResolvedRespectifyRuntime {
24
24
  store: runtime.store,
25
25
  getPostUrl: runtime.getPostUrl ?? defaultGetPostUrl,
26
26
  getPostContent: runtime.getPostContent,
27
+ onModerationStopped: runtime.onModerationStopped,
28
+ onHeldForReview: runtime.onHeldForReview,
27
29
  };
28
30
  }
package/src/types.ts CHANGED
@@ -4,7 +4,7 @@ import type {
4
4
  ModerationTolerances,
5
5
  RespectifyClientOptions,
6
6
  } from '@respectify/client';
7
- import type { ICommentStore } from './store/types';
7
+ import type { CommentRecord, ICommentStore } from './store/types';
8
8
 
9
9
  /**
10
10
  * Options forwarded to `RespectifyClient`.
@@ -106,11 +106,63 @@ export interface RespectifyRuntime {
106
106
  * `getPostUrl` for topic initialization when provided.
107
107
  */
108
108
  getPostContent?: (slug: string) => string | Promise<string>;
109
+
110
+ /**
111
+ * Called when Respectify stops moderating because the account's free plan is used up.
112
+ * From then on comments are published unmoderated, so tell yourself: email, Slack, a
113
+ * dashboard flag. Called once per affected comment. Commenters are never told. The event
114
+ * is also logged at error level whether or not this is set.
115
+ */
116
+ onModerationStopped?: (event: ModerationStoppedEvent) => void | Promise<void>;
117
+
118
+ /**
119
+ * Called when a comment is stored for you to review instead of being published or
120
+ * rejected: on the free plan, a comment that has used all five of its attempts. The
121
+ * comment is in your store with `approved: false`; set `approved` to true to publish it,
122
+ * or delete it.
123
+ */
124
+ onHeldForReview?: (event: HeldForReviewEvent) => void | Promise<void>;
125
+ }
126
+
127
+ /** Why moderation stopped. Only the free plan can run out today. */
128
+ export type ModerationStoppedReason = 'free_allowance_exhausted';
129
+
130
+ /** What `onModerationStopped` receives. */
131
+ export interface ModerationStoppedEvent {
132
+ reason: ModerationStoppedReason;
133
+ /** Where to add credit so moderation resumes */
134
+ upgradeUrl: string;
135
+ /** The API's own message, which already names the upgrade URL */
136
+ message: string;
137
+ /** The post the unmoderated comment was published on */
138
+ postSlug: string | undefined;
139
+ }
140
+
141
+ /** Why a comment was held rather than published or rejected. */
142
+ export type HeldForReviewReason = 'revision_limit_reached';
143
+
144
+ /** What `onHeldForReview` receives. */
145
+ export interface HeldForReviewEvent {
146
+ reason: HeldForReviewReason;
147
+ /** The stored comment, with `approved: false` */
148
+ comment: CommentRecord;
109
149
  }
110
150
 
111
151
  export interface AnalyzeCommentOptions {
112
152
  /** Parent comment text when submitting a reply */
113
153
  replyToComment?: string;
154
+ /**
155
+ * The revision token the previous analysis of this same comment returned, when the
156
+ * commenter is resubmitting a revised version (see `RespectifyAnalysisResult.revisionToken`).
157
+ */
158
+ revisionToken?: string;
159
+ }
160
+
161
+ /** Moderation did not run on this comment; it was published as it was. */
162
+ export interface ModerationSkipped {
163
+ reason: ModerationStoppedReason;
164
+ /** Where to add credit so moderation resumes */
165
+ upgradeUrl: string;
114
166
  }
115
167
 
116
168
  export interface RespectifyAnalysisResult {
@@ -118,6 +170,23 @@ export interface RespectifyAnalysisResult {
118
170
  approved: boolean;
119
171
  feedback: string;
120
172
  suggestion?: string;
173
+ /**
174
+ * Set when the comment went through unmoderated because the account's free plan is used
175
+ * up. `approved` is true: publish it as it is, and tell the site owner, never the commenter.
176
+ */
177
+ moderationSkipped?: ModerationSkipped;
178
+ /**
179
+ * True when the comment should be stored unpublished for the site owner to review, rather
180
+ * than rejected: on the free plan, when it has used all five of its attempts. `approved`
181
+ * is false.
182
+ */
183
+ heldForReview?: boolean;
184
+ /**
185
+ * On the free plan, the token to send back (as `AnalyzeCommentOptions.revisionToken`) if the
186
+ * commenter revises this comment, so the revision is not counted as a new comment. Absent
187
+ * for paid accounts.
188
+ */
189
+ revisionToken?: string;
121
190
  /** True when the comment is spam: it is rejected */
122
191
  isSpam?: boolean;
123
192
  spamConfidence?: number;