@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.
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
 
@@ -33,6 +34,81 @@ Built for production — powers [nickhodges.com](https://nickhodges.com) as a li
33
34
 
34
35
  ## Quick start
35
36
 
37
+ ### 1. Add the integration
38
+
39
+ ```bash
40
+ npx astro add @respectify/astro
41
+ ```
42
+
43
+ This installs the package and adds `respectify()` to your `astro.config`. Comments are saved by your server, so the site also needs a server adapter; if it has none yet, add one the same way, for example `npx astro add node` (or `vercel`, `netlify`, `cloudflare`).
44
+
45
+ ### 2. Run init
46
+
47
+ ```bash
48
+ npx @respectify/astro init
49
+ ```
50
+
51
+ It asks which database your comments go in (or pass `--database postgres` or `--database sqlite`; a project with a `drizzle.config` is not asked) and writes what the integration needs:
52
+
53
+ | File | What it is |
54
+ | --- | --- |
55
+ | `src/respectify.runtime.ts` | The runtime module: connects to your database and creates the comment store |
56
+ | `respectify.config.json` | Moderation settings, with the defaults |
57
+ | `src/actions/index.ts` | Astro Actions exposing the comment actions |
58
+ | `src/db/schema.ts` | A Drizzle schema with the comment table |
59
+ | `drizzle.config.ts` | A drizzle-kit config for creating the table |
60
+
61
+ A file that already exists is never overwritten. If you already use Drizzle, your own `drizzle.config` is kept and the comment table is added as one line at the end of the schema file it names. Where `init` cannot safely make a change itself, such as a site that already has actions or a schema split over several files, it prints the lines for you to add. It finishes with a numbered list of what is left, which is steps 3 to 6 below with anything you have already done left out.
62
+
63
+ ### 3. Install the database packages
64
+
65
+ `init` prints the exact command for your package manager and whatever is missing. For Postgres:
66
+
67
+ ```bash
68
+ npm install @respectify/client drizzle-orm pg
69
+ npm install -D drizzle-kit @types/pg
70
+ ```
71
+
72
+ For SQLite (libSQL or Turso):
73
+
74
+ ```bash
75
+ npm install @respectify/client drizzle-orm @libsql/client
76
+ npm install -D drizzle-kit
77
+ ```
78
+
79
+ ### 4. Set your environment variables
80
+
81
+ ```env
82
+ RESPECTIFY_EMAIL=you@example.com
83
+ RESPECTIFY_API_KEY=your-api-key
84
+ DATABASE_URL=postgres://...
85
+ ```
86
+
87
+ For SQLite, `DATABASE_URL` is `file:local.db` or your `libsql://` URL, and a hosted database such as Turso also needs `DATABASE_AUTH_TOKEN`.
88
+
89
+ ### 5. Create the comment table
90
+
91
+ ```bash
92
+ npx drizzle-kit generate
93
+ npx drizzle-kit migrate
94
+ ```
95
+
96
+ ### 6. Add comments to your layout
97
+
98
+ ```astro
99
+ ---
100
+ import CommentSection from '@respectify/astro/components/CommentSection.astro';
101
+ ---
102
+
103
+ <CommentSection postSlug={post.id} />
104
+ ```
105
+
106
+ That's it. Comments are moderated by Respectify before they appear.
107
+
108
+ ## Manual setup
109
+
110
+ Everything `init` and `astro add` do can be done by hand. These are the same steps, written out.
111
+
36
112
  ### 1. Install
37
113
 
38
114
  Install the package, Drizzle, and the driver for your database. For Postgres with node-postgres:
@@ -105,14 +181,14 @@ export default defineConfig({
105
181
  DATABASE_URL: envField.string({ context: 'server', access: 'secret' }),
106
182
  },
107
183
  },
108
- integrations: [
109
- respectify({
110
- runtime: './src/respectify.runtime.ts',
111
- }),
112
- ],
184
+ integrations: [respectify()],
113
185
  });
114
186
  ```
115
187
 
188
+ `respectify()` loads the runtime module from `./src/respectify.runtime.ts`. If yours is somewhere else, say where: `respectify({ runtime: './src/lib/comments.runtime.ts' })`.
189
+
190
+ The `env.schema` entry is for the runtime module above, which imports `DATABASE_URL` from `astro:env/server`. The module `init` writes reads it with `getSecret('DATABASE_URL')`, which needs no schema entry.
191
+
116
192
  ### 5. Configure Respectify
117
193
 
118
194
  Copy a starter config to your project root:
@@ -156,8 +232,6 @@ import CommentSection from '@respectify/astro/components/CommentSection.astro';
156
232
  <CommentSection postSlug={post.id} />
157
233
  ```
158
234
 
159
- That's it. Comments are moderated by Respectify before they appear.
160
-
161
235
  ## Storage
162
236
 
163
237
  The actions, the comments API route and the moderation service depend only on the `ICommentStore` interface:
@@ -224,7 +298,7 @@ Override on `.rf-comments`:
224
298
 
225
299
  ```ts
226
300
  respectify({
227
- // Required: the module whose default export is defineRespectifyRuntime({ store, ... })
301
+ // The module whose default export is defineRespectifyRuntime({ store, ... }). This is the default.
228
302
  runtime: './src/respectify.runtime.ts',
229
303
 
230
304
  configPath: './respectify.config.json',
@@ -261,7 +335,7 @@ respectify({
261
335
  });
262
336
  ```
263
337
 
264
- The runtime module takes the store and the two optional post functions:
338
+ The runtime module takes the store, the two optional post functions, and two optional callbacks for the site owner:
265
339
 
266
340
  ```ts
267
341
  export default defineRespectifyRuntime({
@@ -272,6 +346,10 @@ export default defineRespectifyRuntime({
272
346
  // fetch getPostUrl. Useful for staged/preview/auth-gated content, or when the URL isn't
273
347
  // live yet right after deploy. Takes priority over getPostUrl.
274
348
  getPostContent: async (slug) => loadPostBody(slug),
349
+ // The free plan is used up: comments are now published unmoderated. Tell yourself.
350
+ onModerationStopped: async ({ reason, upgradeUrl, message, postSlug }) => sendAlert(message),
351
+ // A comment is waiting in your store with approved: false (see "Free plan" below)
352
+ onHeldForReview: async ({ reason, comment }) => sendAlert(`Comment ${comment.id} awaits review`),
275
353
  });
276
354
  ```
277
355
 
@@ -325,6 +403,18 @@ Spam, off-topic (`blockOffTopic`) and dogwhistle (`blockDogwhistles`) rejections
325
403
 
326
404
  `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
405
 
406
+ ### Free plan: revisions, running out, and held comments
407
+
408
+ 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.
409
+
410
+ **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.
411
+
412
+ **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.
413
+
414
+ **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.
415
+
416
+ The form's `respectify:comment-held` event fires when a comment is held; the comment list does not change.
417
+
328
418
  ### Admin delete (optional)
329
419
 
330
420
  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 +426,8 @@ Visitor submits comment
336
426
  → Astro Action (comments.submit)
337
427
  → Respectify megacall (configured checks: spam, score, relevance, dogwhistle, …)
338
428
  → If approved: store.create() saves it through your ICommentStore
429
+ → If sent back for revision: the browser keeps the revision token for the resubmission
430
+ → If held for review (free plan, fifth attempt): store.create() saves it with approved: false
339
431
  → Client refreshes comment list via GET /api/respectify/comments (store.listApproved())
340
432
  ```
341
433
 
@@ -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'));
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { runCli } from './cli.js';
4
+ import { NodeProjectFiles } from './project-files.js';
5
+ import { TerminalLogger, TerminalPrompter } from './terminal.js';
6
+ // The package root is two folders up from both src/cli and the compiled dist/cli
7
+ const defaultConfigJson = readFileSync(new URL('../../default-respectify.config.json', import.meta.url), 'utf8');
8
+ process.exitCode = await runCli(process.argv.slice(2), {
9
+ logger: new TerminalLogger(),
10
+ prompter: new TerminalPrompter(),
11
+ openProject: (folder) => new NodeProjectFiles(folder),
12
+ defaultConfigJson,
13
+ });
@@ -0,0 +1,98 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { z } from 'zod';
3
+ import { InitError, runInit } from './init.js';
4
+ import { DATABASE_KINDS } from './types.js';
5
+ export const USAGE = `Usage: npx @respectify/astro init [options]
6
+
7
+ Sets up Respectify comments in an Astro project: writes the runtime module, the config
8
+ file and the comment actions, and adds the comment table to your Drizzle schema.
9
+ Files that already exist are never overwritten.
10
+
11
+ Options:
12
+ --database <postgres|sqlite> The database your comments go in. Read from drizzle.config
13
+ when there is one, otherwise you are asked.
14
+ --cwd <folder> The project folder (default: the current folder)
15
+ -h, --help Show this help`;
16
+ const cliArgumentsSchema = z.object({
17
+ command: z.literal('init', { error: 'Unknown command. The only command is "init".' }),
18
+ database: z
19
+ .enum(DATABASE_KINDS, { error: `--database must be one of: ${DATABASE_KINDS.join(', ')}` })
20
+ .optional(),
21
+ cwd: z.string().min(1).default('.'),
22
+ });
23
+ const STEP_LABELS = {
24
+ created: 'Created ',
25
+ updated: 'Updated ',
26
+ unchanged: 'Kept ',
27
+ manual: 'By hand ',
28
+ };
29
+ function describeStep(step) {
30
+ const line = ` ${STEP_LABELS[step.status]} ${step.path}`;
31
+ return step.status === 'unchanged' ? `${line} (already there)` : line;
32
+ }
33
+ /** Say what was done, then what is left to do. */
34
+ function report(result, logger) {
35
+ logger.info(`Respectify comments, stored in ${result.database === 'postgres' ? 'Postgres' : 'SQLite'}:\n`);
36
+ for (const step of result.steps)
37
+ logger.info(describeStep(step));
38
+ const manualSteps = result.steps.flatMap((step) => (step.instructions === undefined ? [] : [step.instructions]));
39
+ const remaining = [...manualSteps, ...result.nextSteps];
40
+ logger.info('\nWhat is left to do:');
41
+ remaining.forEach((step, index) => {
42
+ logger.info(`\n${index + 1}. ${step}`);
43
+ });
44
+ logger.info('\nDocs: https://docs.respectify.ai/docs/astro');
45
+ }
46
+ /**
47
+ * Run the command line.
48
+ * @param argv the arguments after the program name
49
+ * @returns the process exit code
50
+ */
51
+ export async function runCli(argv, dependencies) {
52
+ const { logger, prompter, openProject, defaultConfigJson } = dependencies;
53
+ let parsed;
54
+ try {
55
+ parsed = parseCommandLine(argv);
56
+ }
57
+ catch (error) {
58
+ logger.error(error instanceof Error ? error.message : String(error));
59
+ logger.info(`\n${USAGE}`);
60
+ return 1;
61
+ }
62
+ if (parsed.values.help === true || parsed.positionals.length === 0) {
63
+ logger.info(USAGE);
64
+ return parsed.values.help === true ? 0 : 1;
65
+ }
66
+ const validated = cliArgumentsSchema.safeParse({
67
+ command: parsed.positionals[0],
68
+ database: parsed.values.database,
69
+ cwd: parsed.values.cwd,
70
+ });
71
+ if (!validated.success) {
72
+ logger.error(validated.error.issues.map((issue) => issue.message).join('; '));
73
+ logger.info(`\n${USAGE}`);
74
+ return 1;
75
+ }
76
+ try {
77
+ const result = await runInit({ database: validated.data.database }, { files: openProject(validated.data.cwd), prompter, defaultConfigJson });
78
+ report(result, logger);
79
+ return 0;
80
+ }
81
+ catch (error) {
82
+ if (!(error instanceof InitError))
83
+ throw error;
84
+ logger.error(error.message);
85
+ return 1;
86
+ }
87
+ }
88
+ function parseCommandLine(argv) {
89
+ return parseArgs({
90
+ args: [...argv],
91
+ allowPositionals: true,
92
+ options: {
93
+ database: { type: 'string' },
94
+ cwd: { type: 'string' },
95
+ help: { type: 'boolean', short: 'h' },
96
+ },
97
+ });
98
+ }
@@ -0,0 +1,225 @@
1
+ import path from 'node:path';
2
+ import { z } from 'zod';
3
+ import { ACTIONS_MANUAL_INSTRUCTIONS, COMPONENT_SNIPPET, ENVIRONMENT_VARIABLES, REQUIRED_PACKAGES, SCAFFOLD_PATHS, actionsTemplate, drizzleConfigTemplate, runtimeTemplate, schemaExportLine, schemaTemplate, } from './templates.js';
4
+ /** A problem the person running the command can fix, reported without a stack trace. */
5
+ export class InitError extends Error {
6
+ name = 'InitError';
7
+ }
8
+ const PACKAGE_JSON = 'package.json';
9
+ const ASTRO_CONFIG_FILES = [
10
+ 'astro.config.ts',
11
+ 'astro.config.mjs',
12
+ 'astro.config.js',
13
+ 'astro.config.mts',
14
+ 'astro.config.cjs',
15
+ ];
16
+ const DRIZZLE_CONFIG_FILES = [
17
+ 'drizzle.config.ts',
18
+ 'drizzle.config.js',
19
+ 'drizzle.config.mjs',
20
+ 'drizzle.config.mts',
21
+ 'drizzle.config.cjs',
22
+ ];
23
+ /** The places Astro looks for a site's actions. */
24
+ const ACTIONS_FILES = [
25
+ 'src/actions/index.ts',
26
+ 'src/actions/index.js',
27
+ 'src/actions/index.mjs',
28
+ 'src/actions.ts',
29
+ 'src/actions.js',
30
+ ];
31
+ /** A schema that is one source file, which a line can be added to. */
32
+ const SCHEMA_SOURCE_FILE = /\.(?:ts|mts|js|mjs)$/;
33
+ /** Which database each drizzle-kit dialect means to this package. Other dialects are not supported. */
34
+ const DIALECT_DATABASE = {
35
+ postgresql: 'postgres',
36
+ sqlite: 'sqlite',
37
+ turso: 'sqlite',
38
+ };
39
+ const packageJsonSchema = z.object({
40
+ dependencies: z.record(z.string(), z.string()).optional(),
41
+ devDependencies: z.record(z.string(), z.string()).optional(),
42
+ });
43
+ const PACKAGE_MANAGERS = [
44
+ { lockFiles: ['pnpm-lock.yaml'], commands: { install: 'pnpm add', installDev: 'pnpm add -D', run: 'pnpm exec' } },
45
+ { lockFiles: ['yarn.lock'], commands: { install: 'yarn add', installDev: 'yarn add -D', run: 'yarn' } },
46
+ { lockFiles: ['bun.lock', 'bun.lockb'], commands: { install: 'bun add', installDev: 'bun add -d', run: 'bunx' } },
47
+ ];
48
+ const NPM_COMMANDS = { install: 'npm install', installDev: 'npm install -D', run: 'npx' };
49
+ /** The first of the candidate files that exists in the project. */
50
+ function findFirst(files, candidates) {
51
+ return candidates.find((candidate) => files.exists(candidate));
52
+ }
53
+ /** The package manager the project uses, judged by its lock file. npm when there is none. */
54
+ function detectPackageManager(files) {
55
+ const found = PACKAGE_MANAGERS.find((manager) => manager.lockFiles.some((lockFile) => files.exists(lockFile)));
56
+ return found?.commands ?? NPM_COMMANDS;
57
+ }
58
+ /** The names of every package the project already depends on. */
59
+ function readInstalledPackages(files) {
60
+ let parsed;
61
+ try {
62
+ parsed = packageJsonSchema.parse(JSON.parse(files.read(PACKAGE_JSON)));
63
+ }
64
+ catch (error) {
65
+ const reason = error instanceof Error ? error.message : String(error);
66
+ throw new InitError(`Could not read ${PACKAGE_JSON}: ${reason}`);
67
+ }
68
+ return new Set([...Object.keys(parsed.dependencies ?? {}), ...Object.keys(parsed.devDependencies ?? {})]);
69
+ }
70
+ /** True for a relative path that stays inside the project folder. */
71
+ function isInsideProject(relativePath) {
72
+ const segments = relativePath.split(/[\\/]/);
73
+ return !path.isAbsolute(relativePath) && !segments.includes('..');
74
+ }
75
+ /** Read the dialect and schema file out of a drizzle-kit config without running it. */
76
+ function readDrizzleConfig(files) {
77
+ const path = findFirst(files, DRIZZLE_CONFIG_FILES);
78
+ if (path === undefined)
79
+ return undefined;
80
+ const source = files.read(path);
81
+ const dialect = /\bdialect\s*:\s*(['"`])([a-z]+)\1/.exec(source)?.[2];
82
+ const schema = /\bschema\s*:\s*(['"`])([^'"`]+)\1/.exec(source)?.[2];
83
+ // Only a single source file inside the project can have a line added to it
84
+ const schemaFile = schema !== undefined && !schema.includes('*') && SCHEMA_SOURCE_FILE.test(schema) && isInsideProject(schema)
85
+ ? schema.replace(/^\.\//, '')
86
+ : undefined;
87
+ return {
88
+ path,
89
+ dialect,
90
+ database: dialect === undefined ? undefined : DIALECT_DATABASE[dialect],
91
+ schemaFile,
92
+ };
93
+ }
94
+ /** The database to scaffold for: the one asked for, else the project's own, else the person's answer. */
95
+ async function resolveDatabase(options, drizzleConfig, { prompter }) {
96
+ if (options.database !== undefined)
97
+ return options.database;
98
+ if (drizzleConfig?.database !== undefined)
99
+ return drizzleConfig.database;
100
+ if (!prompter.interactive) {
101
+ throw new InitError('Say which database your comments go in: --database postgres or --database sqlite');
102
+ }
103
+ return prompter.choose('Which database will store your comments?', [
104
+ { value: 'postgres', label: 'Postgres' },
105
+ { value: 'sqlite', label: 'SQLite (libSQL or Turso)' },
106
+ ]);
107
+ }
108
+ /** Write a file unless it already exists. */
109
+ function createIfMissing(files, path, content) {
110
+ if (files.exists(path))
111
+ return { status: 'unchanged', path };
112
+ files.create(path, content);
113
+ return { status: 'created', path };
114
+ }
115
+ /** Expose the comment actions: in a new actions file, or by telling the person what to add to theirs. */
116
+ function scaffoldActions(files) {
117
+ const existing = findFirst(files, ACTIONS_FILES);
118
+ if (existing === undefined)
119
+ return createIfMissing(files, SCAFFOLD_PATHS.actions, actionsTemplate());
120
+ if (files.read(existing).includes('respectifyCommentActions'))
121
+ return { status: 'unchanged', path: existing };
122
+ return { status: 'manual', path: existing, instructions: ACTIONS_MANUAL_INSTRUCTIONS };
123
+ }
124
+ /** Make sure a schema file exports the comment table, adding the line when it is missing. */
125
+ function addTableToSchema(files, path, database) {
126
+ if (!files.exists(path)) {
127
+ files.create(path, schemaTemplate(database));
128
+ return { status: 'created', path };
129
+ }
130
+ const source = files.read(path);
131
+ if (source.includes('@respectify/astro/'))
132
+ return { status: 'unchanged', path };
133
+ const separator = source === '' || source.endsWith('\n') ? '' : '\n';
134
+ files.append(path, `${separator}${schemaExportLine(database)}\n`);
135
+ return { status: 'updated', path };
136
+ }
137
+ /**
138
+ * Put the comment table in the project's Drizzle schema. A project with no drizzle-kit config
139
+ * gets one; a project with its own keeps it, and gets the table added to the schema it names.
140
+ */
141
+ function scaffoldDrizzle(files, database, drizzleConfig) {
142
+ if (drizzleConfig === undefined) {
143
+ return [
144
+ addTableToSchema(files, SCAFFOLD_PATHS.schema, database),
145
+ createIfMissing(files, SCAFFOLD_PATHS.drizzleConfig, drizzleConfigTemplate(database)),
146
+ ];
147
+ }
148
+ const exportLine = schemaExportLine(database);
149
+ if (drizzleConfig.dialect !== undefined && drizzleConfig.database !== database) {
150
+ return [
151
+ {
152
+ status: 'manual',
153
+ path: drizzleConfig.path,
154
+ instructions: `${drizzleConfig.path} is set up for "${drizzleConfig.dialect}", not ${database}, so the comment table ` +
155
+ `was not added to it. Give the comment table its own drizzle-kit config, with a schema containing:\n\n ${exportLine}`,
156
+ },
157
+ ];
158
+ }
159
+ if (drizzleConfig.schemaFile === undefined) {
160
+ return [
161
+ {
162
+ status: 'manual',
163
+ path: drizzleConfig.path,
164
+ instructions: `Add the comment table to your Drizzle schema:\n\n ${exportLine}`,
165
+ },
166
+ ];
167
+ }
168
+ return [addTableToSchema(files, drizzleConfig.schemaFile, database)];
169
+ }
170
+ /** Everything the command leaves for the person, in the order to do it. */
171
+ function describeNextSteps(files, database, project) {
172
+ const commands = detectPackageManager(files);
173
+ const { installed, astroConfig, astroConfigPath } = project;
174
+ const steps = [];
175
+ const required = REQUIRED_PACKAGES[database];
176
+ const missing = required.runtime.filter((name) => !installed.has(name));
177
+ const missingDev = required.dev.filter((name) => !installed.has(name));
178
+ const installLines = [
179
+ ...(missing.length > 0 ? [`${commands.install} ${missing.join(' ')}`] : []),
180
+ ...(missingDev.length > 0 ? [`${commands.installDev} ${missingDev.join(' ')}`] : []),
181
+ ];
182
+ if (installLines.length > 0) {
183
+ steps.push(`Install the database packages:\n\n ${installLines.join('\n ')}`);
184
+ }
185
+ if (!astroConfig.includes('@respectify/astro')) {
186
+ steps.push(`Add the integration to ${astroConfigPath}:\n\n ${commands.run} astro add @respectify/astro`);
187
+ }
188
+ if (!/\badapter\s*:/.test(astroConfig)) {
189
+ steps.push('Comments are saved by your server, so the site needs a server adapter. For Node:\n\n' +
190
+ ` ${commands.run} astro add node\n\n` +
191
+ 'Vercel, Netlify and Cloudflare have adapters too.');
192
+ }
193
+ steps.push(`Set these environment variables (in .env for local work):\n\n ${ENVIRONMENT_VARIABLES[database].join('\n ')}`);
194
+ steps.push(`Create the comment table:\n\n ${commands.run} drizzle-kit generate\n ${commands.run} drizzle-kit migrate`);
195
+ steps.push(`Put comments on a page, for example in your blog post layout:\n\n ${COMPONENT_SNIPPET.split('\n').join('\n ')}`);
196
+ return steps;
197
+ }
198
+ /**
199
+ * Scaffold the files a site needs for Respectify comments: the runtime module, the config
200
+ * file, the comment actions and the comment table in the Drizzle schema. A file that already
201
+ * exists is never overwritten.
202
+ * @throws InitError when the folder is not an Astro project or the database cannot be decided
203
+ */
204
+ export async function runInit(options, dependencies) {
205
+ const { files, defaultConfigJson } = dependencies;
206
+ const astroConfigPath = findFirst(files, ASTRO_CONFIG_FILES);
207
+ if (!files.exists(PACKAGE_JSON) || astroConfigPath === undefined) {
208
+ throw new InitError('Run this in the root folder of an Astro project: no package.json and astro.config found here.');
209
+ }
210
+ // Everything that can fail is read before the first file is written
211
+ const project = {
212
+ astroConfigPath,
213
+ astroConfig: files.read(astroConfigPath),
214
+ installed: readInstalledPackages(files),
215
+ };
216
+ const drizzleConfig = readDrizzleConfig(files);
217
+ const database = await resolveDatabase(options, drizzleConfig, dependencies);
218
+ const steps = [
219
+ createIfMissing(files, SCAFFOLD_PATHS.runtime, runtimeTemplate(database)),
220
+ createIfMissing(files, SCAFFOLD_PATHS.config, defaultConfigJson),
221
+ scaffoldActions(files),
222
+ ...scaffoldDrizzle(files, database, drizzleConfig),
223
+ ];
224
+ return { database, steps, nextSteps: describeNextSteps(files, database, project) };
225
+ }
@@ -0,0 +1,38 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /** The files of a project on disk. */
4
+ export class NodeProjectFiles {
5
+ root;
6
+ constructor(root) {
7
+ this.root = path.resolve(root);
8
+ }
9
+ exists(relativePath) {
10
+ const resolved = this.tryResolve(relativePath);
11
+ return resolved !== undefined && fs.existsSync(resolved) && fs.statSync(resolved).isFile();
12
+ }
13
+ read(relativePath) {
14
+ return fs.readFileSync(this.resolve(relativePath), 'utf8');
15
+ }
16
+ create(relativePath, content) {
17
+ const resolved = this.resolve(relativePath);
18
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
19
+ // 'wx' fails when the file exists, so a file is never overwritten even in a race
20
+ fs.writeFileSync(resolved, content, { encoding: 'utf8', flag: 'wx' });
21
+ }
22
+ append(relativePath, content) {
23
+ fs.appendFileSync(this.resolve(relativePath), content, 'utf8');
24
+ }
25
+ /** The absolute path, or undefined when it would leave the project. */
26
+ tryResolve(relativePath) {
27
+ const resolved = path.resolve(this.root, relativePath);
28
+ const inside = resolved === this.root || resolved.startsWith(`${this.root}${path.sep}`);
29
+ return inside ? resolved : undefined;
30
+ }
31
+ resolve(relativePath) {
32
+ const resolved = this.tryResolve(relativePath);
33
+ if (resolved === undefined) {
34
+ throw new Error(`${relativePath} is outside the project folder`);
35
+ }
36
+ return resolved;
37
+ }
38
+ }