@codapult/cli 0.15.3 → 0.16.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.
Files changed (67) hide show
  1. package/README.md +107 -3
  2. package/dist/commands/config-show.js +6 -32
  3. package/dist/commands/db.d.ts +2 -0
  4. package/dist/commands/db.js +81 -2
  5. package/dist/commands/deploy.js +44 -17
  6. package/dist/commands/doctor.d.ts +1 -1
  7. package/dist/commands/doctor.js +9 -234
  8. package/dist/commands/env.js +21 -17
  9. package/dist/commands/mcp.d.ts +5 -0
  10. package/dist/commands/mcp.js +98 -0
  11. package/dist/commands/plugins.js +40 -5
  12. package/dist/commands/setup.js +2 -2
  13. package/dist/index.js +24 -5
  14. package/dist/mcp/resources.js +34 -3
  15. package/dist/mcp/server.js +4 -1
  16. package/dist/mcp/tools/db.js +185 -49
  17. package/dist/mcp/tools/db.test.js +59 -7
  18. package/dist/mcp/tools/env.d.ts +7 -0
  19. package/dist/mcp/tools/env.js +96 -2
  20. package/dist/mcp/tools/env.test.js +4 -2
  21. package/dist/mcp/tools/generate.js +64 -10
  22. package/dist/mcp/tools/plugins.js +125 -13
  23. package/dist/mcp/tools/project.js +59 -46
  24. package/dist/mcp/tools/project.test.js +20 -8
  25. package/dist/utils/check-report.d.ts +18 -0
  26. package/dist/utils/check-report.js +30 -0
  27. package/dist/utils/command.d.ts +18 -0
  28. package/dist/utils/command.js +29 -0
  29. package/dist/utils/config-report.d.ts +12 -0
  30. package/dist/utils/config-report.js +41 -0
  31. package/dist/utils/config-report.test.d.ts +1 -0
  32. package/dist/utils/config-report.test.js +20 -0
  33. package/dist/utils/db-diff.d.ts +11 -0
  34. package/dist/utils/db-diff.js +37 -0
  35. package/dist/utils/env-compatibility.d.ts +10 -0
  36. package/dist/utils/env-compatibility.js +52 -0
  37. package/dist/utils/env-compatibility.test.d.ts +1 -0
  38. package/dist/utils/env-compatibility.test.js +23 -0
  39. package/dist/utils/env-config.d.ts +9 -0
  40. package/dist/utils/env-config.js +116 -4
  41. package/dist/utils/env-schema-parser.d.ts +2 -0
  42. package/dist/utils/env-schema-parser.js +32 -0
  43. package/dist/utils/env-schema-parser.test.d.ts +1 -0
  44. package/dist/utils/env-schema-parser.test.js +11 -0
  45. package/dist/utils/health-render.d.ts +3 -0
  46. package/dist/utils/health-render.js +28 -0
  47. package/dist/utils/health-render.test.d.ts +1 -0
  48. package/dist/utils/health-render.test.js +18 -0
  49. package/dist/utils/health.d.ts +26 -0
  50. package/dist/utils/health.js +249 -0
  51. package/dist/utils/live-db-diff.d.ts +17 -0
  52. package/dist/utils/live-db-diff.js +131 -0
  53. package/dist/utils/live-db-diff.test.d.ts +1 -0
  54. package/dist/utils/live-db-diff.test.js +29 -0
  55. package/dist/utils/manifest.d.ts +1 -0
  56. package/dist/utils/patchers.d.ts +2 -0
  57. package/dist/utils/patchers.js +25 -13
  58. package/dist/utils/patchers.test.js +41 -7
  59. package/dist/utils/schema-parity.d.ts +15 -0
  60. package/dist/utils/schema-parity.js +91 -0
  61. package/dist/utils/schema-parity.test.d.ts +1 -0
  62. package/dist/utils/schema-parity.test.js +27 -0
  63. package/dist/utils/schema-parser.d.ts +12 -0
  64. package/dist/utils/schema-parser.js +130 -0
  65. package/dist/utils/schema-parser.test.d.ts +1 -0
  66. package/dist/utils/schema-parser.test.js +59 -0
  67. package/package.json +2 -2
@@ -0,0 +1,249 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { findPageBackups, findPageConflicts } from './patchers.js';
4
+ import { resolveManifest } from './manifest.js';
5
+ import { findProjectRoot, readJsonFile } from './project.js';
6
+ import { getProjectEnvOptions, loadProjectEnv } from './project-env.js';
7
+ import { findProviderIssues, getAdapters, readEnvVar } from './env-config.js';
8
+ import { runProjectCommand } from './command.js';
9
+ import { checkEnvSchemaCompatibility } from './env-compatibility.js';
10
+ import { compareSchemaFiles } from './schema-parity.js';
11
+ import { parseDatabaseSchema } from './schema-parser.js';
12
+ function commandCheck(id, result, message) {
13
+ return {
14
+ id,
15
+ status: result.passed ? 'ok' : 'fail',
16
+ message: result.passed ? message : `${message}: ${result.stderr || result.stdout}`.trim(),
17
+ details: result,
18
+ };
19
+ }
20
+ function finalizeReport(root, checks) {
21
+ const summary = {
22
+ ok: checks.filter((check) => check.status === 'ok').length,
23
+ warnings: checks.filter((check) => check.status === 'warn').length,
24
+ failures: checks.filter((check) => check.status === 'fail').length,
25
+ };
26
+ const status = summary.failures > 0 ? 'fail' : summary.warnings > 0 ? 'warn' : 'ok';
27
+ return { root, status, checks, summary };
28
+ }
29
+ export function collectProjectHealth(root = findProjectRoot() ?? process.cwd(), options = {}) {
30
+ const checks = [];
31
+ const add = (check) => {
32
+ checks.push(check);
33
+ };
34
+ const file = (id, path, label, required = true) => {
35
+ const present = existsSync(resolve(root, path));
36
+ add({
37
+ id,
38
+ status: present ? 'ok' : required ? 'fail' : 'warn',
39
+ message: present ? `${label} exists` : `${label} is missing`,
40
+ path,
41
+ });
42
+ };
43
+ const pkg = readJsonFile(resolve(root, 'package.json'));
44
+ file('package', 'package.json', 'package.json');
45
+ file('next-config', 'next.config.ts', 'Next.js config');
46
+ file('app-config', 'src/config/app.ts', 'App config');
47
+ file('env-schema', 'src/config/env-schema.ts', 'Environment schema');
48
+ file('navigation-config', 'src/config/navigation.ts', 'Navigation config', false);
49
+ const envCompatibility = checkEnvSchemaCompatibility(root);
50
+ add({
51
+ id: 'env-schema-compatibility',
52
+ status: envCompatibility.status,
53
+ message: envCompatibility.message,
54
+ path: envCompatibility.schemaPath,
55
+ details: envCompatibility,
56
+ });
57
+ const env = loadProjectEnv(root, getProjectEnvOptions(options.envSource));
58
+ add({
59
+ id: 'env-file',
60
+ status: env.source === 'process' || env.fileExists ? 'ok' : 'fail',
61
+ message: env.source === 'process'
62
+ ? 'Using process.env'
63
+ : env.fileExists
64
+ ? '.env.local exists'
65
+ : '.env.local is missing',
66
+ path: env.filePath,
67
+ });
68
+ const adapters = getAdapters(env.content);
69
+ add({
70
+ id: 'effective-config',
71
+ status: 'ok',
72
+ message: 'Effective providers and feature configuration resolved',
73
+ details: {
74
+ adapters,
75
+ appMode: readEnvVar(env.content, 'APP_MODE') ?? 'app',
76
+ },
77
+ });
78
+ const schemaPath = adapters.database === 'postgres' ? 'src/lib/db/schema-pg.ts' : 'src/lib/db/schema.ts';
79
+ file('database-schema', schemaPath, `Active database schema (${adapters.database})`);
80
+ const sqliteSchemaPath = resolve(root, 'src/lib/db/schema.ts');
81
+ const postgresSchemaPath = resolve(root, 'src/lib/db/schema-pg.ts');
82
+ if (existsSync(sqliteSchemaPath) && existsSync(postgresSchemaPath)) {
83
+ const parity = compareSchemaFiles(parseDatabaseSchema(readFileSync(sqliteSchemaPath, 'utf-8') ?? ''), parseDatabaseSchema(readFileSync(postgresSchemaPath, 'utf-8') ?? ''));
84
+ if (parity.differences.length === 0) {
85
+ add({
86
+ id: 'database-schema-parity',
87
+ status: 'ok',
88
+ message: 'SQLite and PostgreSQL schemas match',
89
+ path: 'src/lib/db/schema.ts ↔ src/lib/db/schema-pg.ts',
90
+ });
91
+ }
92
+ else {
93
+ for (const [index, difference] of parity.differences.entries()) {
94
+ add({
95
+ id: `database-schema-parity-${index + 1}`,
96
+ status: difference.severity,
97
+ message: `${difference.table}: ${difference.issue}${difference.details !== undefined ? ` ${JSON.stringify(difference.details)}` : ''}`,
98
+ path: 'src/lib/db/schema.ts ↔ src/lib/db/schema-pg.ts',
99
+ details: difference,
100
+ });
101
+ }
102
+ }
103
+ }
104
+ else {
105
+ add({
106
+ id: 'database-schema-parity-files',
107
+ status: 'fail',
108
+ message: 'Both SQLite and PostgreSQL schema files are required for parity checking',
109
+ path: 'src/lib/db/schema.ts ↔ src/lib/db/schema-pg.ts',
110
+ });
111
+ }
112
+ file('auth-module', 'src/lib/auth/index.ts', 'Auth module', adapters.auth !== 'none');
113
+ file('payments-module', 'src/lib/payments/index.ts', 'Payments module');
114
+ file('plugin-registry', 'codapult.plugins.ts', 'Plugin registry', false);
115
+ for (const issue of findProviderIssues(env.content)) {
116
+ add({
117
+ id: `env-${issue.key.toLowerCase()}`,
118
+ status: issue.severity === 'error' ? 'fail' : 'warn',
119
+ message: issue.message,
120
+ details: { key: issue.key, severity: issue.severity },
121
+ });
122
+ }
123
+ if (!readEnvVar(env.content, 'NEXT_PUBLIC_APP_URL')) {
124
+ add({
125
+ id: 'env-app-url',
126
+ status: 'warn',
127
+ message: 'NEXT_PUBLIC_APP_URL is not set; defaults to http://localhost:3000',
128
+ });
129
+ }
130
+ const nodeModulesPath = resolve(root, 'node_modules');
131
+ add({
132
+ id: 'dependencies',
133
+ status: existsSync(nodeModulesPath) ? 'ok' : 'fail',
134
+ message: existsSync(nodeModulesPath) ? 'node_modules exists' : 'node_modules is missing',
135
+ path: 'node_modules',
136
+ });
137
+ if (options.includeCommands !== false) {
138
+ const node = runProjectCommand('node --version', root, { timeout: 15_000 });
139
+ const nodeMajor = Number.parseInt(node.stdout.replace(/^v/, ''), 10);
140
+ add({
141
+ id: 'node-version',
142
+ status: node.passed && nodeMajor >= 20 ? 'ok' : 'fail',
143
+ message: node.passed
144
+ ? `Node.js ${node.stdout.trim()} (requires v20+)`
145
+ : 'Node.js is not available',
146
+ details: node,
147
+ });
148
+ add(commandCheck('pnpm-version', runProjectCommand('pnpm --version', root, { timeout: 15_000 }), 'pnpm is available'));
149
+ add(commandCheck('typecheck', runProjectCommand('pnpm type-check', root, { timeout: 120_000 }), 'TypeScript compiles cleanly'));
150
+ }
151
+ const pluginsDir = resolve(root, 'src/plugins');
152
+ const plugins = existsSync(pluginsDir)
153
+ ? readdirSync(pluginsDir)
154
+ .filter((fileName) => fileName.endsWith('.ts') && fileName !== 'index.ts')
155
+ .map((fileName) => fileName.replace('.ts', ''))
156
+ : [];
157
+ for (const plugin of plugins) {
158
+ const resolved = resolveManifest(root, plugin);
159
+ if (!resolved?.manifest.install.pages)
160
+ continue;
161
+ const conflicts = findPageConflicts(root, resolved.manifest.install.pages).filter((conflict) => !conflict.isStub);
162
+ if (conflicts.length > 0) {
163
+ add({
164
+ id: `plugin-${plugin}-pages`,
165
+ status: 'fail',
166
+ message: `${plugin} has ${conflicts.length} page conflict(s)`,
167
+ details: conflicts,
168
+ });
169
+ }
170
+ }
171
+ const backups = findPageBackups(root);
172
+ if (backups.length > 0) {
173
+ add({
174
+ id: 'plugin-backups',
175
+ status: 'warn',
176
+ message: `${backups.length} plugin page backup file(s) found`,
177
+ details: backups,
178
+ });
179
+ }
180
+ if (pkg) {
181
+ const deps = {
182
+ ...(pkg.dependencies ?? {}),
183
+ ...(pkg.devDependencies ?? {}),
184
+ };
185
+ add({
186
+ id: 'key-packages',
187
+ status: 'ok',
188
+ message: 'Key package versions detected',
189
+ details: Object.fromEntries(['next', 'react', 'typescript', 'drizzle-orm', 'tailwindcss', 'better-auth']
190
+ .filter((name) => deps[name])
191
+ .map((name) => [name, deps[name]])),
192
+ });
193
+ }
194
+ const git = runProjectCommand('git status --porcelain', root, { timeout: 15_000 });
195
+ if (git.passed) {
196
+ add({
197
+ id: 'git-status',
198
+ status: git.stdout.trim() ? 'warn' : 'ok',
199
+ message: git.stdout.trim()
200
+ ? `${git.stdout.trim().split('\n').length} uncommitted change(s)`
201
+ : 'Working tree is clean',
202
+ details: git.stdout.trim(),
203
+ });
204
+ }
205
+ const remotes = runProjectCommand('git remote', root, { timeout: 15_000 });
206
+ if (remotes.passed) {
207
+ add({
208
+ id: 'upstream-remote',
209
+ status: remotes.stdout.split('\n').includes('codapult-upstream') ? 'ok' : 'warn',
210
+ message: remotes.stdout.split('\n').includes('codapult-upstream')
211
+ ? 'Codapult upstream remote is configured'
212
+ : 'Codapult upstream remote is not configured; run `codapult update` when needed',
213
+ details: remotes.stdout.trim(),
214
+ });
215
+ }
216
+ return finalizeReport(root, checks);
217
+ }
218
+ /** Project health plus checks specific to the editor-facing MCP installation. */
219
+ export function collectMcpHealth(root = findProjectRoot() ?? process.cwd(), options = {}) {
220
+ const report = collectProjectHealth(root, options);
221
+ const checks = [...report.checks];
222
+ const configPath = '.cursor/mcp.json';
223
+ const config = readJsonFile(resolve(root, configPath));
224
+ if (!config) {
225
+ checks.push({
226
+ id: 'mcp-config',
227
+ status: 'fail',
228
+ message: 'MCP config is missing or invalid',
229
+ path: configPath,
230
+ });
231
+ return finalizeReport(root, checks);
232
+ }
233
+ const server = config.mcpServers?.codapult;
234
+ const command = typeof server === 'object' && server !== null ? server : undefined;
235
+ const args = Array.isArray(command?.args) ? command.args.map(String) : [];
236
+ const valid = command?.command === 'npx' &&
237
+ args.includes('mcp-server') &&
238
+ args.some((arg) => arg.includes('@codapult/cli@'));
239
+ checks.push({
240
+ id: 'mcp-config',
241
+ status: valid ? 'ok' : 'fail',
242
+ message: valid
243
+ ? 'MCP config points to @codapult/cli'
244
+ : 'MCP config has no valid Codapult server entry',
245
+ path: configPath,
246
+ details: { command: command?.command, args, cwd: command?.cwd },
247
+ });
248
+ return finalizeReport(root, checks);
249
+ }
@@ -0,0 +1,17 @@
1
+ import type { ParsedTable } from './schema-parser.js';
2
+ export interface LiveDatabaseColumn {
3
+ name: string;
4
+ type: string;
5
+ constraints: string[];
6
+ }
7
+ export interface LiveDatabaseTable {
8
+ name: string;
9
+ columns: LiveDatabaseColumn[];
10
+ }
11
+ export interface DatabaseDrift {
12
+ table: string;
13
+ issue: 'missing_in_database' | 'missing_in_schema' | 'column_missing_in_database' | 'column_missing_in_schema' | 'column_type_differs';
14
+ details?: unknown;
15
+ }
16
+ export declare function inspectLiveDatabase(root: string, envContent: string): LiveDatabaseTable[];
17
+ export declare function diffSchemaWithLiveDatabase(schema: ParsedTable[], database: LiveDatabaseTable[]): DatabaseDrift[];
@@ -0,0 +1,131 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { getAdapters, readEnvVar } from './env-config.js';
3
+ const INSPECTOR_SCRIPT = String.raw `
4
+ const provider = process.env.CODAPULT_DB_PROVIDER;
5
+ const output = (tables) => process.stdout.write(JSON.stringify(tables));
6
+ if (provider === 'turso') {
7
+ const { createClient } = await import('@libsql/client');
8
+ const client = createClient({ url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN || undefined });
9
+ const rows = (await client.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name != '__drizzle_migrations' ORDER BY name")).rows;
10
+ const tables = [];
11
+ for (const row of rows) {
12
+ const name = String(row.name);
13
+ const escaped = name.replaceAll('"', '""');
14
+ const [columnsResult, foreignKeysResult] = await Promise.all([
15
+ client.execute('PRAGMA table_info("' + escaped + '")'),
16
+ client.execute('PRAGMA foreign_key_list("' + escaped + '")'),
17
+ ]);
18
+ const foreignKeys = new Set(foreignKeysResult.rows.map((key) => String(key.from)));
19
+ tables.push({ name, columns: columnsResult.rows.map((column) => {
20
+ const constraints = [];
21
+ if (Number(column.pk) > 0) constraints.push('PRIMARY KEY');
22
+ if (Number(column.notnull) > 0) constraints.push('NOT NULL');
23
+ if (column.dflt_value != null) constraints.push('DEFAULT');
24
+ if (foreignKeys.has(String(column.name))) constraints.push('FK');
25
+ return { name: String(column.name), type: String(column.type).toLowerCase(), constraints };
26
+ }) });
27
+ }
28
+ client.close();
29
+ output(tables);
30
+ } else {
31
+ const postgres = (await import('postgres')).default;
32
+ const sql = postgres(process.env.DATABASE_URL);
33
+ const result = await sql.unsafe(
34
+ "SELECT c.table_name, c.column_name, c.data_type, c.is_nullable, c.column_default, " +
35
+ "COALESCE(array_agg(tc.constraint_type) FILTER (WHERE tc.constraint_type IS NOT NULL), '{}') AS constraints " +
36
+ "FROM information_schema.columns c " +
37
+ "LEFT JOIN information_schema.key_column_usage kcu ON c.table_schema=kcu.table_schema AND c.table_name=kcu.table_name AND c.column_name=kcu.column_name " +
38
+ "LEFT JOIN information_schema.table_constraints tc ON kcu.constraint_schema=tc.constraint_schema AND kcu.constraint_name=tc.constraint_name AND kcu.table_name=tc.table_name " +
39
+ "WHERE c.table_schema='public' AND c.table_name != '__drizzle_migrations' GROUP BY c.table_name,c.column_name,c.data_type,c.is_nullable,c.column_default ORDER BY c.table_name,c.ordinal_position"
40
+ );
41
+ const map = new Map();
42
+ for (const row of result.rows) {
43
+ if (!map.has(row.table_name)) map.set(row.table_name, { name: row.table_name, columns: [] });
44
+ const constraints = [];
45
+ if (row.constraints.includes('PRIMARY KEY')) constraints.push('PRIMARY KEY');
46
+ if (row.is_nullable === 'NO') constraints.push('NOT NULL');
47
+ if (row.constraints.includes('FOREIGN KEY')) constraints.push('FK');
48
+ if (row.column_default != null) constraints.push('DEFAULT');
49
+ if (row.constraints.includes('UNIQUE')) constraints.push('UNIQUE');
50
+ map.get(row.table_name).columns.push({ name: row.column_name, type: row.data_type.toLowerCase(), constraints });
51
+ }
52
+ await sql.end({ timeout: 5 });
53
+ output([...map.values()]);
54
+ }
55
+ `;
56
+ function databaseEnv(envContent) {
57
+ const adapters = getAdapters(envContent);
58
+ return {
59
+ CODAPULT_DB_PROVIDER: adapters.database,
60
+ TURSO_DATABASE_URL: readEnvVar(envContent, 'TURSO_DATABASE_URL'),
61
+ TURSO_AUTH_TOKEN: readEnvVar(envContent, 'TURSO_AUTH_TOKEN'),
62
+ DATABASE_URL: readEnvVar(envContent, 'DATABASE_URL'),
63
+ };
64
+ }
65
+ export function inspectLiveDatabase(root, envContent) {
66
+ const env = databaseEnv(envContent);
67
+ const requiredKey = env.CODAPULT_DB_PROVIDER === 'postgres' ? 'DATABASE_URL' : 'TURSO_DATABASE_URL';
68
+ if (!env[requiredKey])
69
+ throw new Error(`${requiredKey} is required to inspect the live database`);
70
+ try {
71
+ const output = execFileSync(process.execPath, ['--input-type=module', '--eval', INSPECTOR_SCRIPT], {
72
+ cwd: root,
73
+ env: { ...process.env, ...env },
74
+ stdio: ['ignore', 'pipe', 'pipe'],
75
+ timeout: 60_000,
76
+ }).toString();
77
+ return JSON.parse(output);
78
+ }
79
+ catch {
80
+ throw new Error('Could not inspect the live database. Verify connectivity and database credentials.');
81
+ }
82
+ }
83
+ function normalizedType(type) {
84
+ const value = type.toLowerCase().replaceAll(/\s+/g, '');
85
+ if (value === 'character varying')
86
+ return 'varchar';
87
+ if (value === 'timestamp without timezone')
88
+ return 'timestamp';
89
+ if (value === 'double precision')
90
+ return 'doubleprecision';
91
+ return value;
92
+ }
93
+ export function diffSchemaWithLiveDatabase(schema, database) {
94
+ const sourceTables = new Map(schema.map((table) => [table.name, table]));
95
+ const liveTables = new Map(database.map((table) => [table.name, table]));
96
+ const differences = [];
97
+ for (const name of new Set([...sourceTables.keys(), ...liveTables.keys()])) {
98
+ const source = sourceTables.get(name);
99
+ const live = liveTables.get(name);
100
+ if (!live) {
101
+ differences.push({ table: name, issue: 'missing_in_database' });
102
+ continue;
103
+ }
104
+ if (!source) {
105
+ differences.push({ table: name, issue: 'missing_in_schema' });
106
+ continue;
107
+ }
108
+ const sourceColumns = new Map(source.columns.map((column) => [column.databaseName, column]));
109
+ const liveColumns = new Map(live.columns.map((column) => [column.name, column]));
110
+ for (const columnName of new Set([...sourceColumns.keys(), ...liveColumns.keys()])) {
111
+ const sourceColumn = sourceColumns.get(columnName);
112
+ const liveColumn = liveColumns.get(columnName);
113
+ if (!liveColumn) {
114
+ differences.push({ table: name, issue: 'column_missing_in_database', details: columnName });
115
+ continue;
116
+ }
117
+ if (!sourceColumn) {
118
+ differences.push({ table: name, issue: 'column_missing_in_schema', details: columnName });
119
+ continue;
120
+ }
121
+ if (normalizedType(sourceColumn.type) !== normalizedType(liveColumn.type)) {
122
+ differences.push({
123
+ table: name,
124
+ issue: 'column_type_differs',
125
+ details: { column: columnName, schema: sourceColumn.type, database: liveColumn.type },
126
+ });
127
+ }
128
+ }
129
+ }
130
+ return differences;
131
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { diffSchemaWithLiveDatabase } from './live-db-diff.js';
3
+ describe('diffSchemaWithLiveDatabase', () => {
4
+ it('compares physical column names and normalizes SQL types', () => {
5
+ const differences = diffSchemaWithLiveDatabase([
6
+ {
7
+ name: 'users',
8
+ columns: [
9
+ { name: 'displayName', databaseName: 'display_name', type: 'text', constraints: [] },
10
+ { name: 'id', databaseName: 'id', type: 'uuid', constraints: ['PRIMARY KEY'] },
11
+ ],
12
+ },
13
+ ], [
14
+ {
15
+ name: 'users',
16
+ columns: [
17
+ { name: 'display_name', type: 'text', constraints: [] },
18
+ { name: 'legacy', type: 'text', constraints: [] },
19
+ ],
20
+ },
21
+ { name: 'orphan', columns: [] },
22
+ ]);
23
+ expect(differences).toEqual([
24
+ { table: 'users', issue: 'column_missing_in_database', details: 'id' },
25
+ { table: 'users', issue: 'column_missing_in_schema', details: 'legacy' },
26
+ { table: 'orphan', issue: 'missing_in_schema' },
27
+ ]);
28
+ });
29
+ });
@@ -10,6 +10,7 @@ export interface PluginManifest {
10
10
  description: string;
11
11
  install: {
12
12
  schemaImports?: string[];
13
+ schemaImportsPg?: string[];
13
14
  dbReExports?: string[];
14
15
  schemaTables?: string;
15
16
  schemaTablesPg?: string;
@@ -1,6 +1,8 @@
1
1
  import type { PluginManifest } from './manifest.js';
2
2
  export declare function patchSchemaImports(projectRoot: string, pluginName: string, imports: string[], action: 'add' | 'remove'): void;
3
+ export declare function patchSchemaImportsPg(projectRoot: string, pluginName: string, imports: string[], action: 'add' | 'remove'): void;
3
4
  export declare function patchSchemaTables(projectRoot: string, pluginName: string, pluginDir: string, tablesFile: string, action: 'add' | 'remove' | 'update'): boolean;
5
+ export declare function patchSchemaTablesPg(projectRoot: string, pluginName: string, pluginDir: string, tablesFile: string, action: 'add' | 'remove' | 'update'): boolean;
4
6
  export declare function patchDbReExports(projectRoot: string, pluginName: string, symbols: string[], action: 'add' | 'remove'): void;
5
7
  export declare function patchNextConfig(projectRoot: string, pluginName: string, manifest: PluginManifest, action: 'add' | 'remove'): void;
6
8
  export declare function regenerateBarrel(projectRoot: string): void;
@@ -21,12 +21,12 @@ function removeMarkedBlock(content, name) {
21
21
  // ---------------------------------------------------------------------------
22
22
  // schema.ts — add/remove schema imports and table definitions
23
23
  // ---------------------------------------------------------------------------
24
- export function patchSchemaImports(projectRoot, pluginName, imports, action) {
25
- const schemaPath = resolve(projectRoot, 'src/lib/db/schema.ts');
26
- if (!existsSync(schemaPath))
24
+ function patchSchemaImportsAtPath(projectRoot, pluginName, imports, action, schemaPath, packageName) {
25
+ const absoluteSchemaPath = resolve(projectRoot, schemaPath);
26
+ if (!existsSync(absoluteSchemaPath))
27
27
  return;
28
- let content = readFileSync(schemaPath, 'utf-8');
29
- const importLine = /import\s*\{([^}]+)\}\s*from\s*['"]drizzle-orm\/sqlite-core['"];?/.exec(content);
28
+ let content = readFileSync(absoluteSchemaPath, 'utf-8');
29
+ const importLine = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*['"]drizzle-orm\\/${packageName}['"];?`).exec(content);
30
30
  if (!importLine)
31
31
  return;
32
32
  const existing = importLine[1]
@@ -54,9 +54,15 @@ export function patchSchemaImports(projectRoot, pluginName, imports, action) {
54
54
  }
55
55
  }
56
56
  }
57
- const newImportLine = `import { ${existing.join(', ')} } from 'drizzle-orm/sqlite-core';`;
57
+ const newImportLine = `import { ${existing.join(', ')} } from 'drizzle-orm/${packageName}';`;
58
58
  content = content.replace(importLine[0], newImportLine);
59
- writeFileSync(schemaPath, content, 'utf-8');
59
+ writeFileSync(absoluteSchemaPath, content, 'utf-8');
60
+ }
61
+ export function patchSchemaImports(projectRoot, pluginName, imports, action) {
62
+ patchSchemaImportsAtPath(projectRoot, pluginName, imports, action, 'src/lib/db/schema.ts', 'sqlite-core');
63
+ }
64
+ export function patchSchemaImportsPg(projectRoot, pluginName, imports, action) {
65
+ patchSchemaImportsAtPath(projectRoot, pluginName, imports, action, 'src/lib/db/schema-pg.ts', 'pg-core');
60
66
  }
61
67
  function extractMarkedBlock(content, name) {
62
68
  const start = MARKER_START(name);
@@ -84,14 +90,14 @@ function readPluginTables(pluginDir, tablesFile) {
84
90
  tables = tables.replace(/^(?:export\s+)?interface\s+\w+\s*\{[\s\S]*?\}\s*\n/gm, '');
85
91
  return tables.trim();
86
92
  }
87
- export function patchSchemaTables(projectRoot, pluginName, pluginDir, tablesFile, action) {
88
- const schemaPath = resolve(projectRoot, 'src/lib/db/schema.ts');
89
- if (!existsSync(schemaPath))
93
+ function patchSchemaTablesAtPath(projectRoot, pluginName, pluginDir, tablesFile, action, schemaPath) {
94
+ const absoluteSchemaPath = resolve(projectRoot, schemaPath);
95
+ if (!existsSync(absoluteSchemaPath))
90
96
  return false;
91
- let content = readFileSync(schemaPath, 'utf-8');
97
+ let content = readFileSync(absoluteSchemaPath, 'utf-8');
92
98
  if (action === 'remove') {
93
99
  content = removeMarkedBlock(content, pluginName);
94
- writeFileSync(schemaPath, content, 'utf-8');
100
+ writeFileSync(absoluteSchemaPath, content, 'utf-8');
95
101
  return true;
96
102
  }
97
103
  if (action === 'add' && hasMarker(content, pluginName))
@@ -109,9 +115,15 @@ export function patchSchemaTables(projectRoot, pluginName, pluginDir, tablesFile
109
115
  }
110
116
  const block = `\n${MARKER_START(pluginName)}\n${tables}\n${MARKER_END(pluginName)}\n`;
111
117
  content = content.trimEnd() + '\n' + block;
112
- writeFileSync(schemaPath, content, 'utf-8');
118
+ writeFileSync(absoluteSchemaPath, content, 'utf-8');
113
119
  return true;
114
120
  }
121
+ export function patchSchemaTables(projectRoot, pluginName, pluginDir, tablesFile, action) {
122
+ return patchSchemaTablesAtPath(projectRoot, pluginName, pluginDir, tablesFile, action, 'src/lib/db/schema.ts');
123
+ }
124
+ export function patchSchemaTablesPg(projectRoot, pluginName, pluginDir, tablesFile, action) {
125
+ return patchSchemaTablesAtPath(projectRoot, pluginName, pluginDir, tablesFile, action, 'src/lib/db/schema-pg.ts');
126
+ }
115
127
  // ---------------------------------------------------------------------------
116
128
  // db/index.ts — re-export tables for FK references
117
129
  // ---------------------------------------------------------------------------
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, regenerateBarrel, createPluginRegistration, patchPages, findPageConflicts, findPageBackups, readPageExtensions, PageConflictError, patchEnvFile, patchPackageJson, } from './patchers.js';
2
+ import { patchSchemaImports, patchSchemaImportsPg, patchSchemaTables, patchSchemaTablesPg, patchDbReExports, patchNextConfig, regenerateBarrel, createPluginRegistration, patchPages, findPageConflicts, findPageBackups, readPageExtensions, PageConflictError, patchEnvFile, patchPackageJson, } from './patchers.js';
3
3
  import { ENV_FILE_NAME } from './project-env.js';
4
4
  vi.mock('node:fs');
5
5
  const { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } = await import('node:fs');
@@ -44,6 +44,7 @@ export const user = sqliteTable('user', {
44
44
  export const widget = sqliteTable('widget', {
45
45
  score: real('score'),
46
46
  });
47
+
47
48
  // --- plugin:test-plugin:end ---
48
49
  `;
49
50
  mockedExists.mockReturnValue(true);
@@ -75,6 +76,23 @@ export const widget = sqliteTable('widget', {
75
76
  expect(written).toContain('integer');
76
77
  });
77
78
  });
79
+ describe('PostgreSQL schema patchers', () => {
80
+ it('adds PostgreSQL imports to schema-pg.ts', () => {
81
+ mockedExists.mockReturnValue(true);
82
+ mockedRead.mockReturnValue("import { pgTable, text } from 'drizzle-orm/pg-core';\n\nexport const user = pgTable('user', {});");
83
+ patchSchemaImportsPg(ROOT, 'test-plugin', ['jsonb', 'primaryKey'], 'add');
84
+ expect(mockedWrite.mock.calls[0][1]).toContain("import { pgTable, text, jsonb, primaryKey } from 'drizzle-orm/pg-core';");
85
+ });
86
+ it('copies PostgreSQL tables into schema-pg.ts', () => {
87
+ const schema = "import { pgTable, text } from 'drizzle-orm/pg-core';\n\nexport const user = pgTable('user', {});";
88
+ const tables = "import { pgTable, text } from 'drizzle-orm/pg-core';\n\nexport const widget = pgTable('widget', {});";
89
+ mockedExists.mockReturnValue(true);
90
+ mockedRead.mockImplementation((path) => String(path).includes('schema-pg.ts') ? schema : tables);
91
+ patchSchemaTablesPg(ROOT, 'test-plugin', '/plugins/test', 'tables-pg.ts', 'add');
92
+ expect(mockedWrite.mock.calls[0][0]).toBe('/project/src/lib/db/schema-pg.ts');
93
+ expect(mockedWrite.mock.calls[0][1]).toContain("pgTable('widget'");
94
+ });
95
+ });
78
96
  // ---------------------------------------------------------------------------
79
97
  // patchSchemaTables
80
98
  // ---------------------------------------------------------------------------
@@ -439,7 +457,9 @@ describe('patchPages', () => {
439
457
  });
440
458
  describe('findPageConflicts', () => {
441
459
  it('reports a sibling file at a different Next.js page extension', () => {
442
- const pages = { 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome' };
460
+ const pages = {
461
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
462
+ };
443
463
  const sibling = '/project/src/app/welcome/page.tsx';
444
464
  mockedExists.mockImplementation((p) => p === sibling);
445
465
  mockedRead.mockReturnValue('export default function User() {}');
@@ -450,14 +470,18 @@ describe('findPageConflicts', () => {
450
470
  expect(conflicts[0].conflictRel).toBe('src/app/welcome/page.tsx');
451
471
  });
452
472
  it('returns [] when the only file at the target path is our own stub', () => {
453
- const pages = { 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome' };
473
+ const pages = {
474
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
475
+ };
454
476
  const target = '/project/src/app/welcome/page.ts';
455
477
  mockedExists.mockImplementation((p) => p === target);
456
478
  mockedRead.mockReturnValue("export { default } from '@codapult/plugin-onboarding/pages/welcome';\n");
457
479
  expect(findPageConflicts(ROOT, pages)).toEqual([]);
458
480
  });
459
481
  it('flags foreign stubs as conflicts but marks them isStub=true', () => {
460
- const pages = { 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome' };
482
+ const pages = {
483
+ 'src/app/welcome/page.ts': '@codapult/plugin-onboarding/pages/welcome',
484
+ };
461
485
  const sibling = '/project/src/app/welcome/page.tsx';
462
486
  mockedExists.mockImplementation((p) => p === sibling);
463
487
  mockedRead.mockReturnValue("export { default } from 'some-other/pages/welcome';\n");
@@ -544,7 +568,11 @@ describe('patchEnvFile', () => {
544
568
  mockedExists.mockReturnValue(true);
545
569
  mockedRead.mockReturnValue(envContent);
546
570
  const envVars = {
547
- PLUGIN_API_KEY: { default: '', required: true, description: 'API key for the plugin' },
571
+ PLUGIN_API_KEY: {
572
+ default: '',
573
+ required: true,
574
+ description: 'API key for the plugin',
575
+ },
548
576
  PLUGIN_URL: { default: 'http://localhost:3001', required: false },
549
577
  };
550
578
  patchEnvFile(ROOT, 'test-plugin', envVars, 'add');
@@ -583,7 +611,10 @@ describe('patchEnvFile', () => {
583
611
  // ---------------------------------------------------------------------------
584
612
  describe('patchPackageJson', () => {
585
613
  it('adds dependency with file: protocol on add', () => {
586
- const pkg = JSON.stringify({ name: 'codapult', dependencies: { next: '16' } });
614
+ const pkg = JSON.stringify({
615
+ name: 'codapult',
616
+ dependencies: { next: '16' },
617
+ });
587
618
  mockedExists.mockReturnValue(true);
588
619
  mockedRead.mockReturnValue(pkg);
589
620
  patchPackageJson(ROOT, 'test-plugin', '@codapult/plugin-test', '/plugins/test-plugin', 'add');
@@ -595,7 +626,10 @@ describe('patchPackageJson', () => {
595
626
  it('removes dependency on remove', () => {
596
627
  const pkg = JSON.stringify({
597
628
  name: 'codapult',
598
- dependencies: { next: '16', '@codapult/plugin-test': 'file:../test-plugin' },
629
+ dependencies: {
630
+ next: '16',
631
+ '@codapult/plugin-test': 'file:../test-plugin',
632
+ },
599
633
  });
600
634
  mockedExists.mockReturnValue(true);
601
635
  mockedRead.mockReturnValue(pkg);
@@ -0,0 +1,15 @@
1
+ import type { ParsedTable } from './schema-parser.js';
2
+ export type SchemaParityStatus = 'ok' | 'warn' | 'fail';
3
+ export type SchemaParityIssue = 'missing_in_sqlite' | 'missing_in_postgres' | 'column_missing_in_sqlite' | 'column_missing_in_postgres' | 'column_type_differs';
4
+ export interface SchemaParityDifference {
5
+ table: string;
6
+ issue: SchemaParityIssue;
7
+ severity: Exclude<SchemaParityStatus, 'ok'>;
8
+ details?: unknown;
9
+ }
10
+ export interface SchemaParityReport {
11
+ status: SchemaParityStatus;
12
+ identical: boolean;
13
+ differences: SchemaParityDifference[];
14
+ }
15
+ export declare function compareSchemaFiles(sqlite: ParsedTable[], postgres: ParsedTable[]): SchemaParityReport;