@respectify/astro 1.0.2 → 1.2.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,311 @@
1
+ import path from 'node:path';
2
+ import { z } from 'zod';
3
+ import {
4
+ ACTIONS_MANUAL_INSTRUCTIONS,
5
+ COMPONENT_SNIPPET,
6
+ ENVIRONMENT_VARIABLES,
7
+ REQUIRED_PACKAGES,
8
+ SCAFFOLD_PATHS,
9
+ actionsTemplate,
10
+ drizzleConfigTemplate,
11
+ runtimeTemplate,
12
+ schemaExportLine,
13
+ schemaTemplate,
14
+ } from './templates.js';
15
+ import type {
16
+ DatabaseKind,
17
+ IProjectFiles,
18
+ InitDependencies,
19
+ InitOptions,
20
+ InitResult,
21
+ InitStep,
22
+ } from './types.js';
23
+
24
+ /** A problem the person running the command can fix, reported without a stack trace. */
25
+ export class InitError extends Error {
26
+ override readonly name = 'InitError';
27
+ }
28
+
29
+ const PACKAGE_JSON = 'package.json';
30
+
31
+ const ASTRO_CONFIG_FILES = [
32
+ 'astro.config.ts',
33
+ 'astro.config.mjs',
34
+ 'astro.config.js',
35
+ 'astro.config.mts',
36
+ 'astro.config.cjs',
37
+ ] as const;
38
+
39
+ const DRIZZLE_CONFIG_FILES = [
40
+ 'drizzle.config.ts',
41
+ 'drizzle.config.js',
42
+ 'drizzle.config.mjs',
43
+ 'drizzle.config.mts',
44
+ 'drizzle.config.cjs',
45
+ ] as const;
46
+
47
+ /** The places Astro looks for a site's actions. */
48
+ const ACTIONS_FILES = [
49
+ 'src/actions/index.ts',
50
+ 'src/actions/index.js',
51
+ 'src/actions/index.mjs',
52
+ 'src/actions.ts',
53
+ 'src/actions.js',
54
+ ] as const;
55
+
56
+ /** A schema that is one source file, which a line can be added to. */
57
+ const SCHEMA_SOURCE_FILE = /\.(?:ts|mts|js|mjs)$/;
58
+
59
+ /** Which database each drizzle-kit dialect means to this package. Other dialects are not supported. */
60
+ const DIALECT_DATABASE: Record<string, DatabaseKind | undefined> = {
61
+ postgresql: 'postgres',
62
+ sqlite: 'sqlite',
63
+ turso: 'sqlite',
64
+ };
65
+
66
+ const packageJsonSchema = z.object({
67
+ dependencies: z.record(z.string(), z.string()).optional(),
68
+ devDependencies: z.record(z.string(), z.string()).optional(),
69
+ });
70
+
71
+ /** How each package manager installs packages and runs a project's binaries. */
72
+ interface PackageManagerCommands {
73
+ install: string;
74
+ installDev: string;
75
+ run: string;
76
+ }
77
+
78
+ const PACKAGE_MANAGERS: readonly { lockFiles: readonly string[]; commands: PackageManagerCommands }[] = [
79
+ { lockFiles: ['pnpm-lock.yaml'], commands: { install: 'pnpm add', installDev: 'pnpm add -D', run: 'pnpm exec' } },
80
+ { lockFiles: ['yarn.lock'], commands: { install: 'yarn add', installDev: 'yarn add -D', run: 'yarn' } },
81
+ { lockFiles: ['bun.lock', 'bun.lockb'], commands: { install: 'bun add', installDev: 'bun add -d', run: 'bunx' } },
82
+ ];
83
+
84
+ const NPM_COMMANDS: PackageManagerCommands = { install: 'npm install', installDev: 'npm install -D', run: 'npx' };
85
+
86
+ /** The first of the candidate files that exists in the project. */
87
+ function findFirst(files: IProjectFiles, candidates: readonly string[]): string | undefined {
88
+ return candidates.find((candidate) => files.exists(candidate));
89
+ }
90
+
91
+ /** The package manager the project uses, judged by its lock file. npm when there is none. */
92
+ function detectPackageManager(files: IProjectFiles): PackageManagerCommands {
93
+ const found = PACKAGE_MANAGERS.find((manager) => manager.lockFiles.some((lockFile) => files.exists(lockFile)));
94
+ return found?.commands ?? NPM_COMMANDS;
95
+ }
96
+
97
+ /** The names of every package the project already depends on. */
98
+ function readInstalledPackages(files: IProjectFiles): Set<string> {
99
+ let parsed: z.infer<typeof packageJsonSchema>;
100
+ try {
101
+ parsed = packageJsonSchema.parse(JSON.parse(files.read(PACKAGE_JSON)));
102
+ } catch (error) {
103
+ const reason = error instanceof Error ? error.message : String(error);
104
+ throw new InitError(`Could not read ${PACKAGE_JSON}: ${reason}`);
105
+ }
106
+ return new Set([...Object.keys(parsed.dependencies ?? {}), ...Object.keys(parsed.devDependencies ?? {})]);
107
+ }
108
+
109
+ /** True for a relative path that stays inside the project folder. */
110
+ function isInsideProject(relativePath: string): boolean {
111
+ const segments = relativePath.split(/[\\/]/);
112
+ return !path.isAbsolute(relativePath) && !segments.includes('..');
113
+ }
114
+
115
+ /** What an existing drizzle-kit config says about the project's database. */
116
+ interface DrizzleConfigInfo {
117
+ path: string;
118
+ /** The config's dialect as written, when it could be read. */
119
+ dialect?: string;
120
+ /** The database that dialect means, when this package supports it. */
121
+ database?: DatabaseKind;
122
+ /** The schema file, relative to the project root, when the config names exactly one source file. */
123
+ schemaFile?: string;
124
+ }
125
+
126
+ /** Read the dialect and schema file out of a drizzle-kit config without running it. */
127
+ function readDrizzleConfig(files: IProjectFiles): DrizzleConfigInfo | undefined {
128
+ const path = findFirst(files, DRIZZLE_CONFIG_FILES);
129
+ if (path === undefined) return undefined;
130
+
131
+ const source = files.read(path);
132
+ const dialect = /\bdialect\s*:\s*(['"`])([a-z]+)\1/.exec(source)?.[2];
133
+ const schema = /\bschema\s*:\s*(['"`])([^'"`]+)\1/.exec(source)?.[2];
134
+ // Only a single source file inside the project can have a line added to it
135
+ const schemaFile =
136
+ schema !== undefined && !schema.includes('*') && SCHEMA_SOURCE_FILE.test(schema) && isInsideProject(schema)
137
+ ? schema.replace(/^\.\//, '')
138
+ : undefined;
139
+
140
+ return {
141
+ path,
142
+ dialect,
143
+ database: dialect === undefined ? undefined : DIALECT_DATABASE[dialect],
144
+ schemaFile,
145
+ };
146
+ }
147
+
148
+ /** The database to scaffold for: the one asked for, else the project's own, else the person's answer. */
149
+ async function resolveDatabase(
150
+ options: InitOptions,
151
+ drizzleConfig: DrizzleConfigInfo | undefined,
152
+ { prompter }: InitDependencies,
153
+ ): Promise<DatabaseKind> {
154
+ if (options.database !== undefined) return options.database;
155
+ if (drizzleConfig?.database !== undefined) return drizzleConfig.database;
156
+ if (!prompter.interactive) {
157
+ throw new InitError('Say which database your comments go in: --database postgres or --database sqlite');
158
+ }
159
+ return prompter.choose<DatabaseKind>('Which database will store your comments?', [
160
+ { value: 'postgres', label: 'Postgres' },
161
+ { value: 'sqlite', label: 'SQLite (libSQL or Turso)' },
162
+ ]);
163
+ }
164
+
165
+ /** Write a file unless it already exists. */
166
+ function createIfMissing(files: IProjectFiles, path: string, content: string): InitStep {
167
+ if (files.exists(path)) return { status: 'unchanged', path };
168
+ files.create(path, content);
169
+ return { status: 'created', path };
170
+ }
171
+
172
+ /** Expose the comment actions: in a new actions file, or by telling the person what to add to theirs. */
173
+ function scaffoldActions(files: IProjectFiles): InitStep {
174
+ const existing = findFirst(files, ACTIONS_FILES);
175
+ if (existing === undefined) return createIfMissing(files, SCAFFOLD_PATHS.actions, actionsTemplate());
176
+ if (files.read(existing).includes('respectifyCommentActions')) return { status: 'unchanged', path: existing };
177
+ return { status: 'manual', path: existing, instructions: ACTIONS_MANUAL_INSTRUCTIONS };
178
+ }
179
+
180
+ /** Make sure a schema file exports the comment table, adding the line when it is missing. */
181
+ function addTableToSchema(files: IProjectFiles, path: string, database: DatabaseKind): InitStep {
182
+ if (!files.exists(path)) {
183
+ files.create(path, schemaTemplate(database));
184
+ return { status: 'created', path };
185
+ }
186
+ const source = files.read(path);
187
+ if (source.includes('@respectify/astro/')) return { status: 'unchanged', path };
188
+ const separator = source === '' || source.endsWith('\n') ? '' : '\n';
189
+ files.append(path, `${separator}${schemaExportLine(database)}\n`);
190
+ return { status: 'updated', path };
191
+ }
192
+
193
+ /**
194
+ * Put the comment table in the project's Drizzle schema. A project with no drizzle-kit config
195
+ * gets one; a project with its own keeps it, and gets the table added to the schema it names.
196
+ */
197
+ function scaffoldDrizzle(
198
+ files: IProjectFiles,
199
+ database: DatabaseKind,
200
+ drizzleConfig: DrizzleConfigInfo | undefined,
201
+ ): InitStep[] {
202
+ if (drizzleConfig === undefined) {
203
+ return [
204
+ addTableToSchema(files, SCAFFOLD_PATHS.schema, database),
205
+ createIfMissing(files, SCAFFOLD_PATHS.drizzleConfig, drizzleConfigTemplate(database)),
206
+ ];
207
+ }
208
+
209
+ const exportLine = schemaExportLine(database);
210
+ if (drizzleConfig.dialect !== undefined && drizzleConfig.database !== database) {
211
+ return [
212
+ {
213
+ status: 'manual',
214
+ path: drizzleConfig.path,
215
+ instructions:
216
+ `${drizzleConfig.path} is set up for "${drizzleConfig.dialect}", not ${database}, so the comment table ` +
217
+ `was not added to it. Give the comment table its own drizzle-kit config, with a schema containing:\n\n ${exportLine}`,
218
+ },
219
+ ];
220
+ }
221
+ if (drizzleConfig.schemaFile === undefined) {
222
+ return [
223
+ {
224
+ status: 'manual',
225
+ path: drizzleConfig.path,
226
+ instructions: `Add the comment table to your Drizzle schema:\n\n ${exportLine}`,
227
+ },
228
+ ];
229
+ }
230
+ return [addTableToSchema(files, drizzleConfig.schemaFile, database)];
231
+ }
232
+
233
+ /** What the project looked like before anything was written. */
234
+ interface ProjectState {
235
+ astroConfigPath: string;
236
+ astroConfig: string;
237
+ installed: Set<string>;
238
+ }
239
+
240
+ /** Everything the command leaves for the person, in the order to do it. */
241
+ function describeNextSteps(files: IProjectFiles, database: DatabaseKind, project: ProjectState): string[] {
242
+ const commands = detectPackageManager(files);
243
+ const { installed, astroConfig, astroConfigPath } = project;
244
+ const steps: string[] = [];
245
+
246
+ const required = REQUIRED_PACKAGES[database];
247
+ const missing = required.runtime.filter((name) => !installed.has(name));
248
+ const missingDev = required.dev.filter((name) => !installed.has(name));
249
+ const installLines = [
250
+ ...(missing.length > 0 ? [`${commands.install} ${missing.join(' ')}`] : []),
251
+ ...(missingDev.length > 0 ? [`${commands.installDev} ${missingDev.join(' ')}`] : []),
252
+ ];
253
+ if (installLines.length > 0) {
254
+ steps.push(`Install the database packages:\n\n ${installLines.join('\n ')}`);
255
+ }
256
+
257
+ if (!astroConfig.includes('@respectify/astro')) {
258
+ steps.push(`Add the integration to ${astroConfigPath}:\n\n ${commands.run} astro add @respectify/astro`);
259
+ }
260
+ if (!/\badapter\s*:/.test(astroConfig)) {
261
+ steps.push(
262
+ 'Comments are saved by your server, so the site needs a server adapter. For Node:\n\n' +
263
+ ` ${commands.run} astro add node\n\n` +
264
+ 'Vercel, Netlify and Cloudflare have adapters too.',
265
+ );
266
+ }
267
+
268
+ steps.push(
269
+ `Set these environment variables (in .env for local work):\n\n ${ENVIRONMENT_VARIABLES[database].join('\n ')}`,
270
+ );
271
+ steps.push(
272
+ `Create the comment table:\n\n ${commands.run} drizzle-kit generate\n ${commands.run} drizzle-kit migrate`,
273
+ );
274
+ steps.push(
275
+ `Put comments on a page, for example in your blog post layout:\n\n ${COMPONENT_SNIPPET.split('\n').join('\n ')}`,
276
+ );
277
+ return steps;
278
+ }
279
+
280
+ /**
281
+ * Scaffold the files a site needs for Respectify comments: the runtime module, the config
282
+ * file, the comment actions and the comment table in the Drizzle schema. A file that already
283
+ * exists is never overwritten.
284
+ * @throws InitError when the folder is not an Astro project or the database cannot be decided
285
+ */
286
+ export async function runInit(options: InitOptions, dependencies: InitDependencies): Promise<InitResult> {
287
+ const { files, defaultConfigJson } = dependencies;
288
+
289
+ const astroConfigPath = findFirst(files, ASTRO_CONFIG_FILES);
290
+ if (!files.exists(PACKAGE_JSON) || astroConfigPath === undefined) {
291
+ throw new InitError('Run this in the root folder of an Astro project: no package.json and astro.config found here.');
292
+ }
293
+
294
+ // Everything that can fail is read before the first file is written
295
+ const project: ProjectState = {
296
+ astroConfigPath,
297
+ astroConfig: files.read(astroConfigPath),
298
+ installed: readInstalledPackages(files),
299
+ };
300
+ const drizzleConfig = readDrizzleConfig(files);
301
+ const database = await resolveDatabase(options, drizzleConfig, dependencies);
302
+
303
+ const steps: InitStep[] = [
304
+ createIfMissing(files, SCAFFOLD_PATHS.runtime, runtimeTemplate(database)),
305
+ createIfMissing(files, SCAFFOLD_PATHS.config, defaultConfigJson),
306
+ scaffoldActions(files),
307
+ ...scaffoldDrizzle(files, database, drizzleConfig),
308
+ ];
309
+
310
+ return { database, steps, nextSteps: describeNextSteps(files, database, project) };
311
+ }
@@ -0,0 +1,47 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import type { IProjectFiles } from './types.js';
4
+
5
+ /** The files of a project on disk. */
6
+ export class NodeProjectFiles implements IProjectFiles {
7
+ private readonly root: string;
8
+
9
+ constructor(root: string) {
10
+ this.root = path.resolve(root);
11
+ }
12
+
13
+ exists(relativePath: string): boolean {
14
+ const resolved = this.tryResolve(relativePath);
15
+ return resolved !== undefined && fs.existsSync(resolved) && fs.statSync(resolved).isFile();
16
+ }
17
+
18
+ read(relativePath: string): string {
19
+ return fs.readFileSync(this.resolve(relativePath), 'utf8');
20
+ }
21
+
22
+ create(relativePath: string, content: string): void {
23
+ const resolved = this.resolve(relativePath);
24
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
25
+ // 'wx' fails when the file exists, so a file is never overwritten even in a race
26
+ fs.writeFileSync(resolved, content, { encoding: 'utf8', flag: 'wx' });
27
+ }
28
+
29
+ append(relativePath: string, content: string): void {
30
+ fs.appendFileSync(this.resolve(relativePath), content, 'utf8');
31
+ }
32
+
33
+ /** The absolute path, or undefined when it would leave the project. */
34
+ private tryResolve(relativePath: string): string | undefined {
35
+ const resolved = path.resolve(this.root, relativePath);
36
+ const inside = resolved === this.root || resolved.startsWith(`${this.root}${path.sep}`);
37
+ return inside ? resolved : undefined;
38
+ }
39
+
40
+ private resolve(relativePath: string): string {
41
+ const resolved = this.tryResolve(relativePath);
42
+ if (resolved === undefined) {
43
+ throw new Error(`${relativePath} is outside the project folder`);
44
+ }
45
+ return resolved;
46
+ }
47
+ }
@@ -0,0 +1,158 @@
1
+ import type { DatabaseKind } from './types.js';
2
+
3
+ /** Where `init` puts each file, relative to the project root. */
4
+ export const SCAFFOLD_PATHS = {
5
+ runtime: 'src/respectify.runtime.ts',
6
+ config: 'respectify.config.json',
7
+ actions: 'src/actions/index.ts',
8
+ schema: 'src/db/schema.ts',
9
+ drizzleConfig: 'drizzle.config.ts',
10
+ } as const;
11
+
12
+ /** The package subpath that exports the comment table and store for each database. */
13
+ const ADAPTER_ENTRY: Record<DatabaseKind, string> = {
14
+ postgres: '@respectify/astro/postgres',
15
+ sqlite: '@respectify/astro/sqlite',
16
+ };
17
+
18
+ /** The line a Drizzle schema needs so drizzle-kit creates the comment table. */
19
+ export function schemaExportLine(database: DatabaseKind): string {
20
+ return `export { respectifyComments } from '${ADAPTER_ENTRY[database]}';`;
21
+ }
22
+
23
+ /** A new Drizzle schema file holding only the comment table. */
24
+ export function schemaTemplate(database: DatabaseKind): string {
25
+ return `// The table Respectify comments are stored in. Add your own tables to this file too.
26
+ ${schemaExportLine(database)}
27
+ `;
28
+ }
29
+
30
+ const POSTGRES_RUNTIME = `import { defineRespectifyRuntime } from '@respectify/astro/runtime';
31
+ import { createPostgresCommentStore } from '@respectify/astro/postgres';
32
+ import { drizzle } from 'drizzle-orm/node-postgres';
33
+ import { Pool } from 'pg';
34
+ import { getSecret } from 'astro:env/server';
35
+
36
+ const connectionString = getSecret('DATABASE_URL');
37
+ if (!connectionString) {
38
+ throw new Error('DATABASE_URL is not set. Respectify comments need it to reach your database.');
39
+ }
40
+
41
+ // If your site already creates a Drizzle database, import it here and delete these lines.
42
+ const db = drizzle({ client: new Pool({ connectionString }) });
43
+
44
+ export default defineRespectifyRuntime({
45
+ store: createPostgresCommentStore(db),
46
+ // Optional: the public URL of a post, which Respectify reads for topic context
47
+ // getPostUrl: (slug, site) => \`\${site}/blog/\${slug}/\`,
48
+ });
49
+ `;
50
+
51
+ const SQLITE_RUNTIME = `import { defineRespectifyRuntime } from '@respectify/astro/runtime';
52
+ import { createSqliteCommentStore } from '@respectify/astro/sqlite';
53
+ import { drizzle } from 'drizzle-orm/libsql';
54
+ import { createClient } from '@libsql/client';
55
+ import { getSecret } from 'astro:env/server';
56
+
57
+ const url = getSecret('DATABASE_URL');
58
+ if (!url) {
59
+ throw new Error('DATABASE_URL is not set. Respectify comments need it to reach your database.');
60
+ }
61
+
62
+ // Only a hosted database such as Turso needs a token; an empty one counts as none
63
+ const authToken = getSecret('DATABASE_AUTH_TOKEN') || undefined;
64
+
65
+ // If your site already creates a Drizzle database, import it here and delete these lines.
66
+ const db = drizzle({ client: createClient({ url, authToken }) });
67
+
68
+ export default defineRespectifyRuntime({
69
+ store: createSqliteCommentStore(db),
70
+ // Optional: the public URL of a post, which Respectify reads for topic context
71
+ // getPostUrl: (slug, site) => \`\${site}/blog/\${slug}/\`,
72
+ });
73
+ `;
74
+
75
+ /** The runtime module: it builds the comment store from the site's database connection. */
76
+ export function runtimeTemplate(database: DatabaseKind): string {
77
+ return database === 'postgres' ? POSTGRES_RUNTIME : SQLITE_RUNTIME;
78
+ }
79
+
80
+ /** The lines an existing actions file needs. */
81
+ export const ACTIONS_MANUAL_INSTRUCTIONS = `Add the comment actions to your existing actions:
82
+
83
+ import { respectifyCommentActions } from '@respectify/astro/actions';
84
+
85
+ export const server = {
86
+ // ...your actions
87
+ comments: respectifyCommentActions,
88
+ };`;
89
+
90
+ /** A new Astro Actions file exposing the comment actions. */
91
+ export function actionsTemplate(): string {
92
+ return `import { respectifyCommentActions } from '@respectify/astro/actions';
93
+
94
+ export const server = {
95
+ comments: respectifyCommentActions,
96
+ };
97
+ `;
98
+ }
99
+
100
+ const DRIZZLE_CONFIG_HEAD = `import { existsSync } from 'node:fs';
101
+ import { defineConfig } from 'drizzle-kit';
102
+
103
+ // drizzle-kit does not read .env by itself
104
+ if (existsSync('.env')) process.loadEnvFile('.env');
105
+
106
+ const url = process.env.DATABASE_URL;
107
+ if (!url) {
108
+ throw new Error('Set DATABASE_URL before running drizzle-kit.');
109
+ }
110
+ `;
111
+
112
+ /** A new drizzle-kit config pointing at the schema file `init` writes. */
113
+ export function drizzleConfigTemplate(database: DatabaseKind): string {
114
+ const dialect = database === 'postgres' ? 'postgresql' : 'turso';
115
+ // drizzle-kit rejects an empty token, so an empty DATABASE_AUTH_TOKEN counts as none
116
+ const credentials =
117
+ database === 'postgres' ? '{ url }' : '{ url, authToken: process.env.DATABASE_AUTH_TOKEN || undefined }';
118
+ return `${DRIZZLE_CONFIG_HEAD}
119
+ export default defineConfig({
120
+ dialect: '${dialect}',
121
+ schema: './${SCAFFOLD_PATHS.schema}',
122
+ out: './drizzle',
123
+ dbCredentials: ${credentials},
124
+ });
125
+ `;
126
+ }
127
+
128
+ /** The packages each database needs beside `@respectify/astro` itself. */
129
+ export const REQUIRED_PACKAGES: Record<DatabaseKind, { runtime: readonly string[]; dev: readonly string[] }> = {
130
+ postgres: { runtime: ['@respectify/client', 'drizzle-orm', 'pg'], dev: ['drizzle-kit', '@types/pg'] },
131
+ sqlite: { runtime: ['@respectify/client', 'drizzle-orm', '@libsql/client'], dev: ['drizzle-kit'] },
132
+ };
133
+
134
+ /** The lines shown for the environment variables each database's runtime module reads, with sample values. */
135
+ export const ENVIRONMENT_VARIABLES: Record<DatabaseKind, readonly string[]> = {
136
+ postgres: [
137
+ 'RESPECTIFY_EMAIL=you@example.com',
138
+ 'RESPECTIFY_API_KEY=your-api-key',
139
+ 'DATABASE_URL=postgres://user:password@host:5432/database',
140
+ ],
141
+ sqlite: [
142
+ 'RESPECTIFY_EMAIL=you@example.com',
143
+ 'RESPECTIFY_API_KEY=your-api-key',
144
+ 'DATABASE_URL=file:local.db',
145
+ '',
146
+ 'For a hosted database such as Turso, use its URL and token instead:',
147
+ '',
148
+ 'DATABASE_URL=libsql://your-database.turso.io',
149
+ 'DATABASE_AUTH_TOKEN=your-database-token',
150
+ ],
151
+ };
152
+
153
+ /** The snippet that puts comments on a page. */
154
+ export const COMPONENT_SNIPPET = `---
155
+ import CommentSection from '@respectify/astro/components/CommentSection.astro';
156
+ ---
157
+
158
+ <CommentSection postSlug={post.id} />`;
@@ -0,0 +1,39 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import type { ICliLogger, IPrompter, PromptChoice } from './types.js';
3
+
4
+ /** Writes messages to the terminal: information to stdout, warnings and errors to stderr. */
5
+ export class TerminalLogger implements ICliLogger {
6
+ info(message: string): void {
7
+ process.stdout.write(`${message}\n`);
8
+ }
9
+
10
+ warn(message: string): void {
11
+ process.stderr.write(`Warning: ${message}\n`);
12
+ }
13
+
14
+ error(message: string): void {
15
+ process.stderr.write(`Error: ${message}\n`);
16
+ }
17
+ }
18
+
19
+ /** Asks questions on the terminal, when there is one. */
20
+ export class TerminalPrompter implements IPrompter {
21
+ get interactive(): boolean {
22
+ return process.stdin.isTTY === true && process.stdout.isTTY === true;
23
+ }
24
+
25
+ async choose<Value extends string>(question: string, choices: readonly PromptChoice<Value>[]): Promise<Value> {
26
+ const readline = createInterface({ input: process.stdin, output: process.stdout });
27
+ try {
28
+ const menu = choices.map((choice, index) => ` ${index + 1}. ${choice.label}`).join('\n');
29
+ for (;;) {
30
+ const answer = (await readline.question(`${question}\n${menu}\n> `)).trim().toLowerCase();
31
+ const picked = choices[Number(answer) - 1] ?? choices.find((choice) => choice.value === answer);
32
+ if (picked !== undefined) return picked.value;
33
+ process.stdout.write(`Enter a number from 1 to ${choices.length}.\n`);
34
+ }
35
+ } finally {
36
+ readline.close();
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,89 @@
1
+ /** The databases `init` can scaffold a comment store for. */
2
+ export const DATABASE_KINDS = ['postgres', 'sqlite'] as const;
3
+
4
+ /** A database `init` can scaffold a comment store for: Postgres, or SQLite through libSQL/Turso. */
5
+ export type DatabaseKind = (typeof DATABASE_KINDS)[number];
6
+
7
+ /** Where the command writes what it has to say. */
8
+ export interface ICliLogger {
9
+ info(message: string): void;
10
+ warn(message: string): void;
11
+ error(message: string): void;
12
+ }
13
+
14
+ /**
15
+ * The project the command works on. Every path is relative to the project root, and a path
16
+ * that would leave the root is refused.
17
+ */
18
+ export interface IProjectFiles {
19
+ /** True when the path names a file inside the project. */
20
+ exists(relativePath: string): boolean;
21
+
22
+ /** @throws Error when the file is missing or outside the project */
23
+ read(relativePath: string): string;
24
+
25
+ /**
26
+ * Write a new file, creating its folders.
27
+ * @throws Error when the file already exists: nothing is ever overwritten
28
+ */
29
+ create(relativePath: string, content: string): void;
30
+
31
+ /** Add text to the end of an existing file. */
32
+ append(relativePath: string, content: string): void;
33
+ }
34
+
35
+ /** One answer a question accepts. */
36
+ export interface PromptChoice<Value extends string> {
37
+ value: Value;
38
+ label: string;
39
+ }
40
+
41
+ /** Asks the person running the command a question. */
42
+ export interface IPrompter {
43
+ /** True when there is a terminal to ask on. */
44
+ readonly interactive: boolean;
45
+
46
+ choose<Value extends string>(question: string, choices: readonly PromptChoice<Value>[]): Promise<Value>;
47
+ }
48
+
49
+ /** What `init` was asked to do. */
50
+ export interface InitOptions {
51
+ /** The database to scaffold for. When absent it is read from drizzle.config, then asked for. */
52
+ database?: DatabaseKind;
53
+ }
54
+
55
+ /** What happened to one file `init` is responsible for. */
56
+ export type InitStepStatus =
57
+ /** The file did not exist and was written. */
58
+ | 'created'
59
+ /** A line was added to the end of an existing file. */
60
+ | 'updated'
61
+ /** The file already had what it needs, or already exists and was left alone. */
62
+ | 'unchanged'
63
+ /** The command could not safely make the change; `instructions` says what to do by hand. */
64
+ | 'manual';
65
+
66
+ /** The outcome for one file. */
67
+ export interface InitStep {
68
+ status: InitStepStatus;
69
+ /** The file, relative to the project root. */
70
+ path: string;
71
+ /** What the person has to do themselves, for a `manual` step. */
72
+ instructions?: string;
73
+ }
74
+
75
+ /** Everything `init` did and everything left for the person to do. */
76
+ export interface InitResult {
77
+ database: DatabaseKind;
78
+ steps: InitStep[];
79
+ /** The remaining steps, in the order to do them. */
80
+ nextSteps: string[];
81
+ }
82
+
83
+ /** What `init` needs from the outside world. */
84
+ export interface InitDependencies {
85
+ files: IProjectFiles;
86
+ prompter: IPrompter;
87
+ /** The text of the package's default-respectify.config.json. */
88
+ defaultConfigJson: string;
89
+ }
@@ -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
@@ -51,9 +51,10 @@ function createVirtualModulesPlugin(modules: Record<string, string>): VirtualMod
51
51
  /**
52
52
  * The Respectify comments integration. Its options are serialized into the server bundle,
53
53
  * so they must be plain data; the comment store and post functions live in the module
54
- * named by `runtime`.
54
+ * named by `runtime`. Every option has a default, so `astro add @respectify/astro` and
55
+ * `respectify-astro init` are enough to set a site up.
55
56
  */
56
- export default function respectify(userOptions: RespectifyIntegrationOptions): AstroIntegration {
57
+ export default function respectify(userOptions: RespectifyIntegrationOptions = {}): AstroIntegration {
57
58
  const parsed = parseIntegrationOptions(userOptions);
58
59
  const resolvedOptions = toResolvedIntegrationOptions(parsed);
59
60
  const routePattern = resolvedOptions.commentsApiPath.replace(/^\//, '');
@@ -109,6 +110,11 @@ export type {
109
110
  RespectifyClientConfig,
110
111
  RespectifyMegacallConfig,
111
112
  AnalyzeCommentOptions,
113
+ ModerationSkipped,
114
+ ModerationStoppedEvent,
115
+ ModerationStoppedReason,
116
+ HeldForReviewEvent,
117
+ HeldForReviewReason,
112
118
  } from './types';
113
119
  export type { ICommentStore, CommentRecord, NewComment, PublicComment } from './store/types';
114
120
  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.';