@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/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@respectify/astro",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Respectify-powered commenting for Astro
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Respectify-powered commenting for Astro \u2014 AI moderation, spam filtering, and beautiful UX out of the box.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Respectify",
|
|
@@ -41,10 +41,14 @@
|
|
|
41
41
|
"./sqlite": "./src/adapters/sqlite/index.ts",
|
|
42
42
|
"./testing": "./src/testing/index.ts"
|
|
43
43
|
},
|
|
44
|
+
"bin": {
|
|
45
|
+
"respectify-astro": "./dist/cli/bin.js"
|
|
46
|
+
},
|
|
44
47
|
"files": [
|
|
45
48
|
"src",
|
|
46
49
|
"components",
|
|
47
50
|
"client",
|
|
51
|
+
"dist",
|
|
48
52
|
"migrations",
|
|
49
53
|
"drizzle",
|
|
50
54
|
"default-respectify.config.json",
|
|
@@ -77,7 +81,9 @@
|
|
|
77
81
|
"zod": "^4.6.6"
|
|
78
82
|
},
|
|
79
83
|
"scripts": {
|
|
80
|
-
"typecheck": "tsc --noEmit",
|
|
84
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.cli.json --noEmit",
|
|
85
|
+
"build:cli": "tsc -p tsconfig.cli.json",
|
|
86
|
+
"prepack": "npm run build:cli",
|
|
81
87
|
"test": "vitest run",
|
|
82
88
|
"migrations:generate": "drizzle-kit generate --config drizzle/postgres.config.ts && drizzle-kit generate --config drizzle/sqlite.config.ts"
|
|
83
89
|
},
|
package/src/cli/bin.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
|
|
7
|
+
// The package root is two folders up from both src/cli and the compiled dist/cli
|
|
8
|
+
const defaultConfigJson = readFileSync(new URL('../../default-respectify.config.json', import.meta.url), 'utf8');
|
|
9
|
+
|
|
10
|
+
process.exitCode = await runCli(process.argv.slice(2), {
|
|
11
|
+
logger: new TerminalLogger(),
|
|
12
|
+
prompter: new TerminalPrompter(),
|
|
13
|
+
openProject: (folder) => new NodeProjectFiles(folder),
|
|
14
|
+
defaultConfigJson,
|
|
15
|
+
});
|
package/src/cli/cli.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
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
|
+
import type { ICliLogger, IPrompter, IProjectFiles, InitResult, InitStep, InitStepStatus } from './types.js';
|
|
6
|
+
|
|
7
|
+
export const USAGE = `Usage: npx @respectify/astro init [options]
|
|
8
|
+
|
|
9
|
+
Sets up Respectify comments in an Astro project: writes the runtime module, the config
|
|
10
|
+
file and the comment actions, and adds the comment table to your Drizzle schema.
|
|
11
|
+
Files that already exist are never overwritten.
|
|
12
|
+
|
|
13
|
+
Options:
|
|
14
|
+
--database <postgres|sqlite> The database your comments go in. Read from drizzle.config
|
|
15
|
+
when there is one, otherwise you are asked.
|
|
16
|
+
--cwd <folder> The project folder (default: the current folder)
|
|
17
|
+
-h, --help Show this help`;
|
|
18
|
+
|
|
19
|
+
const cliArgumentsSchema = z.object({
|
|
20
|
+
command: z.literal('init', { error: 'Unknown command. The only command is "init".' }),
|
|
21
|
+
database: z
|
|
22
|
+
.enum(DATABASE_KINDS, { error: `--database must be one of: ${DATABASE_KINDS.join(', ')}` })
|
|
23
|
+
.optional(),
|
|
24
|
+
cwd: z.string().min(1).default('.'),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/** What the command needs from the outside world. */
|
|
28
|
+
export interface CliDependencies {
|
|
29
|
+
logger: ICliLogger;
|
|
30
|
+
prompter: IPrompter;
|
|
31
|
+
/** Opens the project in a folder. */
|
|
32
|
+
openProject: (folder: string) => IProjectFiles;
|
|
33
|
+
/** The text of the package's default-respectify.config.json. */
|
|
34
|
+
defaultConfigJson: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const STEP_LABELS: Record<InitStepStatus, string> = {
|
|
38
|
+
created: 'Created ',
|
|
39
|
+
updated: 'Updated ',
|
|
40
|
+
unchanged: 'Kept ',
|
|
41
|
+
manual: 'By hand ',
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
function describeStep(step: InitStep): string {
|
|
45
|
+
const line = ` ${STEP_LABELS[step.status]} ${step.path}`;
|
|
46
|
+
return step.status === 'unchanged' ? `${line} (already there)` : line;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Say what was done, then what is left to do. */
|
|
50
|
+
function report(result: InitResult, logger: ICliLogger): void {
|
|
51
|
+
logger.info(`Respectify comments, stored in ${result.database === 'postgres' ? 'Postgres' : 'SQLite'}:\n`);
|
|
52
|
+
for (const step of result.steps) logger.info(describeStep(step));
|
|
53
|
+
|
|
54
|
+
const manualSteps = result.steps.flatMap((step) => (step.instructions === undefined ? [] : [step.instructions]));
|
|
55
|
+
const remaining = [...manualSteps, ...result.nextSteps];
|
|
56
|
+
logger.info('\nWhat is left to do:');
|
|
57
|
+
remaining.forEach((step, index) => {
|
|
58
|
+
logger.info(`\n${index + 1}. ${step}`);
|
|
59
|
+
});
|
|
60
|
+
logger.info('\nDocs: https://docs.respectify.ai/docs/astro');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Run the command line.
|
|
65
|
+
* @param argv the arguments after the program name
|
|
66
|
+
* @returns the process exit code
|
|
67
|
+
*/
|
|
68
|
+
export async function runCli(argv: readonly string[], dependencies: CliDependencies): Promise<number> {
|
|
69
|
+
const { logger, prompter, openProject, defaultConfigJson } = dependencies;
|
|
70
|
+
|
|
71
|
+
let parsed: ReturnType<typeof parseCommandLine>;
|
|
72
|
+
try {
|
|
73
|
+
parsed = parseCommandLine(argv);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
logger.error(error instanceof Error ? error.message : String(error));
|
|
76
|
+
logger.info(`\n${USAGE}`);
|
|
77
|
+
return 1;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (parsed.values.help === true || parsed.positionals.length === 0) {
|
|
81
|
+
logger.info(USAGE);
|
|
82
|
+
return parsed.values.help === true ? 0 : 1;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const validated = cliArgumentsSchema.safeParse({
|
|
86
|
+
command: parsed.positionals[0],
|
|
87
|
+
database: parsed.values.database,
|
|
88
|
+
cwd: parsed.values.cwd,
|
|
89
|
+
});
|
|
90
|
+
if (!validated.success) {
|
|
91
|
+
logger.error(validated.error.issues.map((issue) => issue.message).join('; '));
|
|
92
|
+
logger.info(`\n${USAGE}`);
|
|
93
|
+
return 1;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
const result = await runInit(
|
|
98
|
+
{ database: validated.data.database },
|
|
99
|
+
{ files: openProject(validated.data.cwd), prompter, defaultConfigJson },
|
|
100
|
+
);
|
|
101
|
+
report(result, logger);
|
|
102
|
+
return 0;
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (!(error instanceof InitError)) throw error;
|
|
105
|
+
logger.error(error.message);
|
|
106
|
+
return 1;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function parseCommandLine(argv: readonly string[]) {
|
|
111
|
+
return parseArgs({
|
|
112
|
+
args: [...argv],
|
|
113
|
+
allowPositionals: true,
|
|
114
|
+
options: {
|
|
115
|
+
database: { type: 'string' },
|
|
116
|
+
cwd: { type: 'string' },
|
|
117
|
+
help: { type: 'boolean', short: 'h' },
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
}
|
package/src/cli/init.ts
ADDED
|
@@ -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} />`;
|