@lssm/app.cli-database 1.41.0 → 1.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ //#region rolldown:runtime
4
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
5
+
6
+ //#endregion
7
+ export { __require };
package/dist/cli.mjs ADDED
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ import { runImport } from "./commands/import.mjs";
3
+ import { runCheck } from "./commands/check.mjs";
4
+ import { runGenerate } from "./commands/generate.mjs";
5
+ import { runMigrate } from "./commands/migrate.mjs";
6
+ import { runSeed } from "./commands/seed.mjs";
7
+ import { runSchemaGenerate } from "./commands/schema-generate.mjs";
8
+ import { runSchemaCompose } from "./commands/schema-compose.mjs";
9
+ import mri from "minimist";
10
+
11
+ //#region src/cli.ts
12
+ async function main() {
13
+ const argv = mri(process.argv.slice(2));
14
+ const [cmd] = argv._;
15
+ switch (cmd) {
16
+ case "import":
17
+ await runImport(argv);
18
+ break;
19
+ case "check":
20
+ await runCheck(argv);
21
+ break;
22
+ case "generate":
23
+ await runGenerate(argv);
24
+ break;
25
+ case "migrate:dev":
26
+ case "migrate:deploy":
27
+ case "migrate:status":
28
+ await runMigrate(cmd, argv);
29
+ break;
30
+ case "seed":
31
+ await runSeed(argv);
32
+ break;
33
+ case "schema:generate":
34
+ await runSchemaGenerate(argv);
35
+ break;
36
+ case "schema:compose":
37
+ await runSchemaCompose(argv);
38
+ break;
39
+ default:
40
+ printUsage();
41
+ process.exit(1);
42
+ }
43
+ }
44
+ function printUsage() {
45
+ console.log(`
46
+ Usage: database <command> [options]
47
+
48
+ Commands:
49
+ import Import schema from external sources
50
+ check Check Prisma schema validity
51
+ generate Generate Prisma client
52
+ migrate:dev Run migrations in development
53
+ migrate:deploy Deploy migrations to production
54
+ migrate:status Check migration status
55
+ seed Seed the database
56
+
57
+ Schema Generation (spec-first):
58
+ schema:generate Generate Prisma schema from entity specs
59
+ --config <path> Schema config file (default: ./schema.config.ts)
60
+ --output <path> Output path (default: ./prisma/schema/generated.prisma)
61
+ --module <id> Generate only a specific module
62
+
63
+ schema:compose Compose multiple module schemas
64
+ --config <path> Schema config file (default: ./schema.config.ts)
65
+ --output <path> Output path (default: ./prisma/schema/composed.prisma)
66
+ --modules <list> Comma-separated module IDs to include
67
+
68
+ Examples:
69
+ database schema:generate --config ./schema.config.ts
70
+ database schema:compose --modules "@lssm/lib.identity-rbac,@lssm/module.audit-trail"
71
+ database generate
72
+ database migrate:dev --name add_users_table
73
+ `);
74
+ }
75
+ main().catch((err) => {
76
+ console.error(err);
77
+ process.exit(1);
78
+ });
79
+
80
+ //#endregion
81
+ export { };
@@ -0,0 +1,34 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+
5
+ //#region src/commands/check.ts
6
+ function sha256(content) {
7
+ return crypto.createHash("sha256").update(content).digest("hex");
8
+ }
9
+ async function runCheck(argv) {
10
+ const target = argv.target || process.cwd();
11
+ const lockPath = path.join(target, "prisma", "schema", "imported", "imported.lock.json");
12
+ if (!fs.existsSync(lockPath)) {
13
+ console.error("No imported.lock.json found. Run: database import");
14
+ process.exit(1);
15
+ }
16
+ const lock = JSON.parse(fs.readFileSync(lockPath, "utf8"));
17
+ let ok = true;
18
+ for (const e of lock.entries) {
19
+ if (!fs.existsSync(e.sourcePath)) {
20
+ console.error(`Missing source: ${e.sourcePath}`);
21
+ ok = false;
22
+ continue;
23
+ }
24
+ if (sha256(fs.readFileSync(e.sourcePath, "utf8")) !== e.sha256) {
25
+ console.error(`Drift detected for ${e.moduleName} (${e.sourcePath})`);
26
+ ok = false;
27
+ }
28
+ }
29
+ if (!ok) process.exit(2);
30
+ console.log("Imported schemas are in sync with lock.");
31
+ }
32
+
33
+ //#endregion
34
+ export { runCheck };
@@ -0,0 +1,9 @@
1
+ import { execa } from "execa";
2
+
3
+ //#region src/commands/generate.ts
4
+ async function runGenerate(argv) {
5
+ await execa("prisma", ["generate"], { stdio: "inherit" });
6
+ }
7
+
8
+ //#endregion
9
+ export { runGenerate };
@@ -0,0 +1,95 @@
1
+ import { __require } from "../_virtual/rolldown_runtime.mjs";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import crypto from "node:crypto";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ //#region src/commands/import.ts
8
+ function sha256(content) {
9
+ return crypto.createHash("sha256").update(content).digest("hex");
10
+ }
11
+ function stripDatasourceAndGenerators(schema) {
12
+ return schema.replace(/datasource\s+\w+\s*\{[\s\S]*?\}/g, "").replace(/generator\s+\w+\s*\{[\s\S]*?\}/g, "").trim();
13
+ }
14
+ async function runImport(argv) {
15
+ const target = argv.target || process.cwd();
16
+ const modulesArg = argv.modules || "";
17
+ async function loadModulesFromMergerConfig() {
18
+ const candidates = [
19
+ path.join(target, "prisma-merger.config.ts"),
20
+ path.join(target, "prisma-merger.config.mts"),
21
+ path.join(target, "prisma-merger.config.js"),
22
+ path.join(target, "prisma-merger.config.mjs"),
23
+ path.join(target, "prisma-merger.config.cjs"),
24
+ path.join(target, "prisma-merger.config.json")
25
+ ];
26
+ for (const file of candidates) {
27
+ if (!fs.existsSync(file)) continue;
28
+ if (file.endsWith(".json")) {
29
+ const json = JSON.parse(fs.readFileSync(file, "utf8"));
30
+ if (Array.isArray(json.modules) && json.modules.length > 0) return json.modules;
31
+ } else if (file.endsWith(".ts") || file.endsWith(".mts")) {
32
+ const match = fs.readFileSync(file, "utf8").match(/modules\s*:\s*\[([\s\S]*?)\]/m);
33
+ if (Array.isArray(match) && typeof match[1] === "string") {
34
+ const arr = match[1] || "";
35
+ const mods = [];
36
+ const re = /['\"]([^'\"]+)['\"]/g;
37
+ let m;
38
+ while (m = re.exec(arr)) {
39
+ const val = m[1] ?? "";
40
+ if (val) mods.push(val);
41
+ }
42
+ if (mods.length > 0) return mods;
43
+ }
44
+ } else {
45
+ const mod = await import(pathToFileURL(file).href);
46
+ const cfg = mod.default || mod;
47
+ if (Array.isArray(cfg.modules) && cfg.modules.length > 0) return cfg.modules;
48
+ }
49
+ }
50
+ return null;
51
+ }
52
+ let modules = modulesArg.split(",").map((s) => s.trim()).filter(Boolean);
53
+ if (modules.length === 0) {
54
+ const fromCfg = await loadModulesFromMergerConfig();
55
+ if (fromCfg) modules = fromCfg;
56
+ }
57
+ if (modules.length === 0) {
58
+ console.error("No modules specified. Provide --modules or define prisma-merger.config.ts { modules: [...] }");
59
+ process.exit(1);
60
+ }
61
+ const importedDir = path.join(target, "prisma", "schema", "imported");
62
+ fs.mkdirSync(importedDir, { recursive: true });
63
+ const entries = [];
64
+ for (const mod of modules) {
65
+ const pkgPath = __require.resolve(path.join(mod, "package.json"));
66
+ const modRoot = path.dirname(pkgPath);
67
+ const schemaPath = path.join(modRoot, "prisma", "schema.prisma");
68
+ if (!fs.existsSync(schemaPath)) {
69
+ console.error(`Module ${mod} missing prisma/schema.prisma`);
70
+ process.exit(1);
71
+ }
72
+ const raw = fs.readFileSync(schemaPath, "utf8");
73
+ const stripped = stripDatasourceAndGenerators(raw);
74
+ const outDir = path.join(importedDir, path.basename(mod).replace(/^@/, "").replace(/\//g, "_"));
75
+ fs.mkdirSync(outDir, { recursive: true });
76
+ const outFile = path.join(outDir, "models.prisma");
77
+ fs.writeFileSync(outFile, stripped, "utf8");
78
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
79
+ entries.push({
80
+ moduleName: mod,
81
+ version: pkg.version || "0.0.0",
82
+ sourcePath: schemaPath,
83
+ sha256: sha256(raw)
84
+ });
85
+ }
86
+ const lock = {
87
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
88
+ entries
89
+ };
90
+ fs.writeFileSync(path.join(importedDir, "imported.lock.json"), JSON.stringify(lock, null, 2));
91
+ console.log(`Imported ${entries.length} modules into ${importedDir}`);
92
+ }
93
+
94
+ //#endregion
95
+ export { runImport };
@@ -0,0 +1,20 @@
1
+ import { execa } from "execa";
2
+
3
+ //#region src/commands/migrate.ts
4
+ async function runMigrate(cmd, argv) {
5
+ if (cmd === "migrate:dev") {
6
+ await execa("prisma", ["migrate", "dev"], { stdio: "inherit" });
7
+ return;
8
+ }
9
+ if (cmd === "migrate:deploy") {
10
+ await execa("prisma", ["migrate", "deploy"], { stdio: "inherit" });
11
+ return;
12
+ }
13
+ if (cmd === "migrate:status") {
14
+ await execa("prisma", ["migrate", "status"], { stdio: "inherit" });
15
+ return;
16
+ }
17
+ }
18
+
19
+ //#endregion
20
+ export { runMigrate };
@@ -0,0 +1,76 @@
1
+ import { loadSchemaConfig } from "../lib/schema-config.mjs";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ //#region src/commands/schema-compose.ts
6
+ /**
7
+ * Compose multiple module schemas into a single Prisma schema.
8
+ *
9
+ * Usage:
10
+ * database schema:compose --config ./schema.config.ts
11
+ * database schema:compose --modules "@lssm/lib.identity-rbac,@lssm/module.audit-trail"
12
+ */
13
+ async function runSchemaCompose(argv) {
14
+ console.log("🔗 Composing module schemas...\n");
15
+ const configPath = argv.config ?? "./schema.config.ts";
16
+ const config = await loadSchemaConfig(configPath);
17
+ if (!config) {
18
+ console.error(`❌ Could not load schema config from ${configPath}`);
19
+ process.exit(1);
20
+ }
21
+ let modules = config.modules;
22
+ if (argv.modules) {
23
+ const moduleIds = argv.modules.split(",").map((m) => m.trim());
24
+ modules = config.modules.filter((m) => moduleIds.includes(m.moduleId));
25
+ }
26
+ if (modules.length === 0) {
27
+ console.error("❌ No modules found to compose");
28
+ process.exit(1);
29
+ }
30
+ console.log(`📦 Composing ${modules.length} module(s):`);
31
+ modules.forEach((m) => {
32
+ console.log(` - ${m.moduleId}`);
33
+ m.entities.forEach((e) => {
34
+ console.log(` • ${e.name} (${Object.keys(e.fields).length} fields)`);
35
+ });
36
+ });
37
+ console.log("");
38
+ const allEnums = /* @__PURE__ */ new Set();
39
+ modules.forEach((m) => {
40
+ m.enums?.forEach((e) => allEnums.add(e.name));
41
+ m.entities.forEach((entity) => {
42
+ entity.enums?.forEach((e) => allEnums.add(e.name));
43
+ });
44
+ });
45
+ if (allEnums.size > 0) {
46
+ console.log(`📋 Enums discovered: ${Array.from(allEnums).join(", ")}`);
47
+ console.log("");
48
+ }
49
+ const { composeModuleSchemas } = await import("@lssm/lib.schema");
50
+ const prismaSchema = composeModuleSchemas(modules, {
51
+ provider: config.provider ?? "postgresql",
52
+ clientOutput: config.clientOutput,
53
+ includePothos: config.includePothos ?? true,
54
+ pothosOutput: config.pothosOutput
55
+ });
56
+ const outputPath = argv.output ?? config.outputPath ?? "./prisma/schema/composed.prisma";
57
+ const outputDir = path.dirname(outputPath);
58
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
59
+ fs.writeFileSync(outputPath, prismaSchema, "utf-8");
60
+ const entityCount = modules.reduce((acc, m) => acc + m.entities.length, 0);
61
+ const fieldCount = modules.reduce((acc, m) => acc + m.entities.reduce((eAcc, e) => eAcc + Object.keys(e.fields).length, 0), 0);
62
+ console.log("✅ Schema composition complete!");
63
+ console.log("");
64
+ console.log(` 📄 Output: ${outputPath}`);
65
+ console.log(` 📦 Modules: ${modules.length}`);
66
+ console.log(` 🏗️ Entities: ${entityCount}`);
67
+ console.log(` 📝 Fields: ${fieldCount}`);
68
+ console.log(` 📋 Enums: ${allEnums.size}`);
69
+ console.log("");
70
+ console.log("Next steps:");
71
+ console.log(" 1. Run: database generate");
72
+ console.log(" 2. Run: database migrate:dev --name <migration-name>");
73
+ }
74
+
75
+ //#endregion
76
+ export { runSchemaCompose };
@@ -0,0 +1,51 @@
1
+ import { loadSchemaConfig } from "../lib/schema-config.mjs";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ //#region src/commands/schema-generate.ts
6
+ /**
7
+ * Generate Prisma schema from ContractSpec entity definitions.
8
+ *
9
+ * Usage:
10
+ * database schema:generate --config ./schema.config.ts --output ./prisma/schema
11
+ * database schema:generate --module @lssm/lib.identity-rbac
12
+ */
13
+ async function runSchemaGenerate(argv) {
14
+ console.log("📝 Generating Prisma schema from entity specs...\n");
15
+ const configPath = argv.config ?? "./schema.config.ts";
16
+ const config = await loadSchemaConfig(configPath);
17
+ if (!config) {
18
+ console.error(`❌ Could not load schema config from ${configPath}`);
19
+ process.exit(1);
20
+ }
21
+ const modules = argv.module ? config.modules.filter((m) => m.moduleId === argv.module) : config.modules;
22
+ if (modules.length === 0) {
23
+ console.error("❌ No modules found to generate");
24
+ process.exit(1);
25
+ }
26
+ console.log(`📦 Processing ${modules.length} module(s):`);
27
+ modules.forEach((m) => {
28
+ console.log(` - ${m.moduleId} (${m.entities.length} entities)`);
29
+ });
30
+ console.log("");
31
+ const { composeModuleSchemas } = await import("@lssm/lib.schema");
32
+ const prismaSchema = composeModuleSchemas(modules, {
33
+ provider: config.provider ?? "postgresql",
34
+ clientOutput: config.clientOutput,
35
+ includePothos: config.includePothos ?? true,
36
+ pothosOutput: config.pothosOutput
37
+ });
38
+ const outputPath = argv.output ?? config.outputPath ?? "./prisma/schema/generated.prisma";
39
+ const outputDir = path.dirname(outputPath);
40
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
41
+ fs.writeFileSync(outputPath, prismaSchema, "utf-8");
42
+ console.log(`✅ Generated Prisma schema: ${outputPath}`);
43
+ console.log("");
44
+ console.log("Next steps:");
45
+ console.log(" 1. Review the generated schema");
46
+ console.log(" 2. Run: database generate");
47
+ console.log(" 3. Run: database migrate:dev");
48
+ }
49
+
50
+ //#endregion
51
+ export { runSchemaGenerate };
@@ -0,0 +1,14 @@
1
+ import { execa } from "execa";
2
+
3
+ //#region src/commands/seed.ts
4
+ async function runSeed(argv) {
5
+ try {
6
+ await execa("prisma", ["db", "seed"], { stdio: "inherit" });
7
+ } catch (e) {
8
+ console.warn("No prisma seed configured or seed failed.");
9
+ throw e;
10
+ }
11
+ }
12
+
13
+ //#endregion
14
+ export { runSeed };
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import { defineSchemaConfig, loadSchemaConfig } from "./lib/schema-config.mjs";
2
+ import { defineMergedPrismaConfig } from "./lib/config.mjs";
3
+
4
+ export { defineMergedPrismaConfig, defineSchemaConfig, loadSchemaConfig };
@@ -0,0 +1,7 @@
1
+ //#region src/lib/config.ts
2
+ function defineMergedPrismaConfig(config) {
3
+ return config;
4
+ }
5
+
6
+ //#endregion
7
+ export { defineMergedPrismaConfig };
@@ -0,0 +1,22 @@
1
+ //#region src/lib/schema-config.ts
2
+ /**
3
+ * Define a schema configuration.
4
+ */
5
+ function defineSchemaConfig(config) {
6
+ return config;
7
+ }
8
+ /**
9
+ * Load schema configuration from a file.
10
+ */
11
+ async function loadSchemaConfig(configPath) {
12
+ try {
13
+ const module = await (configPath.startsWith("/") ? import(configPath) : import(`${process.cwd()}/${configPath}`));
14
+ return module.default ?? module.config ?? module;
15
+ } catch (error) {
16
+ console.error(`Failed to load schema config from ${configPath}:`, error);
17
+ return null;
18
+ }
19
+ }
20
+
21
+ //#endregion
22
+ export { defineSchemaConfig, loadSchemaConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lssm/app.cli-database",
3
- "version": "1.41.0",
3
+ "version": "1.41.1",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "database": "dist/cli.js"
@@ -8,6 +8,7 @@
8
8
  "scripts": {
9
9
  "clean": "rm -rf dist",
10
10
  "publish:pkg": "bun publish --tolerate-republish --ignore-scripts --verbose",
11
+ "publish:pkg:canary": "bun publish:pkg --tag canary",
11
12
  "build": "tsdown",
12
13
  "dev": "bun run build --watch",
13
14
  "lint": "bun run lint:fix",
@@ -24,7 +25,7 @@
24
25
  "schema:compose": "database schema:compose"
25
26
  },
26
27
  "dependencies": {
27
- "@lssm/lib.schema": "workspace:*",
28
+ "@lssm/lib.schema": "1.41.1",
28
29
  "@prisma/adapter-pg": "^7.1.0",
29
30
  "@prisma/client": "^7.1.0",
30
31
  "prisma": "^7.1.0",
@@ -32,7 +33,7 @@
32
33
  "execa": "^9.6.1"
33
34
  },
34
35
  "devDependencies": {
35
- "@lssm/tool.tsdown": "workspace:*",
36
+ "@lssm/tool.tsdown": "1.41.1",
36
37
  "@types/minimist": "^1.2.5",
37
38
  "tsdown": "^0.17.4"
38
39
  },