@respectify/astro 0.2.0 → 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.
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": "7",
3
+ "dialect": "sqlite",
4
+ "entries": [
5
+ {
6
+ "idx": 0,
7
+ "version": "6",
8
+ "when": 1792852601633,
9
+ "tag": "0000_respectify_comment",
10
+ "breakpoints": true
11
+ }
12
+ ]
13
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@respectify/astro",
3
- "version": "0.2.0",
4
- "description": "Respectify-powered commenting for Astro — AI moderation, spam filtering, and beautiful UX out of the box.",
3
+ "version": "1.0.0",
4
+ "description": "Respectify-powered commenting for Astro \u2014 AI moderation, spam filtering, and beautiful UX out of the box.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Respectify",
@@ -31,30 +31,46 @@
31
31
  ".": "./src/index.ts",
32
32
  "./actions": "./src/actions.ts",
33
33
  "./credentials": "./src/credentials.ts",
34
- "./schema": "./src/schema.ts",
35
34
  "./routes/comments": "./src/routes/comments.ts",
36
35
  "./components/CommentSection.astro": "./components/CommentSection.astro",
37
36
  "./components/PoweredByRespectify.astro": "./components/PoweredByRespectify.astro",
38
37
  "./client": "./client/comments.ts",
39
- "./styles.css": "./components/respectify-comments.css"
38
+ "./styles.css": "./components/respectify-comments.css",
39
+ "./postgres": "./src/adapters/postgres/index.ts",
40
+ "./sqlite": "./src/adapters/sqlite/index.ts",
41
+ "./testing": "./src/testing/index.ts"
40
42
  },
41
43
  "files": [
42
44
  "src",
43
45
  "components",
44
46
  "client",
47
+ "migrations",
48
+ "drizzle",
45
49
  "default-respectify.config.json",
46
50
  "respectify.config.sample.jsonc",
47
51
  "README.md"
48
52
  ],
49
53
  "peerDependencies": {
50
- "@astrojs/db": "^0.20.0",
54
+ "@libsql/client": ">=0.10.0",
51
55
  "@respectify/client": "^0.7.0",
52
- "astro": "^5.0.0 || ^6.0.0",
56
+ "astro": "^5.0.0 || ^6.0.0 || ^7.0.0",
57
+ "drizzle-orm": "^0.45.0",
58
+ "pg": "^8.0.0",
59
+ "vitest": "^3.0.0",
53
60
  "zod": "^3.0.0"
54
61
  },
55
62
  "peerDependenciesMeta": {
56
- "@astrojs/db": {
57
- "optional": false
63
+ "@libsql/client": {
64
+ "optional": true
65
+ },
66
+ "drizzle-orm": {
67
+ "optional": true
68
+ },
69
+ "pg": {
70
+ "optional": true
71
+ },
72
+ "vitest": {
73
+ "optional": true
58
74
  }
59
75
  },
60
76
  "dependencies": {
@@ -62,12 +78,16 @@
62
78
  },
63
79
  "scripts": {
64
80
  "typecheck": "tsc --noEmit",
65
- "test": "vitest run"
81
+ "test": "vitest run",
82
+ "migrations:generate": "drizzle-kit generate --config drizzle/postgres.config.ts && drizzle-kit generate --config drizzle/sqlite.config.ts"
66
83
  },
67
84
  "devDependencies": {
68
- "@astrojs/db": "^0.20.0",
85
+ "@electric-sql/pglite": "0.5.8",
86
+ "@libsql/client": "^0.18.0",
69
87
  "@respectify/client": "^0.7.0",
70
88
  "astro": "^6.0.4",
89
+ "drizzle-kit": "^0.31.11",
90
+ "drizzle-orm": "^0.45.4",
71
91
  "typescript": "^5.4.3",
72
92
  "vitest": "^3.2.4"
73
93
  }
package/src/actions.ts CHANGED
@@ -1,9 +1,136 @@
1
- import { defineAction, ActionError } from 'astro:actions';
1
+ import { defineAction, ActionError, type ActionAPIContext } from 'astro:actions';
2
2
  import { z } from 'astro/zod';
3
- import { db, Comment, eq } from 'astro:db';
4
3
  import { analyzeComment } from './lib/service';
5
4
  import { checkRateLimit } from './lib/rate-limit';
6
5
  import { getIntegrationOptions } from './runtime-config';
6
+ import { getRespectifyRuntime } from './runtime';
7
+ import { COMMENT_LIMITS } from './store/limits';
8
+ import { CommentValidationError } from './store/schemas';
9
+
10
+ /** Input to `comments.submit`. Uses Astro's Zod (3 on Astro 5, 4 on Astro 6+), so only API both share. */
11
+ export const submitCommentInput = z.object({
12
+ postSlug: z.string().min(1).max(COMMENT_LIMITS.postSlugMax),
13
+ author: z.string().min(1).max(COMMENT_LIMITS.authorMax),
14
+ email: z.string().email().max(COMMENT_LIMITS.emailMax).optional(),
15
+ content: z.string().min(1).max(COMMENT_LIMITS.contentMax),
16
+ parentId: z.number().int().positive().optional(),
17
+ });
18
+
19
+ /** Input to `comments.delete`. */
20
+ export const deleteCommentInput = z.object({
21
+ commentId: z.number().int().positive(),
22
+ });
23
+
24
+ export type SubmitCommentInput = z.infer<typeof submitCommentInput>;
25
+ export type DeleteCommentInput = z.infer<typeof deleteCommentInput>;
26
+
27
+ export type SubmitCommentResult =
28
+ | {
29
+ success: false;
30
+ approved: false;
31
+ feedback: string;
32
+ suggestion: string | undefined;
33
+ suspectedSpam: boolean;
34
+ score: number;
35
+ }
36
+ | {
37
+ success: true;
38
+ approved: true;
39
+ feedback: string;
40
+ score: number;
41
+ message: string;
42
+ };
43
+
44
+ /** The client's address, or a shared bucket when the adapter or rendering mode does not expose one. */
45
+ function clientAddressOf(context: Pick<ActionAPIContext, 'clientAddress'>): string {
46
+ try {
47
+ return context.clientAddress;
48
+ } catch {
49
+ return 'unknown';
50
+ }
51
+ }
52
+
53
+ /**
54
+ * The text of the comment being replied to.
55
+ * @throws ActionError BAD_REQUEST when the parent does not exist, is on another post, or is not approved
56
+ */
57
+ async function loadReplyTarget(parentId: number, postSlug: string): Promise<string> {
58
+ const parent = await getRespectifyRuntime().store.findById(parentId);
59
+ if (!parent || parent.postSlug !== postSlug || !parent.approved) {
60
+ throw new ActionError({ code: 'BAD_REQUEST', message: 'The comment you are replying to was not found.' });
61
+ }
62
+ return parent.content;
63
+ }
64
+
65
+ /**
66
+ * Rate-limit, moderate with Respectify, and store the comment when it is approved.
67
+ * @throws ActionError TOO_MANY_REQUESTS, or BAD_REQUEST for an invalid parent or comment
68
+ */
69
+ export async function submitComment(
70
+ { postSlug, author, email, content, parentId }: SubmitCommentInput,
71
+ context: Pick<ActionAPIContext, 'clientAddress'>,
72
+ ): Promise<SubmitCommentResult> {
73
+ const { rateLimit } = getIntegrationOptions();
74
+ if (!checkRateLimit(clientAddressOf(context), rateLimit.windowMs, rateLimit.maxRequests)) {
75
+ throw new ActionError({
76
+ code: 'TOO_MANY_REQUESTS',
77
+ message: 'Too many comments submitted. Please wait a bit before trying again.',
78
+ });
79
+ }
80
+
81
+ const replyToComment = parentId === undefined ? undefined : await loadReplyTarget(parentId, postSlug);
82
+ const analysis = await analyzeComment(content, postSlug, { replyToComment });
83
+
84
+ if (!analysis.approved) {
85
+ return {
86
+ success: false,
87
+ approved: false,
88
+ feedback: analysis.feedback,
89
+ suggestion: analysis.suggestion,
90
+ suspectedSpam: analysis.suspectedSpam === true,
91
+ score: analysis.score,
92
+ };
93
+ }
94
+
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
+ }
103
+
104
+ return {
105
+ success: true,
106
+ approved: true,
107
+ feedback: analysis.feedback,
108
+ score: analysis.score,
109
+ message: 'Comment published successfully!',
110
+ };
111
+ }
112
+
113
+ /**
114
+ * Delete a comment. Only for an authenticated admin.
115
+ * @throws ActionError UNAUTHORIZED when not logged in, NOT_FOUND when there is no such comment
116
+ */
117
+ export async function deleteComment(
118
+ { commentId }: DeleteCommentInput,
119
+ context: Pick<ActionAPIContext, 'locals'>,
120
+ ): Promise<{ success: true }> {
121
+ if (!context.locals.isAuthenticated) {
122
+ throw new ActionError({
123
+ code: 'UNAUTHORIZED',
124
+ message: 'You must be logged in to delete comments',
125
+ });
126
+ }
127
+
128
+ const deleted = await getRespectifyRuntime().store.delete(commentId);
129
+ if (!deleted) {
130
+ throw new ActionError({ code: 'NOT_FOUND', message: 'Comment not found' });
131
+ }
132
+ return { success: true };
133
+ }
7
134
 
8
135
  /**
9
136
  * Merge into your src/actions/index.ts:
@@ -20,83 +147,13 @@ import { getIntegrationOptions } from './runtime-config';
20
147
  export const respectifyCommentActions = {
21
148
  submit: defineAction({
22
149
  accept: 'json',
23
- input: z.object({
24
- postSlug: z.string().min(1),
25
- author: z.string().min(1).max(100),
26
- email: z.string().email().optional(),
27
- content: z.string().min(1).max(5000),
28
- parentId: z.number().optional(),
29
- }),
30
- handler: async ({ postSlug, author, email, content, parentId }, context) => {
31
- const { rateLimit } = getIntegrationOptions();
32
- if (rateLimit) {
33
- let key = 'unknown';
34
- try {
35
- key = context.clientAddress;
36
- } catch {
37
- // Some adapters/rendering modes don't expose a client address; fall back to a shared bucket.
38
- }
39
- if (!checkRateLimit(key, rateLimit.windowMs, rateLimit.maxRequests)) {
40
- throw new ActionError({
41
- code: 'TOO_MANY_REQUESTS',
42
- message: 'Too many comments submitted. Please wait a bit before trying again.',
43
- });
44
- }
45
- }
46
-
47
- let replyToComment: string | undefined;
48
- if (parentId !== undefined) {
49
- const [parent] = await db.select().from(Comment).where(eq(Comment.id, parentId)).limit(1);
50
- replyToComment = parent?.content;
51
- }
52
-
53
- const analysis = await analyzeComment(content, postSlug, { replyToComment });
54
-
55
- if (!analysis.approved) {
56
- return {
57
- success: false as const,
58
- approved: false as const,
59
- feedback: analysis.feedback,
60
- suggestion: analysis.suggestion,
61
- suspectedSpam: analysis.suspectedSpam === true,
62
- score: analysis.score,
63
- };
64
- }
65
-
66
- await db.insert(Comment).values({
67
- postSlug,
68
- author,
69
- email,
70
- content,
71
- parentId,
72
- approved: true,
73
- });
74
-
75
- return {
76
- success: true as const,
77
- approved: true as const,
78
- feedback: analysis.feedback,
79
- score: analysis.score,
80
- message: 'Comment published successfully!',
81
- };
82
- },
150
+ input: submitCommentInput,
151
+ handler: submitComment,
83
152
  }),
84
153
 
85
154
  delete: defineAction({
86
155
  accept: 'json',
87
- input: z.object({
88
- commentId: z.number(),
89
- }),
90
- handler: async ({ commentId }, context) => {
91
- if (!context.locals.isAuthenticated) {
92
- throw new ActionError({
93
- code: 'UNAUTHORIZED',
94
- message: 'You must be logged in to delete comments',
95
- });
96
- }
97
-
98
- await db.delete(Comment).where(eq(Comment.id, commentId));
99
- return { success: true as const };
100
- },
156
+ input: deleteCommentInput,
157
+ handler: deleteComment,
101
158
  }),
102
159
  };
@@ -0,0 +1,7 @@
1
+ export { createPostgresCommentStore, type PostgresCommentStoreOptions } from './store';
2
+ export {
3
+ createPostgresCommentTable,
4
+ respectifyComments,
5
+ DEFAULT_POSTGRES_COMMENT_TABLE_NAME,
6
+ type PostgresCommentTable,
7
+ } from './table';
@@ -0,0 +1,83 @@
1
+ import { and, asc, eq } from 'drizzle-orm';
2
+ import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
3
+ import { commentIdSchema, parseNewComment } from '../../store/schemas';
4
+ import type { CommentRecord, ICommentStore, NewComment, PublicComment } from '../../store/types';
5
+ import { respectifyComments, type PostgresCommentTable } from './table';
6
+
7
+ export interface PostgresCommentStoreOptions {
8
+ /** The comment table, when it is not the default `respectify_comment` (see `createPostgresCommentTable`) */
9
+ table?: PostgresCommentTable;
10
+ }
11
+
12
+ /** A comment store on any Drizzle Postgres database: node-postgres, postgres.js, Neon, PGlite and others. */
13
+ class PostgresCommentStore<TQueryResult extends PgQueryResultHKT, TSchema extends Record<string, unknown>>
14
+ implements ICommentStore
15
+ {
16
+ readonly #db: PgDatabase<TQueryResult, TSchema>;
17
+ readonly #table: PostgresCommentTable;
18
+
19
+ constructor(db: PgDatabase<TQueryResult, TSchema>, table: PostgresCommentTable) {
20
+ this.#db = db;
21
+ this.#table = table;
22
+ }
23
+
24
+ async findById(id: number): Promise<CommentRecord | undefined> {
25
+ if (!commentIdSchema.safeParse(id).success) return undefined;
26
+ const [row] = await this.#db.select().from(this.#table).where(eq(this.#table.id, id)).limit(1);
27
+ return row;
28
+ }
29
+
30
+ async listApproved(postSlug: string): Promise<PublicComment[]> {
31
+ const table = this.#table;
32
+ return this.#db
33
+ .select({
34
+ id: table.id,
35
+ author: table.author,
36
+ content: table.content,
37
+ createdAt: table.createdAt,
38
+ parentId: table.parentId,
39
+ })
40
+ .from(table)
41
+ .where(and(eq(table.postSlug, postSlug), eq(table.approved, true)))
42
+ .orderBy(asc(table.createdAt), asc(table.id));
43
+ }
44
+
45
+ async create(input: NewComment): Promise<CommentRecord> {
46
+ const comment = parseNewComment(input);
47
+ const [row] = await this.#db
48
+ .insert(this.#table)
49
+ .values({
50
+ postSlug: comment.postSlug,
51
+ author: comment.author,
52
+ email: comment.email ?? null,
53
+ content: comment.content,
54
+ approved: comment.approved,
55
+ parentId: comment.parentId ?? null,
56
+ })
57
+ .returning();
58
+ if (!row) {
59
+ throw new Error('The comment was not stored: the database returned no row');
60
+ }
61
+ return row;
62
+ }
63
+
64
+ async delete(id: number): Promise<boolean> {
65
+ if (!commentIdSchema.safeParse(id).success) return false;
66
+ // The parent_id foreign key sets each reply's parent to null
67
+ const deleted = await this.#db.delete(this.#table).where(eq(this.#table.id, id)).returning({ id: this.#table.id });
68
+ return deleted.length > 0;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Store comments in Postgres through your own Drizzle database instance, so the integration
74
+ * uses your connection and never opens one. The table must already exist: add
75
+ * `respectifyComments` (or a table from `createPostgresCommentTable`) to your Drizzle schema
76
+ * and migrate with drizzle-kit.
77
+ */
78
+ export function createPostgresCommentStore<
79
+ TQueryResult extends PgQueryResultHKT,
80
+ TSchema extends Record<string, unknown>,
81
+ >(db: PgDatabase<TQueryResult, TSchema>, options: PostgresCommentStoreOptions = {}): ICommentStore {
82
+ return new PostgresCommentStore(db, options.table ?? respectifyComments);
83
+ }
@@ -0,0 +1,37 @@
1
+ import { boolean, index, integer, pgTable, text, timestamp, type AnyPgColumn } from 'drizzle-orm/pg-core';
2
+
3
+ /** The default Postgres table name for Respectify comments. */
4
+ export const DEFAULT_POSTGRES_COMMENT_TABLE_NAME = 'respectify_comment';
5
+
6
+ /**
7
+ * Build the Drizzle definition of the comment table, named `name`. Put the result in your
8
+ * Drizzle schema so drizzle-kit can generate its migration; the store never creates it.
9
+ *
10
+ * Replies keep a foreign key to their parent, which is set to null when the parent is deleted.
11
+ */
12
+ export function createPostgresCommentTable(name: string = DEFAULT_POSTGRES_COMMENT_TABLE_NAME) {
13
+ const table = pgTable(
14
+ name,
15
+ {
16
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
17
+ postSlug: text('post_slug').notNull(),
18
+ author: text('author').notNull(),
19
+ email: text('email'),
20
+ content: text('content').notNull(),
21
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
22
+ approved: boolean('approved').notNull().default(false),
23
+ parentId: integer('parent_id').references((): AnyPgColumn => table.id, { onDelete: 'set null' }),
24
+ },
25
+ (columns) => [
26
+ index(`${name}_post_slug_created_at_idx`).on(columns.postSlug, columns.createdAt),
27
+ index(`${name}_parent_id_idx`).on(columns.parentId),
28
+ ],
29
+ );
30
+ return table;
31
+ }
32
+
33
+ /** The Drizzle type of a Respectify comment table on Postgres. */
34
+ export type PostgresCommentTable = ReturnType<typeof createPostgresCommentTable>;
35
+
36
+ /** The comment table under its default name, ready to export from your Drizzle schema. */
37
+ export const respectifyComments: PostgresCommentTable = createPostgresCommentTable();
@@ -0,0 +1,8 @@
1
+ export { createSqliteCommentStore, type SqliteCommentStoreOptions } from './store';
2
+ export {
3
+ createSqliteCommentTable,
4
+ respectifyComments,
5
+ DEFAULT_SQLITE_COMMENT_TABLE_NAME,
6
+ type SqliteCommentTable,
7
+ } from './table';
8
+ export { parseStoredDate } from './text-date';
@@ -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
- import '@astrojs/db';
4
-
5
- declare global {
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:db' {
19
- export const Comment: import('@astrojs/db/runtime').Table<
20
- 'Comment',
21
- typeof import('./schema').RespectifyComment.columns
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
  }