@respectify/astro 1.1.0 → 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 +81 -8
- package/dist/cli/bin.js +13 -0
- package/dist/cli/cli.js +98 -0
- package/dist/cli/init.js +225 -0
- package/dist/cli/project-files.js +38 -0
- package/dist/cli/templates.js +142 -0
- package/dist/cli/terminal.js +35 -0
- package/dist/cli/types.js +2 -0
- package/package.json +9 -3
- package/src/cli/bin.ts +15 -0
- package/src/cli/cli.ts +120 -0
- package/src/cli/init.ts +311 -0
- package/src/cli/project-files.ts +47 -0
- package/src/cli/templates.ts +158 -0
- package/src/cli/terminal.ts +39 -0
- package/src/cli/types.ts +89 -0
- package/src/index.ts +3 -2
- package/src/options.ts +7 -1
- package/src/types.ts +2 -1
package/README.md
CHANGED
|
@@ -34,6 +34,81 @@ Built for production — powers [nickhodges.com](https://nickhodges.com) as a li
|
|
|
34
34
|
|
|
35
35
|
## Quick start
|
|
36
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
|
+
|
|
37
112
|
### 1. Install
|
|
38
113
|
|
|
39
114
|
Install the package, Drizzle, and the driver for your database. For Postgres with node-postgres:
|
|
@@ -106,14 +181,14 @@ export default defineConfig({
|
|
|
106
181
|
DATABASE_URL: envField.string({ context: 'server', access: 'secret' }),
|
|
107
182
|
},
|
|
108
183
|
},
|
|
109
|
-
integrations: [
|
|
110
|
-
respectify({
|
|
111
|
-
runtime: './src/respectify.runtime.ts',
|
|
112
|
-
}),
|
|
113
|
-
],
|
|
184
|
+
integrations: [respectify()],
|
|
114
185
|
});
|
|
115
186
|
```
|
|
116
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
|
+
|
|
117
192
|
### 5. Configure Respectify
|
|
118
193
|
|
|
119
194
|
Copy a starter config to your project root:
|
|
@@ -157,8 +232,6 @@ import CommentSection from '@respectify/astro/components/CommentSection.astro';
|
|
|
157
232
|
<CommentSection postSlug={post.id} />
|
|
158
233
|
```
|
|
159
234
|
|
|
160
|
-
That's it. Comments are moderated by Respectify before they appear.
|
|
161
|
-
|
|
162
235
|
## Storage
|
|
163
236
|
|
|
164
237
|
The actions, the comments API route and the moderation service depend only on the `ICommentStore` interface:
|
|
@@ -225,7 +298,7 @@ Override on `.rf-comments`:
|
|
|
225
298
|
|
|
226
299
|
```ts
|
|
227
300
|
respectify({
|
|
228
|
-
//
|
|
301
|
+
// The module whose default export is defineRespectifyRuntime({ store, ... }). This is the default.
|
|
229
302
|
runtime: './src/respectify.runtime.ts',
|
|
230
303
|
|
|
231
304
|
configPath: './respectify.config.json',
|
package/dist/cli/bin.js
ADDED
|
@@ -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
|
+
});
|
package/dist/cli/cli.js
ADDED
|
@@ -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
|
+
}
|
package/dist/cli/init.js
ADDED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/** Where `init` puts each file, relative to the project root. */
|
|
2
|
+
export const SCAFFOLD_PATHS = {
|
|
3
|
+
runtime: 'src/respectify.runtime.ts',
|
|
4
|
+
config: 'respectify.config.json',
|
|
5
|
+
actions: 'src/actions/index.ts',
|
|
6
|
+
schema: 'src/db/schema.ts',
|
|
7
|
+
drizzleConfig: 'drizzle.config.ts',
|
|
8
|
+
};
|
|
9
|
+
/** The package subpath that exports the comment table and store for each database. */
|
|
10
|
+
const ADAPTER_ENTRY = {
|
|
11
|
+
postgres: '@respectify/astro/postgres',
|
|
12
|
+
sqlite: '@respectify/astro/sqlite',
|
|
13
|
+
};
|
|
14
|
+
/** The line a Drizzle schema needs so drizzle-kit creates the comment table. */
|
|
15
|
+
export function schemaExportLine(database) {
|
|
16
|
+
return `export { respectifyComments } from '${ADAPTER_ENTRY[database]}';`;
|
|
17
|
+
}
|
|
18
|
+
/** A new Drizzle schema file holding only the comment table. */
|
|
19
|
+
export function schemaTemplate(database) {
|
|
20
|
+
return `// The table Respectify comments are stored in. Add your own tables to this file too.
|
|
21
|
+
${schemaExportLine(database)}
|
|
22
|
+
`;
|
|
23
|
+
}
|
|
24
|
+
const POSTGRES_RUNTIME = `import { defineRespectifyRuntime } from '@respectify/astro/runtime';
|
|
25
|
+
import { createPostgresCommentStore } from '@respectify/astro/postgres';
|
|
26
|
+
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
27
|
+
import { Pool } from 'pg';
|
|
28
|
+
import { getSecret } from 'astro:env/server';
|
|
29
|
+
|
|
30
|
+
const connectionString = getSecret('DATABASE_URL');
|
|
31
|
+
if (!connectionString) {
|
|
32
|
+
throw new Error('DATABASE_URL is not set. Respectify comments need it to reach your database.');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// If your site already creates a Drizzle database, import it here and delete these lines.
|
|
36
|
+
const db = drizzle({ client: new Pool({ connectionString }) });
|
|
37
|
+
|
|
38
|
+
export default defineRespectifyRuntime({
|
|
39
|
+
store: createPostgresCommentStore(db),
|
|
40
|
+
// Optional: the public URL of a post, which Respectify reads for topic context
|
|
41
|
+
// getPostUrl: (slug, site) => \`\${site}/blog/\${slug}/\`,
|
|
42
|
+
});
|
|
43
|
+
`;
|
|
44
|
+
const SQLITE_RUNTIME = `import { defineRespectifyRuntime } from '@respectify/astro/runtime';
|
|
45
|
+
import { createSqliteCommentStore } from '@respectify/astro/sqlite';
|
|
46
|
+
import { drizzle } from 'drizzle-orm/libsql';
|
|
47
|
+
import { createClient } from '@libsql/client';
|
|
48
|
+
import { getSecret } from 'astro:env/server';
|
|
49
|
+
|
|
50
|
+
const url = getSecret('DATABASE_URL');
|
|
51
|
+
if (!url) {
|
|
52
|
+
throw new Error('DATABASE_URL is not set. Respectify comments need it to reach your database.');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Only a hosted database such as Turso needs a token; an empty one counts as none
|
|
56
|
+
const authToken = getSecret('DATABASE_AUTH_TOKEN') || undefined;
|
|
57
|
+
|
|
58
|
+
// If your site already creates a Drizzle database, import it here and delete these lines.
|
|
59
|
+
const db = drizzle({ client: createClient({ url, authToken }) });
|
|
60
|
+
|
|
61
|
+
export default defineRespectifyRuntime({
|
|
62
|
+
store: createSqliteCommentStore(db),
|
|
63
|
+
// Optional: the public URL of a post, which Respectify reads for topic context
|
|
64
|
+
// getPostUrl: (slug, site) => \`\${site}/blog/\${slug}/\`,
|
|
65
|
+
});
|
|
66
|
+
`;
|
|
67
|
+
/** The runtime module: it builds the comment store from the site's database connection. */
|
|
68
|
+
export function runtimeTemplate(database) {
|
|
69
|
+
return database === 'postgres' ? POSTGRES_RUNTIME : SQLITE_RUNTIME;
|
|
70
|
+
}
|
|
71
|
+
/** The lines an existing actions file needs. */
|
|
72
|
+
export const ACTIONS_MANUAL_INSTRUCTIONS = `Add the comment actions to your existing actions:
|
|
73
|
+
|
|
74
|
+
import { respectifyCommentActions } from '@respectify/astro/actions';
|
|
75
|
+
|
|
76
|
+
export const server = {
|
|
77
|
+
// ...your actions
|
|
78
|
+
comments: respectifyCommentActions,
|
|
79
|
+
};`;
|
|
80
|
+
/** A new Astro Actions file exposing the comment actions. */
|
|
81
|
+
export function actionsTemplate() {
|
|
82
|
+
return `import { respectifyCommentActions } from '@respectify/astro/actions';
|
|
83
|
+
|
|
84
|
+
export const server = {
|
|
85
|
+
comments: respectifyCommentActions,
|
|
86
|
+
};
|
|
87
|
+
`;
|
|
88
|
+
}
|
|
89
|
+
const DRIZZLE_CONFIG_HEAD = `import { existsSync } from 'node:fs';
|
|
90
|
+
import { defineConfig } from 'drizzle-kit';
|
|
91
|
+
|
|
92
|
+
// drizzle-kit does not read .env by itself
|
|
93
|
+
if (existsSync('.env')) process.loadEnvFile('.env');
|
|
94
|
+
|
|
95
|
+
const url = process.env.DATABASE_URL;
|
|
96
|
+
if (!url) {
|
|
97
|
+
throw new Error('Set DATABASE_URL before running drizzle-kit.');
|
|
98
|
+
}
|
|
99
|
+
`;
|
|
100
|
+
/** A new drizzle-kit config pointing at the schema file `init` writes. */
|
|
101
|
+
export function drizzleConfigTemplate(database) {
|
|
102
|
+
const dialect = database === 'postgres' ? 'postgresql' : 'turso';
|
|
103
|
+
// drizzle-kit rejects an empty token, so an empty DATABASE_AUTH_TOKEN counts as none
|
|
104
|
+
const credentials = database === 'postgres' ? '{ url }' : '{ url, authToken: process.env.DATABASE_AUTH_TOKEN || undefined }';
|
|
105
|
+
return `${DRIZZLE_CONFIG_HEAD}
|
|
106
|
+
export default defineConfig({
|
|
107
|
+
dialect: '${dialect}',
|
|
108
|
+
schema: './${SCAFFOLD_PATHS.schema}',
|
|
109
|
+
out: './drizzle',
|
|
110
|
+
dbCredentials: ${credentials},
|
|
111
|
+
});
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
/** The packages each database needs beside `@respectify/astro` itself. */
|
|
115
|
+
export const REQUIRED_PACKAGES = {
|
|
116
|
+
postgres: { runtime: ['@respectify/client', 'drizzle-orm', 'pg'], dev: ['drizzle-kit', '@types/pg'] },
|
|
117
|
+
sqlite: { runtime: ['@respectify/client', 'drizzle-orm', '@libsql/client'], dev: ['drizzle-kit'] },
|
|
118
|
+
};
|
|
119
|
+
/** The lines shown for the environment variables each database's runtime module reads, with sample values. */
|
|
120
|
+
export const ENVIRONMENT_VARIABLES = {
|
|
121
|
+
postgres: [
|
|
122
|
+
'RESPECTIFY_EMAIL=you@example.com',
|
|
123
|
+
'RESPECTIFY_API_KEY=your-api-key',
|
|
124
|
+
'DATABASE_URL=postgres://user:password@host:5432/database',
|
|
125
|
+
],
|
|
126
|
+
sqlite: [
|
|
127
|
+
'RESPECTIFY_EMAIL=you@example.com',
|
|
128
|
+
'RESPECTIFY_API_KEY=your-api-key',
|
|
129
|
+
'DATABASE_URL=file:local.db',
|
|
130
|
+
'',
|
|
131
|
+
'For a hosted database such as Turso, use its URL and token instead:',
|
|
132
|
+
'',
|
|
133
|
+
'DATABASE_URL=libsql://your-database.turso.io',
|
|
134
|
+
'DATABASE_AUTH_TOKEN=your-database-token',
|
|
135
|
+
],
|
|
136
|
+
};
|
|
137
|
+
/** The snippet that puts comments on a page. */
|
|
138
|
+
export const COMPONENT_SNIPPET = `---
|
|
139
|
+
import CommentSection from '@respectify/astro/components/CommentSection.astro';
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
<CommentSection postSlug={post.id} />`;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline/promises';
|
|
2
|
+
/** Writes messages to the terminal: information to stdout, warnings and errors to stderr. */
|
|
3
|
+
export class TerminalLogger {
|
|
4
|
+
info(message) {
|
|
5
|
+
process.stdout.write(`${message}\n`);
|
|
6
|
+
}
|
|
7
|
+
warn(message) {
|
|
8
|
+
process.stderr.write(`Warning: ${message}\n`);
|
|
9
|
+
}
|
|
10
|
+
error(message) {
|
|
11
|
+
process.stderr.write(`Error: ${message}\n`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Asks questions on the terminal, when there is one. */
|
|
15
|
+
export class TerminalPrompter {
|
|
16
|
+
get interactive() {
|
|
17
|
+
return process.stdin.isTTY === true && process.stdout.isTTY === true;
|
|
18
|
+
}
|
|
19
|
+
async choose(question, choices) {
|
|
20
|
+
const readline = createInterface({ input: process.stdin, output: process.stdout });
|
|
21
|
+
try {
|
|
22
|
+
const menu = choices.map((choice, index) => ` ${index + 1}. ${choice.label}`).join('\n');
|
|
23
|
+
for (;;) {
|
|
24
|
+
const answer = (await readline.question(`${question}\n${menu}\n> `)).trim().toLowerCase();
|
|
25
|
+
const picked = choices[Number(answer) - 1] ?? choices.find((choice) => choice.value === answer);
|
|
26
|
+
if (picked !== undefined)
|
|
27
|
+
return picked.value;
|
|
28
|
+
process.stdout.write(`Enter a number from 1 to ${choices.length}.\n`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
readline.close();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|