prisma-flare 1.0.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 (45) hide show
  1. package/dist/cli/db-create.cjs +240 -0
  2. package/dist/cli/db-create.d.cts +1 -0
  3. package/dist/cli/db-create.d.ts +1 -0
  4. package/dist/cli/db-create.js +217 -0
  5. package/dist/cli/db-drop.cjs +263 -0
  6. package/dist/cli/db-drop.d.cts +1 -0
  7. package/dist/cli/db-drop.d.ts +1 -0
  8. package/dist/cli/db-drop.js +240 -0
  9. package/dist/cli/db-migrate.cjs +318 -0
  10. package/dist/cli/db-migrate.d.cts +1 -0
  11. package/dist/cli/db-migrate.d.ts +1 -0
  12. package/dist/cli/db-migrate.js +295 -0
  13. package/dist/cli/db-reset.cjs +110 -0
  14. package/dist/cli/db-reset.d.cts +1 -0
  15. package/dist/cli/db-reset.d.ts +1 -0
  16. package/dist/cli/db-reset.js +87 -0
  17. package/dist/cli/db-seed.cjs +87 -0
  18. package/dist/cli/db-seed.d.cts +1 -0
  19. package/dist/cli/db-seed.d.ts +1 -0
  20. package/dist/cli/db-seed.js +64 -0
  21. package/dist/cli/index.cjs +352 -0
  22. package/dist/cli/index.d.cts +1 -0
  23. package/dist/cli/index.d.ts +1 -0
  24. package/dist/cli/index.js +328 -0
  25. package/dist/core/flareBuilder.cjs +681 -0
  26. package/dist/core/flareBuilder.d.cts +402 -0
  27. package/dist/core/flareBuilder.d.ts +402 -0
  28. package/dist/core/flareBuilder.js +658 -0
  29. package/dist/core/hooks.cjs +243 -0
  30. package/dist/core/hooks.d.cts +13 -0
  31. package/dist/core/hooks.d.ts +13 -0
  32. package/dist/core/hooks.js +209 -0
  33. package/dist/generated.cjs +31 -0
  34. package/dist/generated.d.cts +4 -0
  35. package/dist/generated.d.ts +4 -0
  36. package/dist/generated.js +6 -0
  37. package/dist/index.cjs +1315 -0
  38. package/dist/index.d.cts +237 -0
  39. package/dist/index.d.ts +237 -0
  40. package/dist/index.js +1261 -0
  41. package/dist/prisma.types-nGNe1CG8.d.cts +201 -0
  42. package/dist/prisma.types-nGNe1CG8.d.ts +201 -0
  43. package/license.md +21 -0
  44. package/package.json +115 -0
  45. package/readme.md +957 -0
@@ -0,0 +1,352 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli/generate-queries.ts
27
+ var fs2 = __toESM(require("fs"), 1);
28
+ var path2 = __toESM(require("path"), 1);
29
+ var import_pluralize = __toESM(require("pluralize"), 1);
30
+
31
+ // src/cli/config.ts
32
+ var fs = __toESM(require("fs"), 1);
33
+ var path = __toESM(require("path"), 1);
34
+ function findProjectRoot(currentDir) {
35
+ if (fs.existsSync(path.join(currentDir, "package.json"))) {
36
+ return currentDir;
37
+ }
38
+ const parentDir = path.dirname(currentDir);
39
+ if (parentDir === currentDir) {
40
+ throw new Error("Could not find package.json");
41
+ }
42
+ return findProjectRoot(parentDir);
43
+ }
44
+ function loadConfig(rootDir) {
45
+ const projectRoot = rootDir || findProjectRoot(process.cwd());
46
+ const configPath = path.join(projectRoot, "prisma-flare.config.json");
47
+ let config = {
48
+ modelsPath: "prisma/models",
49
+ dbPath: "prisma/db",
50
+ callbacksPath: "prisma/callbacks"
51
+ };
52
+ if (fs.existsSync(configPath)) {
53
+ try {
54
+ const configFile = fs.readFileSync(configPath, "utf-8");
55
+ const userConfig = JSON.parse(configFile);
56
+ config = { ...config, ...userConfig };
57
+ } catch {
58
+ console.warn("\u26A0\uFE0F Could not read prisma-flare.config.json, using defaults.");
59
+ }
60
+ }
61
+ return {
62
+ ...config
63
+ };
64
+ }
65
+
66
+ // src/cli/generate-queries.ts
67
+ function toCamelCase(str) {
68
+ return str.charAt(0).toLowerCase() + str.slice(1);
69
+ }
70
+ function parseRelations(schemaContent, models) {
71
+ const relations = /* @__PURE__ */ new Map();
72
+ models.forEach((model) => relations.set(model, []));
73
+ const modelBlockRegex = /model\s+(\w+)\s+{([^}]+)}/g;
74
+ let modelMatch;
75
+ while ((modelMatch = modelBlockRegex.exec(schemaContent)) !== null) {
76
+ const modelName = modelMatch[1];
77
+ const modelBody = modelMatch[2];
78
+ const lines = modelBody.split("\n");
79
+ for (const line of lines) {
80
+ const trimmed = line.trim();
81
+ if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("@")) continue;
82
+ const fieldMatch = trimmed.match(/^(\w+)\s+(\w+)(\[\])?\s*/);
83
+ if (fieldMatch) {
84
+ const fieldName = fieldMatch[1];
85
+ const fieldType = fieldMatch[2];
86
+ const isArray = !!fieldMatch[3];
87
+ if (models.includes(fieldType)) {
88
+ const modelRelations = relations.get(modelName) || [];
89
+ modelRelations.push({ fieldName, targetModel: fieldType });
90
+ relations.set(modelName, modelRelations);
91
+ }
92
+ }
93
+ }
94
+ }
95
+ return relations;
96
+ }
97
+ function generateQueries() {
98
+ const rootDir = findProjectRoot(process.cwd());
99
+ const config = loadConfig(rootDir);
100
+ const schemaPath = path2.join(rootDir, "prisma", "schema.prisma");
101
+ if (!fs2.existsSync(schemaPath)) {
102
+ console.error(`\u274C Schema not found at ${schemaPath}`);
103
+ return;
104
+ }
105
+ const schemaContent = fs2.readFileSync(schemaPath, "utf-8");
106
+ const modelRegex = /model\s+(\w+)\s+{/g;
107
+ const models = [];
108
+ let match;
109
+ while ((match = modelRegex.exec(schemaContent)) !== null) {
110
+ models.push(match[1]);
111
+ }
112
+ const queriesDir = path2.join(rootDir, config.modelsPath);
113
+ if (!fs2.existsSync(queriesDir)) {
114
+ fs2.mkdirSync(queriesDir, { recursive: true });
115
+ }
116
+ const absDbPath = path2.join(rootDir, config.dbPath);
117
+ let relativePathToDb = path2.relative(queriesDir, absDbPath);
118
+ if (!relativePathToDb.startsWith(".")) relativePathToDb = "./" + relativePathToDb;
119
+ relativePathToDb = relativePathToDb.replace(/\\/g, "/");
120
+ models.forEach((model) => {
121
+ const queryFileName = `${model}.ts`;
122
+ const queryFilePath = path2.join(queriesDir, queryFileName);
123
+ const modelCamel = toCamelCase(model);
124
+ if (fs2.existsSync(queryFilePath)) {
125
+ return;
126
+ }
127
+ console.log(`Generating ${queryFileName}...`);
128
+ let queryBuilderImport = "import { FlareBuilder } from 'prisma-flare';";
129
+ const localQueryBuilderPath = path2.join(rootDir, "src/core/flareBuilder.ts");
130
+ if (fs2.existsSync(localQueryBuilderPath)) {
131
+ const absSrcPath = path2.join(rootDir, "src");
132
+ let relativePathToSrc = path2.relative(queriesDir, absSrcPath);
133
+ if (!relativePathToSrc.startsWith(".")) relativePathToSrc = "./" + relativePathToSrc;
134
+ relativePathToSrc = relativePathToSrc.replace(/\\/g, "/");
135
+ queryBuilderImport = `import { FlareBuilder } from '${relativePathToSrc}';`;
136
+ }
137
+ const content = `import { db } from '${relativePathToDb}';
138
+ ${queryBuilderImport}
139
+
140
+ export default class ${model} extends FlareBuilder<'${modelCamel}'> {
141
+ constructor() {
142
+ super(db.${modelCamel});
143
+ }
144
+ }
145
+ `;
146
+ fs2.writeFileSync(queryFilePath, content);
147
+ });
148
+ let pfDistDir;
149
+ const pfPackageDir = path2.join(rootDir, "node_modules", "prisma-flare");
150
+ let realPfPackageDir = pfPackageDir;
151
+ if (fs2.existsSync(pfPackageDir)) {
152
+ realPfPackageDir = fs2.realpathSync(pfPackageDir);
153
+ }
154
+ pfDistDir = path2.join(realPfPackageDir, "dist");
155
+ let dbPathWithExt = absDbPath;
156
+ if (!absDbPath.endsWith(".ts") && !absDbPath.endsWith(".js")) {
157
+ if (fs2.existsSync(absDbPath + ".ts")) {
158
+ dbPathWithExt = absDbPath + ".ts";
159
+ } else if (fs2.existsSync(absDbPath + ".js")) {
160
+ dbPathWithExt = absDbPath + ".js";
161
+ }
162
+ }
163
+ let relativePathToDbForDist = path2.relative(pfDistDir, dbPathWithExt);
164
+ if (!relativePathToDbForDist.startsWith(".")) relativePathToDbForDist = "./" + relativePathToDbForDist;
165
+ relativePathToDbForDist = relativePathToDbForDist.replace(/\\/g, "/");
166
+ const relativePathToDbForDts = relativePathToDbForDist;
167
+ const absModelsPath = path2.join(queriesDir);
168
+ let relativePathToModels = path2.relative(pfDistDir, absModelsPath);
169
+ if (!relativePathToModels.startsWith(".")) relativePathToModels = "./" + relativePathToModels;
170
+ relativePathToModels = relativePathToModels.replace(/\\/g, "/");
171
+ const relations = parseRelations(schemaContent, models);
172
+ const getters = models.map((model) => {
173
+ const modelCamel = toCamelCase(model);
174
+ const customPlural = config.plurals?.[model];
175
+ const modelPlural = customPlural || (0, import_pluralize.default)(modelCamel);
176
+ return ` static get ${modelPlural}() {
177
+ return new ${model}();
178
+ }`;
179
+ }).join("\n\n");
180
+ const registrationLines = [];
181
+ models.forEach((model) => {
182
+ const modelCamel = toCamelCase(model);
183
+ const customPlural = config.plurals?.[model];
184
+ const modelPlural = customPlural || (0, import_pluralize.default)(modelCamel);
185
+ registrationLines.push(`modelRegistry.register('${modelCamel}', ${model});`);
186
+ registrationLines.push(`modelRegistry.register('${modelPlural}', ${model});`);
187
+ });
188
+ relations.forEach((rels, modelName) => {
189
+ rels.forEach((rel) => {
190
+ registrationLines.push(`modelRegistry.register('${rel.fieldName}', ${rel.targetModel});`);
191
+ });
192
+ });
193
+ const modelRegistrations = registrationLines.join("\n");
194
+ const generatedJsPath = path2.join(pfDistDir, "generated.js");
195
+ const imports = models.map((model) => {
196
+ return `import ${model} from '${relativePathToModels}/${model}.ts';`;
197
+ }).join("\n");
198
+ const generatedContent = `
199
+ import { db } from '${relativePathToDbForDist}';
200
+ import { modelRegistry } from './index.js';
201
+ ${imports}
202
+
203
+ // Register all models so include() can use custom model classes
204
+ ${modelRegistrations}
205
+
206
+ export class DB {
207
+ static get instance() {
208
+ return db;
209
+ }
210
+
211
+ ${getters}
212
+ }
213
+ `;
214
+ fs2.writeFileSync(generatedJsPath, generatedContent);
215
+ const generatedCjsPath = path2.join(pfDistDir, "generated.cjs");
216
+ const importsCjs = models.map((model) => {
217
+ return `const ${model} = require('${relativePathToModels}/${model}').default;`;
218
+ }).join("\n");
219
+ const generatedCjsContent = `
220
+ const { db } = require('${relativePathToDbForDist}');
221
+ const { modelRegistry } = require('./index.cjs');
222
+ ${importsCjs}
223
+
224
+ // Register all models so include() can use custom model classes
225
+ ${modelRegistrations}
226
+
227
+ class DB {
228
+ static get instance() {
229
+ return db;
230
+ }
231
+
232
+ ${getters}
233
+ }
234
+ exports.DB = DB;
235
+ `;
236
+ fs2.writeFileSync(generatedCjsPath, generatedCjsContent);
237
+ const generatedDtsPath = path2.join(pfDistDir, "generated.d.ts");
238
+ const importsDts = models.map((model) => {
239
+ return `import ${model} from '${relativePathToModels}/${model}.ts';`;
240
+ }).join("\n");
241
+ const gettersTypes = models.map((model) => {
242
+ const modelCamel = toCamelCase(model);
243
+ const customPlural = config.plurals?.[model];
244
+ const modelPlural = customPlural || (0, import_pluralize.default)(modelCamel);
245
+ return ` static get ${modelPlural}(): ${model};`;
246
+ }).join("\n");
247
+ const relationMapEntries = [];
248
+ models.forEach((model) => {
249
+ const modelCamel = toCamelCase(model);
250
+ const customPlural = config.plurals?.[model];
251
+ const modelPlural = customPlural || (0, import_pluralize.default)(modelCamel);
252
+ relationMapEntries.push(` ${modelCamel}: ${model};`);
253
+ relationMapEntries.push(` ${modelPlural}: ${model};`);
254
+ });
255
+ relations.forEach((rels, modelName) => {
256
+ rels.forEach((rel) => {
257
+ const entry = ` ${rel.fieldName}: ${rel.targetModel};`;
258
+ if (!relationMapEntries.includes(entry)) {
259
+ relationMapEntries.push(entry);
260
+ }
261
+ });
262
+ });
263
+ const generatedDtsContent = `
264
+ import { db } from '${relativePathToDbForDts}';
265
+ ${importsDts}
266
+
267
+ /**
268
+ * Module augmentation to provide type-safe includes.
269
+ * This maps relation field names to their custom model classes.
270
+ */
271
+ declare module 'prisma-flare' {
272
+ interface RelationModelMap {
273
+ ${relationMapEntries.join("\n")}
274
+ }
275
+ }
276
+
277
+ export declare class DB {
278
+ static get instance(): typeof db;
279
+
280
+ ${gettersTypes}
281
+ }
282
+ `;
283
+ fs2.writeFileSync(generatedDtsPath, generatedDtsContent);
284
+ }
285
+
286
+ // src/cli/index.ts
287
+ var import_child_process = require("child_process");
288
+ var path3 = __toESM(require("path"), 1);
289
+ var fs3 = __toESM(require("fs"), 1);
290
+ var import_url = require("url");
291
+ var import_meta = {};
292
+ var getDirname = () => {
293
+ try {
294
+ return path3.dirname((0, import_url.fileURLToPath)(import_meta.url));
295
+ } catch {
296
+ return __dirname;
297
+ }
298
+ };
299
+ var __dirname_ = getDirname();
300
+ var args = process.argv.slice(2);
301
+ var command = args[0];
302
+ if (!command) {
303
+ console.log("Usage: prisma-flare <command>");
304
+ console.log("Commands:");
305
+ console.log(" generate Generate query classes based on schema.prisma");
306
+ console.log(" create Create the database");
307
+ console.log(" drop Drop the database");
308
+ console.log(" migrate Migrate the database");
309
+ console.log(" reset Reset the database");
310
+ console.log(" seed Seed the database");
311
+ process.exit(1);
312
+ }
313
+ switch (command) {
314
+ case "generate":
315
+ generateQueries();
316
+ break;
317
+ case "create":
318
+ case "drop":
319
+ case "migrate":
320
+ case "reset":
321
+ case "seed":
322
+ runScript(command);
323
+ break;
324
+ default:
325
+ console.error(`Unknown command: ${command}`);
326
+ process.exit(1);
327
+ }
328
+ function runScript(scriptName) {
329
+ const scriptMap = {
330
+ "create": "db-create.ts",
331
+ "drop": "db-drop.ts",
332
+ "migrate": "db-migrate.ts",
333
+ "reset": "db-reset.ts",
334
+ "seed": "db-seed.ts"
335
+ };
336
+ const file = scriptMap[scriptName];
337
+ if (!file) {
338
+ console.error(`No script found for ${scriptName}`);
339
+ return;
340
+ }
341
+ let scriptPath = path3.join(__dirname_, file.replace(".ts", ".js"));
342
+ if (!fs3.existsSync(scriptPath)) {
343
+ const cliScriptPath = path3.join(__dirname_, "cli", file.replace(".ts", ".js"));
344
+ if (fs3.existsSync(cliScriptPath)) {
345
+ scriptPath = cliScriptPath;
346
+ }
347
+ }
348
+ const child = (0, import_child_process.spawn)("node", [scriptPath], { stdio: "inherit" });
349
+ child.on("close", (code) => {
350
+ process.exit(code || 0);
351
+ });
352
+ }
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
@@ -0,0 +1,328 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/generate-queries.ts
4
+ import * as fs2 from "fs";
5
+ import * as path2 from "path";
6
+ import pluralize from "pluralize";
7
+
8
+ // src/cli/config.ts
9
+ import * as fs from "fs";
10
+ import * as path from "path";
11
+ function findProjectRoot(currentDir) {
12
+ if (fs.existsSync(path.join(currentDir, "package.json"))) {
13
+ return currentDir;
14
+ }
15
+ const parentDir = path.dirname(currentDir);
16
+ if (parentDir === currentDir) {
17
+ throw new Error("Could not find package.json");
18
+ }
19
+ return findProjectRoot(parentDir);
20
+ }
21
+ function loadConfig(rootDir) {
22
+ const projectRoot = rootDir || findProjectRoot(process.cwd());
23
+ const configPath = path.join(projectRoot, "prisma-flare.config.json");
24
+ let config = {
25
+ modelsPath: "prisma/models",
26
+ dbPath: "prisma/db",
27
+ callbacksPath: "prisma/callbacks"
28
+ };
29
+ if (fs.existsSync(configPath)) {
30
+ try {
31
+ const configFile = fs.readFileSync(configPath, "utf-8");
32
+ const userConfig = JSON.parse(configFile);
33
+ config = { ...config, ...userConfig };
34
+ } catch {
35
+ console.warn("\u26A0\uFE0F Could not read prisma-flare.config.json, using defaults.");
36
+ }
37
+ }
38
+ return {
39
+ ...config
40
+ };
41
+ }
42
+
43
+ // src/cli/generate-queries.ts
44
+ function toCamelCase(str) {
45
+ return str.charAt(0).toLowerCase() + str.slice(1);
46
+ }
47
+ function parseRelations(schemaContent, models) {
48
+ const relations = /* @__PURE__ */ new Map();
49
+ models.forEach((model) => relations.set(model, []));
50
+ const modelBlockRegex = /model\s+(\w+)\s+{([^}]+)}/g;
51
+ let modelMatch;
52
+ while ((modelMatch = modelBlockRegex.exec(schemaContent)) !== null) {
53
+ const modelName = modelMatch[1];
54
+ const modelBody = modelMatch[2];
55
+ const lines = modelBody.split("\n");
56
+ for (const line of lines) {
57
+ const trimmed = line.trim();
58
+ if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("@")) continue;
59
+ const fieldMatch = trimmed.match(/^(\w+)\s+(\w+)(\[\])?\s*/);
60
+ if (fieldMatch) {
61
+ const fieldName = fieldMatch[1];
62
+ const fieldType = fieldMatch[2];
63
+ const isArray = !!fieldMatch[3];
64
+ if (models.includes(fieldType)) {
65
+ const modelRelations = relations.get(modelName) || [];
66
+ modelRelations.push({ fieldName, targetModel: fieldType });
67
+ relations.set(modelName, modelRelations);
68
+ }
69
+ }
70
+ }
71
+ }
72
+ return relations;
73
+ }
74
+ function generateQueries() {
75
+ const rootDir = findProjectRoot(process.cwd());
76
+ const config = loadConfig(rootDir);
77
+ const schemaPath = path2.join(rootDir, "prisma", "schema.prisma");
78
+ if (!fs2.existsSync(schemaPath)) {
79
+ console.error(`\u274C Schema not found at ${schemaPath}`);
80
+ return;
81
+ }
82
+ const schemaContent = fs2.readFileSync(schemaPath, "utf-8");
83
+ const modelRegex = /model\s+(\w+)\s+{/g;
84
+ const models = [];
85
+ let match;
86
+ while ((match = modelRegex.exec(schemaContent)) !== null) {
87
+ models.push(match[1]);
88
+ }
89
+ const queriesDir = path2.join(rootDir, config.modelsPath);
90
+ if (!fs2.existsSync(queriesDir)) {
91
+ fs2.mkdirSync(queriesDir, { recursive: true });
92
+ }
93
+ const absDbPath = path2.join(rootDir, config.dbPath);
94
+ let relativePathToDb = path2.relative(queriesDir, absDbPath);
95
+ if (!relativePathToDb.startsWith(".")) relativePathToDb = "./" + relativePathToDb;
96
+ relativePathToDb = relativePathToDb.replace(/\\/g, "/");
97
+ models.forEach((model) => {
98
+ const queryFileName = `${model}.ts`;
99
+ const queryFilePath = path2.join(queriesDir, queryFileName);
100
+ const modelCamel = toCamelCase(model);
101
+ if (fs2.existsSync(queryFilePath)) {
102
+ return;
103
+ }
104
+ console.log(`Generating ${queryFileName}...`);
105
+ let queryBuilderImport = "import { FlareBuilder } from 'prisma-flare';";
106
+ const localQueryBuilderPath = path2.join(rootDir, "src/core/flareBuilder.ts");
107
+ if (fs2.existsSync(localQueryBuilderPath)) {
108
+ const absSrcPath = path2.join(rootDir, "src");
109
+ let relativePathToSrc = path2.relative(queriesDir, absSrcPath);
110
+ if (!relativePathToSrc.startsWith(".")) relativePathToSrc = "./" + relativePathToSrc;
111
+ relativePathToSrc = relativePathToSrc.replace(/\\/g, "/");
112
+ queryBuilderImport = `import { FlareBuilder } from '${relativePathToSrc}';`;
113
+ }
114
+ const content = `import { db } from '${relativePathToDb}';
115
+ ${queryBuilderImport}
116
+
117
+ export default class ${model} extends FlareBuilder<'${modelCamel}'> {
118
+ constructor() {
119
+ super(db.${modelCamel});
120
+ }
121
+ }
122
+ `;
123
+ fs2.writeFileSync(queryFilePath, content);
124
+ });
125
+ let pfDistDir;
126
+ const pfPackageDir = path2.join(rootDir, "node_modules", "prisma-flare");
127
+ let realPfPackageDir = pfPackageDir;
128
+ if (fs2.existsSync(pfPackageDir)) {
129
+ realPfPackageDir = fs2.realpathSync(pfPackageDir);
130
+ }
131
+ pfDistDir = path2.join(realPfPackageDir, "dist");
132
+ let dbPathWithExt = absDbPath;
133
+ if (!absDbPath.endsWith(".ts") && !absDbPath.endsWith(".js")) {
134
+ if (fs2.existsSync(absDbPath + ".ts")) {
135
+ dbPathWithExt = absDbPath + ".ts";
136
+ } else if (fs2.existsSync(absDbPath + ".js")) {
137
+ dbPathWithExt = absDbPath + ".js";
138
+ }
139
+ }
140
+ let relativePathToDbForDist = path2.relative(pfDistDir, dbPathWithExt);
141
+ if (!relativePathToDbForDist.startsWith(".")) relativePathToDbForDist = "./" + relativePathToDbForDist;
142
+ relativePathToDbForDist = relativePathToDbForDist.replace(/\\/g, "/");
143
+ const relativePathToDbForDts = relativePathToDbForDist;
144
+ const absModelsPath = path2.join(queriesDir);
145
+ let relativePathToModels = path2.relative(pfDistDir, absModelsPath);
146
+ if (!relativePathToModels.startsWith(".")) relativePathToModels = "./" + relativePathToModels;
147
+ relativePathToModels = relativePathToModels.replace(/\\/g, "/");
148
+ const relations = parseRelations(schemaContent, models);
149
+ const getters = models.map((model) => {
150
+ const modelCamel = toCamelCase(model);
151
+ const customPlural = config.plurals?.[model];
152
+ const modelPlural = customPlural || pluralize(modelCamel);
153
+ return ` static get ${modelPlural}() {
154
+ return new ${model}();
155
+ }`;
156
+ }).join("\n\n");
157
+ const registrationLines = [];
158
+ models.forEach((model) => {
159
+ const modelCamel = toCamelCase(model);
160
+ const customPlural = config.plurals?.[model];
161
+ const modelPlural = customPlural || pluralize(modelCamel);
162
+ registrationLines.push(`modelRegistry.register('${modelCamel}', ${model});`);
163
+ registrationLines.push(`modelRegistry.register('${modelPlural}', ${model});`);
164
+ });
165
+ relations.forEach((rels, modelName) => {
166
+ rels.forEach((rel) => {
167
+ registrationLines.push(`modelRegistry.register('${rel.fieldName}', ${rel.targetModel});`);
168
+ });
169
+ });
170
+ const modelRegistrations = registrationLines.join("\n");
171
+ const generatedJsPath = path2.join(pfDistDir, "generated.js");
172
+ const imports = models.map((model) => {
173
+ return `import ${model} from '${relativePathToModels}/${model}.ts';`;
174
+ }).join("\n");
175
+ const generatedContent = `
176
+ import { db } from '${relativePathToDbForDist}';
177
+ import { modelRegistry } from './index.js';
178
+ ${imports}
179
+
180
+ // Register all models so include() can use custom model classes
181
+ ${modelRegistrations}
182
+
183
+ export class DB {
184
+ static get instance() {
185
+ return db;
186
+ }
187
+
188
+ ${getters}
189
+ }
190
+ `;
191
+ fs2.writeFileSync(generatedJsPath, generatedContent);
192
+ const generatedCjsPath = path2.join(pfDistDir, "generated.cjs");
193
+ const importsCjs = models.map((model) => {
194
+ return `const ${model} = require('${relativePathToModels}/${model}').default;`;
195
+ }).join("\n");
196
+ const generatedCjsContent = `
197
+ const { db } = require('${relativePathToDbForDist}');
198
+ const { modelRegistry } = require('./index.cjs');
199
+ ${importsCjs}
200
+
201
+ // Register all models so include() can use custom model classes
202
+ ${modelRegistrations}
203
+
204
+ class DB {
205
+ static get instance() {
206
+ return db;
207
+ }
208
+
209
+ ${getters}
210
+ }
211
+ exports.DB = DB;
212
+ `;
213
+ fs2.writeFileSync(generatedCjsPath, generatedCjsContent);
214
+ const generatedDtsPath = path2.join(pfDistDir, "generated.d.ts");
215
+ const importsDts = models.map((model) => {
216
+ return `import ${model} from '${relativePathToModels}/${model}.ts';`;
217
+ }).join("\n");
218
+ const gettersTypes = models.map((model) => {
219
+ const modelCamel = toCamelCase(model);
220
+ const customPlural = config.plurals?.[model];
221
+ const modelPlural = customPlural || pluralize(modelCamel);
222
+ return ` static get ${modelPlural}(): ${model};`;
223
+ }).join("\n");
224
+ const relationMapEntries = [];
225
+ models.forEach((model) => {
226
+ const modelCamel = toCamelCase(model);
227
+ const customPlural = config.plurals?.[model];
228
+ const modelPlural = customPlural || pluralize(modelCamel);
229
+ relationMapEntries.push(` ${modelCamel}: ${model};`);
230
+ relationMapEntries.push(` ${modelPlural}: ${model};`);
231
+ });
232
+ relations.forEach((rels, modelName) => {
233
+ rels.forEach((rel) => {
234
+ const entry = ` ${rel.fieldName}: ${rel.targetModel};`;
235
+ if (!relationMapEntries.includes(entry)) {
236
+ relationMapEntries.push(entry);
237
+ }
238
+ });
239
+ });
240
+ const generatedDtsContent = `
241
+ import { db } from '${relativePathToDbForDts}';
242
+ ${importsDts}
243
+
244
+ /**
245
+ * Module augmentation to provide type-safe includes.
246
+ * This maps relation field names to their custom model classes.
247
+ */
248
+ declare module 'prisma-flare' {
249
+ interface RelationModelMap {
250
+ ${relationMapEntries.join("\n")}
251
+ }
252
+ }
253
+
254
+ export declare class DB {
255
+ static get instance(): typeof db;
256
+
257
+ ${gettersTypes}
258
+ }
259
+ `;
260
+ fs2.writeFileSync(generatedDtsPath, generatedDtsContent);
261
+ }
262
+
263
+ // src/cli/index.ts
264
+ import { spawn } from "child_process";
265
+ import * as path3 from "path";
266
+ import * as fs3 from "fs";
267
+ import { fileURLToPath } from "url";
268
+ var getDirname = () => {
269
+ try {
270
+ return path3.dirname(fileURLToPath(import.meta.url));
271
+ } catch {
272
+ return __dirname;
273
+ }
274
+ };
275
+ var __dirname_ = getDirname();
276
+ var args = process.argv.slice(2);
277
+ var command = args[0];
278
+ if (!command) {
279
+ console.log("Usage: prisma-flare <command>");
280
+ console.log("Commands:");
281
+ console.log(" generate Generate query classes based on schema.prisma");
282
+ console.log(" create Create the database");
283
+ console.log(" drop Drop the database");
284
+ console.log(" migrate Migrate the database");
285
+ console.log(" reset Reset the database");
286
+ console.log(" seed Seed the database");
287
+ process.exit(1);
288
+ }
289
+ switch (command) {
290
+ case "generate":
291
+ generateQueries();
292
+ break;
293
+ case "create":
294
+ case "drop":
295
+ case "migrate":
296
+ case "reset":
297
+ case "seed":
298
+ runScript(command);
299
+ break;
300
+ default:
301
+ console.error(`Unknown command: ${command}`);
302
+ process.exit(1);
303
+ }
304
+ function runScript(scriptName) {
305
+ const scriptMap = {
306
+ "create": "db-create.ts",
307
+ "drop": "db-drop.ts",
308
+ "migrate": "db-migrate.ts",
309
+ "reset": "db-reset.ts",
310
+ "seed": "db-seed.ts"
311
+ };
312
+ const file = scriptMap[scriptName];
313
+ if (!file) {
314
+ console.error(`No script found for ${scriptName}`);
315
+ return;
316
+ }
317
+ let scriptPath = path3.join(__dirname_, file.replace(".ts", ".js"));
318
+ if (!fs3.existsSync(scriptPath)) {
319
+ const cliScriptPath = path3.join(__dirname_, "cli", file.replace(".ts", ".js"));
320
+ if (fs3.existsSync(cliScriptPath)) {
321
+ scriptPath = cliScriptPath;
322
+ }
323
+ }
324
+ const child = spawn("node", [scriptPath], { stdio: "inherit" });
325
+ child.on("close", (code) => {
326
+ process.exit(code || 0);
327
+ });
328
+ }