@respectify/astro 0.1.9 → 1.0.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 +213 -69
- package/client/comments.ts +2 -0
- package/default-respectify.config.json +1 -0
- package/drizzle/postgres.config.ts +8 -0
- package/drizzle/sqlite.config.ts +8 -0
- package/migrations/postgres/0000_respectify_comment.sql +14 -0
- package/migrations/postgres/meta/0000_snapshot.json +144 -0
- package/migrations/postgres/meta/_journal.json +13 -0
- package/migrations/sqlite/0000_respectify_comment.sql +13 -0
- package/migrations/sqlite/meta/0000_snapshot.json +101 -0
- package/migrations/sqlite/meta/_journal.json +13 -0
- package/package.json +35 -13
- package/respectify.config.sample.jsonc +47 -5
- package/src/actions.ts +133 -75
- package/src/adapters/postgres/index.ts +7 -0
- package/src/adapters/postgres/store.ts +83 -0
- package/src/adapters/postgres/table.ts +37 -0
- package/src/adapters/sqlite/index.ts +8 -0
- package/src/adapters/sqlite/store.ts +91 -0
- package/src/adapters/sqlite/table.ts +41 -0
- package/src/adapters/sqlite/text-date.ts +37 -0
- package/src/env.d.ts +11 -12
- package/src/index.ts +91 -7
- package/src/lib/config.ts +60 -0
- package/src/lib/service.ts +74 -23
- package/src/options.ts +135 -0
- package/src/routes/comments.ts +31 -33
- package/src/runtime-config.ts +9 -33
- package/src/runtime.ts +28 -0
- package/src/store/limits.ts +11 -0
- package/src/store/schemas.ts +41 -0
- package/src/store/types.ts +52 -0
- package/src/testing/comment-store-contract.ts +197 -0
- package/src/testing/index.ts +1 -0
- package/src/types.ts +87 -17
- package/src/schema.ts +0 -25
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { and, asc, eq } from 'drizzle-orm';
|
|
2
|
+
import type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
|
3
|
+
import { commentIdSchema, parseNewComment } from '../../store/schemas';
|
|
4
|
+
import type { CommentRecord, ICommentStore, NewComment, PublicComment } from '../../store/types';
|
|
5
|
+
import { respectifyComments, type SqliteCommentTable } from './table';
|
|
6
|
+
|
|
7
|
+
export interface SqliteCommentStoreOptions {
|
|
8
|
+
/** The comment table, when it is not the default `Comment` (see `createSqliteCommentTable`) */
|
|
9
|
+
table?: SqliteCommentTable;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A comment store on any Drizzle SQLite database: libSQL/Turso, better-sqlite3, Cloudflare D1 and others. */
|
|
13
|
+
class SqliteCommentStore<
|
|
14
|
+
TResultKind extends 'sync' | 'async',
|
|
15
|
+
TRunResult,
|
|
16
|
+
TSchema extends Record<string, unknown>,
|
|
17
|
+
> implements ICommentStore
|
|
18
|
+
{
|
|
19
|
+
// Widened from the constructor's generic kinds: Drizzle cannot type a select chain on an unresolved result kind
|
|
20
|
+
readonly #db: BaseSQLiteDatabase<'sync' | 'async', TRunResult, TSchema>;
|
|
21
|
+
readonly #table: SqliteCommentTable;
|
|
22
|
+
|
|
23
|
+
constructor(db: BaseSQLiteDatabase<TResultKind, TRunResult, TSchema>, table: SqliteCommentTable) {
|
|
24
|
+
this.#db = db;
|
|
25
|
+
this.#table = table;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async findById(id: number): Promise<CommentRecord | undefined> {
|
|
29
|
+
if (!commentIdSchema.safeParse(id).success) return undefined;
|
|
30
|
+
const [row] = await this.#db.select().from(this.#table).where(eq(this.#table.id, id)).limit(1);
|
|
31
|
+
return row;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async listApproved(postSlug: string): Promise<PublicComment[]> {
|
|
35
|
+
const table = this.#table;
|
|
36
|
+
return this.#db
|
|
37
|
+
.select({
|
|
38
|
+
id: table.id,
|
|
39
|
+
author: table.author,
|
|
40
|
+
content: table.content,
|
|
41
|
+
createdAt: table.createdAt,
|
|
42
|
+
parentId: table.parentId,
|
|
43
|
+
})
|
|
44
|
+
.from(table)
|
|
45
|
+
.where(and(eq(table.postSlug, postSlug), eq(table.approved, true)))
|
|
46
|
+
.orderBy(asc(table.createdAt), asc(table.id));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async create(input: NewComment): Promise<CommentRecord> {
|
|
50
|
+
const comment = parseNewComment(input);
|
|
51
|
+
const [row] = await this.#db
|
|
52
|
+
.insert(this.#table)
|
|
53
|
+
.values({
|
|
54
|
+
postSlug: comment.postSlug,
|
|
55
|
+
author: comment.author,
|
|
56
|
+
email: comment.email ?? null,
|
|
57
|
+
content: comment.content,
|
|
58
|
+
approved: comment.approved,
|
|
59
|
+
parentId: comment.parentId ?? null,
|
|
60
|
+
})
|
|
61
|
+
.returning();
|
|
62
|
+
if (!row) {
|
|
63
|
+
throw new Error('The comment was not stored: the database returned no row');
|
|
64
|
+
}
|
|
65
|
+
return row;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async delete(id: number): Promise<boolean> {
|
|
69
|
+
if (!commentIdSchema.safeParse(id).success) return false;
|
|
70
|
+
const table = this.#table;
|
|
71
|
+
const deleted = await this.#db.delete(table).where(eq(table.id, id)).returning({ id: table.id });
|
|
72
|
+
if (deleted.length === 0) return false;
|
|
73
|
+
// No foreign key does this (the Astro DB table has none), so the replies are detached here
|
|
74
|
+
await this.#db.update(table).set({ parentId: null }).where(eq(table.parentId, id));
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Store comments in SQLite through your own Drizzle database instance, so the integration
|
|
81
|
+
* uses your connection and never opens one. The table must already exist: an Astro DB
|
|
82
|
+
* `Comment` table works as it is; otherwise add `respectifyComments` (or a table from
|
|
83
|
+
* `createSqliteCommentTable`) to your Drizzle schema and migrate with drizzle-kit.
|
|
84
|
+
*/
|
|
85
|
+
export function createSqliteCommentStore<
|
|
86
|
+
TResultKind extends 'sync' | 'async',
|
|
87
|
+
TRunResult,
|
|
88
|
+
TSchema extends Record<string, unknown>,
|
|
89
|
+
>(db: BaseSQLiteDatabase<TResultKind, TRunResult, TSchema>, options: SqliteCommentStoreOptions = {}): ICommentStore {
|
|
90
|
+
return new SqliteCommentStore(db, options.table ?? respectifyComments);
|
|
91
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { sql } from 'drizzle-orm';
|
|
2
|
+
import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
|
|
3
|
+
import { textDate } from './text-date';
|
|
4
|
+
|
|
5
|
+
/** The default SQLite table name: the `Comment` table `@respectify/astro` 0.x created through Astro DB. */
|
|
6
|
+
export const DEFAULT_SQLITE_COMMENT_TABLE_NAME = 'Comment';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Build the Drizzle definition of the comment table, named `name`. Its columns, defaults and
|
|
10
|
+
* index names match the table `@respectify/astro` 0.x defined through Astro DB, so an existing
|
|
11
|
+
* Astro DB (libSQL/Turso) database is used as it is. For a new database, put the result in
|
|
12
|
+
* your Drizzle schema and migrate with drizzle-kit; the store never creates it.
|
|
13
|
+
*
|
|
14
|
+
* Like the Astro DB table it has no foreign key on `parentId`; the store clears a deleted
|
|
15
|
+
* comment's replies' `parentId` itself.
|
|
16
|
+
*/
|
|
17
|
+
export function createSqliteCommentTable(name: string = DEFAULT_SQLITE_COMMENT_TABLE_NAME) {
|
|
18
|
+
return sqliteTable(
|
|
19
|
+
name,
|
|
20
|
+
{
|
|
21
|
+
id: integer('id').primaryKey(),
|
|
22
|
+
postSlug: text('postSlug').notNull(),
|
|
23
|
+
author: text('author').notNull(),
|
|
24
|
+
email: text('email'),
|
|
25
|
+
content: text('content').notNull(),
|
|
26
|
+
createdAt: textDate('createdAt').notNull().default(sql`CURRENT_TIMESTAMP`),
|
|
27
|
+
approved: integer('approved', { mode: 'boolean' }).notNull().default(false),
|
|
28
|
+
parentId: integer('parentId'),
|
|
29
|
+
},
|
|
30
|
+
(columns) => [
|
|
31
|
+
index(`${name}_postSlug_idx`).on(columns.postSlug),
|
|
32
|
+
index(`${name}_approved_idx`).on(columns.approved),
|
|
33
|
+
],
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The Drizzle type of a Respectify comment table on SQLite. */
|
|
38
|
+
export type SqliteCommentTable = ReturnType<typeof createSqliteCommentTable>;
|
|
39
|
+
|
|
40
|
+
/** The comment table under its default name, ready to export from your Drizzle schema. */
|
|
41
|
+
export const respectifyComments: SqliteCommentTable = createSqliteCommentTable();
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { customType } from 'drizzle-orm/sqlite-core';
|
|
2
|
+
|
|
3
|
+
/** `YYYY-MM-DD HH:MM:SS[.fff]`, the UTC form SQLite's CURRENT_TIMESTAMP writes */
|
|
4
|
+
const SQLITE_TIMESTAMP = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?$/;
|
|
5
|
+
|
|
6
|
+
/** Ends in `Z` or a `±HH:MM` offset */
|
|
7
|
+
const HAS_TIME_ZONE = /(Z|[+-]\d{2}:?\d{2})$/;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Read a stored date. Both forms Astro DB wrote are UTC: ISO 8601 (from a Date it was given)
|
|
11
|
+
* and SQLite's `YYYY-MM-DD HH:MM:SS` (from its CURRENT_TIMESTAMP default).
|
|
12
|
+
* @throws Error when the text is not a date
|
|
13
|
+
*/
|
|
14
|
+
export function parseStoredDate(value: string): Date {
|
|
15
|
+
const iso = SQLITE_TIMESTAMP.test(value) ? `${value.replace(' ', 'T')}Z` : value;
|
|
16
|
+
const date = new Date(HAS_TIME_ZONE.test(iso) ? iso : `${iso}Z`);
|
|
17
|
+
if (Number.isNaN(date.getTime())) {
|
|
18
|
+
throw new Error(`Stored comment date is not a date: ${JSON.stringify(value)}`);
|
|
19
|
+
}
|
|
20
|
+
return date;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A date kept as text, the way Astro DB's `column.date()` keeps it, so a table Astro DB
|
|
25
|
+
* created is read and written unchanged.
|
|
26
|
+
*/
|
|
27
|
+
export const textDate = customType<{ data: Date; driverData: string }>({
|
|
28
|
+
dataType() {
|
|
29
|
+
return 'text';
|
|
30
|
+
},
|
|
31
|
+
toDriver(value: Date): string {
|
|
32
|
+
return value.toISOString();
|
|
33
|
+
},
|
|
34
|
+
fromDriver(value: string): Date {
|
|
35
|
+
return parseStoredDate(value);
|
|
36
|
+
},
|
|
37
|
+
});
|
package/src/env.d.ts
CHANGED
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
/// <reference types="astro/client" />
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
namespace App {
|
|
7
|
-
interface Locals {
|
|
8
|
-
isAuthenticated?: boolean;
|
|
9
|
-
}
|
|
3
|
+
declare namespace App {
|
|
4
|
+
interface Locals {
|
|
5
|
+
isAuthenticated?: boolean;
|
|
10
6
|
}
|
|
11
7
|
}
|
|
12
8
|
|
|
@@ -15,9 +11,12 @@ declare module 'astro:env/server' {
|
|
|
15
11
|
export const RESPECTIFY_API_KEY: string | undefined;
|
|
16
12
|
}
|
|
17
13
|
|
|
18
|
-
declare module 'astro
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
14
|
+
declare module 'virtual:@respectify/astro/options' {
|
|
15
|
+
const options: import('./types').ResolvedIntegrationOptions;
|
|
16
|
+
export default options;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
declare module 'virtual:@respectify/astro/runtime' {
|
|
20
|
+
const runtime: import('./types').RespectifyRuntime;
|
|
21
|
+
export default runtime;
|
|
23
22
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,18 +1,69 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import path from 'node:path';
|
|
1
3
|
import type { AstroIntegration } from 'astro';
|
|
2
4
|
import { envField } from 'astro/config';
|
|
3
|
-
import {
|
|
4
|
-
import type { RespectifyIntegrationOptions } from './types';
|
|
5
|
+
import { parseIntegrationOptions, toResolvedIntegrationOptions } from './options';
|
|
6
|
+
import type { RespectifyIntegrationOptions, RespectifyRuntime } from './types';
|
|
5
7
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
+
const OPTIONS_MODULE_ID = 'virtual:@respectify/astro/options';
|
|
9
|
+
const RUNTIME_MODULE_ID = 'virtual:@respectify/astro/runtime';
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
+
/** A Vite plugin serving virtual modules, in the shape `vite.plugins` accepts. */
|
|
12
|
+
interface VirtualModulesPlugin {
|
|
13
|
+
name: string;
|
|
14
|
+
resolveId: (id: string) => string | undefined;
|
|
15
|
+
load: (id: string) => string | undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Declarations for the virtual modules, injected into the site's generated types. */
|
|
19
|
+
const VIRTUAL_MODULE_TYPES = `declare module '${OPTIONS_MODULE_ID}' {
|
|
20
|
+
const options: import('@respectify/astro').ResolvedIntegrationOptions;
|
|
21
|
+
export default options;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
declare module '${RUNTIME_MODULE_ID}' {
|
|
25
|
+
const runtime: import('@respectify/astro').RespectifyRuntime;
|
|
26
|
+
export default runtime;
|
|
27
|
+
}
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Where Vite should load the runtime module from. A relative path is resolved against the
|
|
32
|
+
* project root; an absolute path or a package specifier is left as given.
|
|
33
|
+
*/
|
|
34
|
+
function resolveRuntimeSpecifier(runtime: string, root: URL): string {
|
|
35
|
+
if (runtime.startsWith('./') || runtime.startsWith('../')) {
|
|
36
|
+
return fileURLToPath(new URL(runtime, root));
|
|
37
|
+
}
|
|
38
|
+
return path.isAbsolute(runtime) ? path.normalize(runtime) : runtime;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Serve each virtual module's source, keyed by its public id, using Vite's `\0` resolved-id convention. */
|
|
42
|
+
function createVirtualModulesPlugin(modules: Record<string, string>): VirtualModulesPlugin {
|
|
43
|
+
const sources = new Map(Object.entries(modules).map(([id, source]) => [`\0${id}`, source]));
|
|
44
|
+
return {
|
|
45
|
+
name: '@respectify/astro:virtual-modules',
|
|
46
|
+
resolveId: (id) => (sources.has(`\0${id}`) ? `\0${id}` : undefined),
|
|
47
|
+
load: (id) => sources.get(id),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The Respectify comments integration. Its options are serialized into the server bundle,
|
|
53
|
+
* so they must be plain data; the comment store and post functions live in the module
|
|
54
|
+
* named by `runtime`.
|
|
55
|
+
*/
|
|
56
|
+
export default function respectify(userOptions: RespectifyIntegrationOptions): AstroIntegration {
|
|
57
|
+
const parsed = parseIntegrationOptions(userOptions);
|
|
58
|
+
const resolvedOptions = toResolvedIntegrationOptions(parsed);
|
|
59
|
+
const routePattern = resolvedOptions.commentsApiPath.replace(/^\//, '');
|
|
11
60
|
|
|
12
61
|
return {
|
|
13
62
|
name: '@respectify/astro',
|
|
14
63
|
hooks: {
|
|
15
|
-
'astro:config:setup': ({ injectRoute, updateConfig }) => {
|
|
64
|
+
'astro:config:setup': ({ config, injectRoute, updateConfig }) => {
|
|
65
|
+
const runtimeSpecifier = resolveRuntimeSpecifier(parsed.runtime, config.root);
|
|
66
|
+
|
|
16
67
|
updateConfig({
|
|
17
68
|
env: {
|
|
18
69
|
schema: {
|
|
@@ -20,6 +71,14 @@ export default function respectify(userOptions: RespectifyIntegrationOptions = {
|
|
|
20
71
|
RESPECTIFY_API_KEY: envField.string({ context: 'server', access: 'secret', optional: true }),
|
|
21
72
|
},
|
|
22
73
|
},
|
|
74
|
+
vite: {
|
|
75
|
+
plugins: [
|
|
76
|
+
createVirtualModulesPlugin({
|
|
77
|
+
[OPTIONS_MODULE_ID]: `export default ${JSON.stringify(resolvedOptions)};`,
|
|
78
|
+
[RUNTIME_MODULE_ID]: `export { default } from ${JSON.stringify(runtimeSpecifier)};`,
|
|
79
|
+
}),
|
|
80
|
+
],
|
|
81
|
+
},
|
|
23
82
|
});
|
|
24
83
|
|
|
25
84
|
injectRoute({
|
|
@@ -27,14 +86,39 @@ export default function respectify(userOptions: RespectifyIntegrationOptions = {
|
|
|
27
86
|
entrypoint: '@respectify/astro/routes/comments',
|
|
28
87
|
});
|
|
29
88
|
},
|
|
89
|
+
'astro:config:done': ({ injectTypes }) => {
|
|
90
|
+
injectTypes({ filename: 'virtual-modules.d.ts', content: VIRTUAL_MODULE_TYPES });
|
|
91
|
+
},
|
|
30
92
|
},
|
|
31
93
|
};
|
|
32
94
|
}
|
|
33
95
|
|
|
96
|
+
/**
|
|
97
|
+
* Define the runtime module named by `respectify({ runtime })`. Its default export must be
|
|
98
|
+
* the value this returns:
|
|
99
|
+
*
|
|
100
|
+
* ```ts
|
|
101
|
+
* // src/respectify.runtime.ts
|
|
102
|
+
* import { defineRespectifyRuntime } from '@respectify/astro';
|
|
103
|
+
* import { createSqliteCommentStore } from '@respectify/astro/sqlite';
|
|
104
|
+
*
|
|
105
|
+
* export default defineRespectifyRuntime({ store: createSqliteCommentStore(db) });
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
export function defineRespectifyRuntime(runtime: RespectifyRuntime): RespectifyRuntime {
|
|
109
|
+
return runtime;
|
|
110
|
+
}
|
|
111
|
+
|
|
34
112
|
export type {
|
|
35
113
|
RespectifyIntegrationOptions,
|
|
114
|
+
RespectifyIntegrationClientConfig,
|
|
115
|
+
ResolvedIntegrationOptions,
|
|
116
|
+
RespectifyRuntime,
|
|
36
117
|
RespectifyAnalysisResult,
|
|
37
118
|
RespectifyClientConfig,
|
|
38
119
|
RespectifyMegacallConfig,
|
|
39
120
|
AnalyzeCommentOptions,
|
|
40
121
|
} from './types';
|
|
122
|
+
export type { ICommentStore, CommentRecord, NewComment, PublicComment } from './store/types';
|
|
123
|
+
export { CommentValidationError, newCommentSchema } from './store/schemas';
|
|
124
|
+
export { COMMENT_LIMITS } from './store/limits';
|
package/src/lib/config.ts
CHANGED
|
@@ -1,9 +1,57 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { TOLERANCE_LEVELS } from '@respectify/client';
|
|
5
|
+
import type {
|
|
6
|
+
FlooredModerationCategory,
|
|
7
|
+
FlooredToleranceLevel,
|
|
8
|
+
ModerationTolerances,
|
|
9
|
+
ToleranceLevel,
|
|
10
|
+
} from '@respectify/client';
|
|
4
11
|
import { getIntegrationOptions } from '../runtime-config';
|
|
5
12
|
import type { RespectifyClientConfig, RespectifyMegacallConfig } from '../types';
|
|
6
13
|
|
|
14
|
+
/** Levels a floored category accepts: standard or stricter, never permissive, relaxed or off. */
|
|
15
|
+
const FLOORED_TOLERANCE_LEVELS = ['standard', 'strict', 'zero_tolerance'] as const satisfies readonly FlooredToleranceLevel[];
|
|
16
|
+
|
|
17
|
+
const ToleranceLevelSchema = z.enum(TOLERANCE_LEVELS);
|
|
18
|
+
|
|
19
|
+
/** Levels looser than a floored category allows, which get the API's floor wording rather than the default error. */
|
|
20
|
+
const BELOW_FLOOR_TOLERANCE_LEVELS: readonly ToleranceLevel[] = ['off', 'permissive', 'relaxed'];
|
|
21
|
+
|
|
22
|
+
/** A floored category's level, rejecting "permissive", "relaxed" and "off" with the same wording the API uses. */
|
|
23
|
+
function flooredToleranceLevelSchema(
|
|
24
|
+
category: FlooredModerationCategory,
|
|
25
|
+
): z.ZodEnum<z.Writeable<typeof FLOORED_TOLERANCE_LEVELS>> {
|
|
26
|
+
return z.enum(FLOORED_TOLERANCE_LEVELS, {
|
|
27
|
+
errorMap: (_issue, ctx) => ({
|
|
28
|
+
message:
|
|
29
|
+
BELOW_FLOOR_TOLERANCE_LEVELS.includes(ctx.data)
|
|
30
|
+
? `${category} can be made stricter but not relaxed or turned off`
|
|
31
|
+
: ctx.defaultError,
|
|
32
|
+
}),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Per-site tolerances: a level per comment-health item (the nine problem categories and
|
|
38
|
+
* quality). Items not named are "standard". Unknown items are rejected.
|
|
39
|
+
*/
|
|
40
|
+
const ModerationTolerancesSchema = z
|
|
41
|
+
.object({
|
|
42
|
+
threat: flooredToleranceLevelSchema('threat').optional(),
|
|
43
|
+
identity_attack: flooredToleranceLevelSchema('identity_attack').optional(),
|
|
44
|
+
sexual_content: flooredToleranceLevelSchema('sexual_content').optional(),
|
|
45
|
+
harassment: flooredToleranceLevelSchema('harassment').optional(),
|
|
46
|
+
insult: ToleranceLevelSchema.optional(),
|
|
47
|
+
profanity: ToleranceLevelSchema.optional(),
|
|
48
|
+
dismissive_tone: ToleranceLevelSchema.optional(),
|
|
49
|
+
logical_fallacy: ToleranceLevelSchema.optional(),
|
|
50
|
+
low_effort: ToleranceLevelSchema.optional(),
|
|
51
|
+
quality: ToleranceLevelSchema.optional(),
|
|
52
|
+
})
|
|
53
|
+
.strict() satisfies z.ZodType<ModerationTolerances>;
|
|
54
|
+
|
|
7
55
|
const MegacallConfigSchema = z
|
|
8
56
|
.object({
|
|
9
57
|
includeSpam: z.boolean().optional(),
|
|
@@ -64,6 +112,8 @@ const RespectifyConfigSchema = z.object({
|
|
|
64
112
|
client: ClientConfigSchema,
|
|
65
113
|
/** Options forwarded to megacall (merged with integration `megacall` options) */
|
|
66
114
|
megacall: MegacallConfigSchema,
|
|
115
|
+
/** Moderation tolerances sent with every megacall (merged with integration `tolerances`) */
|
|
116
|
+
tolerances: ModerationTolerancesSchema.optional(),
|
|
67
117
|
});
|
|
68
118
|
|
|
69
119
|
export type RespectifyConfig = z.infer<typeof RespectifyConfigSchema>;
|
|
@@ -110,6 +160,16 @@ export function resolveMegacallConfig(config: RespectifyConfig): RespectifyMegac
|
|
|
110
160
|
};
|
|
111
161
|
}
|
|
112
162
|
|
|
163
|
+
/**
|
|
164
|
+
* Merge JSON + integration tolerances per item. Integration options win.
|
|
165
|
+
* Undefined when neither names an item, so every item is judged at "standard".
|
|
166
|
+
*/
|
|
167
|
+
export function resolveTolerances(config: RespectifyConfig): ModerationTolerances | undefined {
|
|
168
|
+
const { tolerances: integrationTolerances } = getIntegrationOptions();
|
|
169
|
+
const merged: ModerationTolerances = { ...config.tolerances, ...integrationTolerances };
|
|
170
|
+
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
113
173
|
export function getDefaultConfig(): RespectifyConfig {
|
|
114
174
|
return {
|
|
115
175
|
enabled: true,
|
package/src/lib/service.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RespectifyConfig } from './config';
|
|
2
|
-
import { loadRespectifyConfig, resolveClientConfig, resolveMegacallConfig } from './config';
|
|
2
|
+
import { loadRespectifyConfig, resolveClientConfig, resolveMegacallConfig, resolveTolerances } from './config';
|
|
3
3
|
import { RESPECTIFY_API_KEY, RESPECTIFY_EMAIL } from 'astro:env/server';
|
|
4
4
|
import {
|
|
5
5
|
RespectifyClient,
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
type MegacallOptions,
|
|
10
10
|
type MegaCallResult,
|
|
11
11
|
} from '@respectify/client';
|
|
12
|
-
import {
|
|
12
|
+
import { getRespectifyRuntime } from '../runtime';
|
|
13
13
|
import { logger } from './logger';
|
|
14
14
|
import type { AnalyzeCommentOptions, RespectifyAnalysisResult } from '../types';
|
|
15
15
|
|
|
@@ -54,7 +54,7 @@ async function getOrInitializeArticleId(postSlug: string, config: RespectifyConf
|
|
|
54
54
|
const cached = articleIdCache.get(postSlug);
|
|
55
55
|
if (cached) return cached;
|
|
56
56
|
|
|
57
|
-
const { getPostUrl, getPostContent } =
|
|
57
|
+
const { getPostUrl, getPostContent } = getRespectifyRuntime();
|
|
58
58
|
const respectifyClient = getRespectifyClient(config);
|
|
59
59
|
const topicDescription = `Post: ${postSlug}`;
|
|
60
60
|
|
|
@@ -65,7 +65,7 @@ async function getOrInitializeArticleId(postSlug: string, config: RespectifyConf
|
|
|
65
65
|
if (!site) {
|
|
66
66
|
throw new Error('import.meta.env.SITE must be set in astro.config.ts for Respectify topic initialization.');
|
|
67
67
|
}
|
|
68
|
-
return respectifyClient.initTopicFromUrl(getPostUrl
|
|
68
|
+
return respectifyClient.initTopicFromUrl(getPostUrl(postSlug, site), topicDescription);
|
|
69
69
|
})());
|
|
70
70
|
|
|
71
71
|
articleIdCache.set(postSlug, result.article_id);
|
|
@@ -86,6 +86,10 @@ export async function verifyRespectifyCredentials(): Promise<boolean> {
|
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/** Shown for suspected spam when an API sends no suggestion. */
|
|
90
|
+
const DEFAULT_SUSPECTED_SPAM_SUGGESTION =
|
|
91
|
+
'This looks like spam. Please revise it and say what you think about the discussion.';
|
|
92
|
+
|
|
89
93
|
function buildSuggestion(result: MegaCallResult, showFeedback: boolean): string | undefined {
|
|
90
94
|
if (!showFeedback || !result.comment_score) return undefined;
|
|
91
95
|
|
|
@@ -116,6 +120,37 @@ function buildSuggestion(result: MegaCallResult, showFeedback: boolean): string
|
|
|
116
120
|
return suggestions.length > 0 ? suggestions.join(' ') : undefined;
|
|
117
121
|
}
|
|
118
122
|
|
|
123
|
+
/**
|
|
124
|
+
* Approve, warn or block on the comment's content.
|
|
125
|
+
*
|
|
126
|
+
* With a comment score, `exceeds_tolerance` decides whether there is a problem at all:
|
|
127
|
+
* - false: approved, whatever the toxicity (toxicity_score is not adjusted for the site's
|
|
128
|
+
* tolerances, so a comment the site accepts is not held back by it)
|
|
129
|
+
* - true: blocked when respectfulness < thresholds.block and blockDisrespectful is on;
|
|
130
|
+
* otherwise a warning, approved only when allowOverride is on
|
|
131
|
+
*
|
|
132
|
+
* Without exceeds_tolerance the respectfulness bands decide as before: >= autoApprove
|
|
133
|
+
* approves, < block blocks, anything between warns. With no comment score at all the score
|
|
134
|
+
* is autoApprove, so the comment is approved; a comment score lacking exceeds_tolerance
|
|
135
|
+
* (an API older than moderation tolerances) falls back to the bands on 1 - toxicity_score.
|
|
136
|
+
*/
|
|
137
|
+
function decideOnContent(
|
|
138
|
+
config: RespectifyConfig,
|
|
139
|
+
respectfulnessScore: number,
|
|
140
|
+
exceedsTolerance: boolean | undefined,
|
|
141
|
+
): Pick<RespectifyAnalysisResult, 'approved' | 'feedback'> {
|
|
142
|
+
const isWithinTolerance =
|
|
143
|
+
exceedsTolerance === undefined ? respectfulnessScore >= config.thresholds.autoApprove : !exceedsTolerance;
|
|
144
|
+
|
|
145
|
+
if (isWithinTolerance) {
|
|
146
|
+
return { approved: true, feedback: config.feedback.approved };
|
|
147
|
+
}
|
|
148
|
+
if (respectfulnessScore < config.thresholds.block && config.moderation.blockDisrespectful) {
|
|
149
|
+
return { approved: false, feedback: config.feedback.blocked };
|
|
150
|
+
}
|
|
151
|
+
return { approved: config.moderation.allowOverride, feedback: config.feedback.warning };
|
|
152
|
+
}
|
|
153
|
+
|
|
119
154
|
export async function analyzeComment(
|
|
120
155
|
text: string,
|
|
121
156
|
postSlug?: string,
|
|
@@ -169,6 +204,12 @@ export async function analyzeComment(
|
|
|
169
204
|
megacallOptions.replyToComment = options.replyToComment;
|
|
170
205
|
}
|
|
171
206
|
|
|
207
|
+
// Tolerances only shape the comment score, which needs topic context
|
|
208
|
+
const tolerances = resolveTolerances(config);
|
|
209
|
+
if (tolerances && megacallOptions.includeCommentScore) {
|
|
210
|
+
megacallOptions.tolerances = tolerances;
|
|
211
|
+
}
|
|
212
|
+
|
|
172
213
|
const result = await respectifyClient.megacall(megacallOptions);
|
|
173
214
|
const showFeedback = config.moderation.showFeedbackToUser !== false;
|
|
174
215
|
|
|
@@ -178,10 +219,22 @@ export async function analyzeComment(
|
|
|
178
219
|
approved: false,
|
|
179
220
|
feedback: 'This comment appears to be spam.',
|
|
180
221
|
isSpam: true,
|
|
222
|
+
suspectedSpam: false,
|
|
181
223
|
spamConfidence: result.spam_check.confidence,
|
|
182
224
|
};
|
|
183
225
|
}
|
|
184
226
|
|
|
227
|
+
// Suspected spam is not spam: the other checks still run, but the comment is sent back
|
|
228
|
+
// with the server's suggestion. An older API omits suspected_spam, meaning not suspected.
|
|
229
|
+
const spamFields: Pick<RespectifyAnalysisResult, 'isSpam' | 'suspectedSpam' | 'spamSuggestion'> = {};
|
|
230
|
+
if (result.spam_check) {
|
|
231
|
+
spamFields.isSpam = false;
|
|
232
|
+
spamFields.suspectedSpam = result.spam_check.suspected_spam === true;
|
|
233
|
+
if (spamFields.suspectedSpam) {
|
|
234
|
+
spamFields.spamSuggestion = result.spam_check.suggestion || DEFAULT_SUSPECTED_SPAM_SUGGESTION;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
185
238
|
const blockOffTopic = config.moderation.blockOffTopic !== false;
|
|
186
239
|
if (blockOffTopic && result.relevance_check) {
|
|
187
240
|
const { on_topic, banned_topics } = result.relevance_check;
|
|
@@ -192,6 +245,7 @@ export async function analyzeComment(
|
|
|
192
245
|
approved: false,
|
|
193
246
|
feedback: config.feedback.offTopic ?? 'This comment appears to be off-topic.',
|
|
194
247
|
suggestion: showFeedback ? on_topic.reasoning || banned_topics.reasoning : undefined,
|
|
248
|
+
...spamFields,
|
|
195
249
|
};
|
|
196
250
|
}
|
|
197
251
|
}
|
|
@@ -203,35 +257,32 @@ export async function analyzeComment(
|
|
|
203
257
|
approved: false,
|
|
204
258
|
feedback: config.feedback.dogwhistle ?? 'This comment was blocked due to policy violations.',
|
|
205
259
|
suggestion: showFeedback ? result.dogwhistle_check.detection.reasoning : undefined,
|
|
260
|
+
...spamFields,
|
|
206
261
|
};
|
|
207
262
|
}
|
|
208
263
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
264
|
+
// Respectfulness is 1 - toxicity_score. Without a comment score there is nothing to
|
|
265
|
+
// judge content by, so the comment is treated as at the auto-approve threshold.
|
|
266
|
+
const respectfulnessScore = result.comment_score
|
|
267
|
+
? 1 - (result.comment_score.toxicity_score ?? 0)
|
|
268
|
+
: config.thresholds.autoApprove;
|
|
269
|
+
const exceedsTolerance = result.comment_score?.exceeds_tolerance;
|
|
215
270
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
feedback = config.feedback.approved;
|
|
222
|
-
} else if (respectfulnessScore < config.thresholds.block && config.moderation.blockDisrespectful) {
|
|
223
|
-
approved = false;
|
|
224
|
-
feedback = config.feedback.blocked;
|
|
225
|
-
} else {
|
|
226
|
-
approved = config.moderation.allowOverride;
|
|
227
|
-
feedback = config.feedback.warning;
|
|
228
|
-
}
|
|
271
|
+
const contentDecision = decideOnContent(config, respectfulnessScore, exceedsTolerance);
|
|
272
|
+
// Suspected spam always goes back to the commenter, whatever the content decision
|
|
273
|
+
const { approved, feedback } = spamFields.spamSuggestion
|
|
274
|
+
? { approved: false, feedback: spamFields.spamSuggestion }
|
|
275
|
+
: contentDecision;
|
|
229
276
|
|
|
230
277
|
const analysisResult: RespectifyAnalysisResult = {
|
|
231
278
|
score: respectfulnessScore,
|
|
232
279
|
approved,
|
|
233
280
|
feedback,
|
|
281
|
+
...spamFields,
|
|
234
282
|
};
|
|
283
|
+
if (exceedsTolerance !== undefined) analysisResult.exceedsTolerance = exceedsTolerance;
|
|
284
|
+
if (result.comment_score?.health_score !== undefined) analysisResult.healthScore = result.comment_score.health_score;
|
|
285
|
+
if (result.comment_score?.health_items !== undefined) analysisResult.healthItems = result.comment_score.health_items;
|
|
235
286
|
|
|
236
287
|
const suggestion = buildSuggestion(result, showFeedback);
|
|
237
288
|
if (suggestion) analysisResult.suggestion = suggestion;
|