arkos 1.4.1-canary.7 → 1.5.0-canary.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.
- package/dist/cjs/modules/auth/auth.controller.js +13 -0
- package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +40 -14
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js +1 -1
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +6 -4
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/base/utils/error-prettifier.js +185 -0
- package/dist/cjs/modules/base/utils/error-prettifier.js.map +1 -0
- package/dist/cjs/modules/email/email.service.js +4 -1
- package/dist/cjs/modules/email/email.service.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +9 -3
- package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
- package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
- package/dist/cjs/types/auth.js.map +1 -1
- package/dist/cjs/utils/arkos-router/index.js +7 -1
- package/dist/cjs/utils/arkos-router/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js +51 -0
- package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/cjs/utils/cli/generate.js +38 -0
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +37 -4
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
- package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +556 -0
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js +327 -0
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
- package/dist/cjs/utils/cli/utils/template-generators.js +14 -8
- package/dist/cjs/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/cjs/utils/dynamic-loader.js +2 -2
- package/dist/cjs/utils/dynamic-loader.js.map +1 -1
- package/dist/cjs/utils/helpers/routers.helpers.js +2 -3
- package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +19 -4
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/modules/auth/auth.controller.js +13 -0
- package/dist/esm/modules/auth/auth.controller.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +40 -14
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/auth/utils/services/auth-action.service.js +1 -1
- package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/esm/modules/base/base.middlewares.js +6 -4
- package/dist/esm/modules/base/base.middlewares.js.map +1 -1
- package/dist/esm/modules/base/utils/error-prettifier.js +181 -0
- package/dist/esm/modules/base/utils/error-prettifier.js.map +1 -0
- package/dist/esm/modules/email/email.service.js +4 -1
- package/dist/esm/modules/email/email.service.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +9 -3
- package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
- package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
- package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
- package/dist/esm/types/auth.js.map +1 -1
- package/dist/esm/utils/arkos-router/index.js +8 -2
- package/dist/esm/utils/arkos-router/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/arkos-router/utils/helpers/index.js +50 -0
- package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
- package/dist/esm/utils/cli/generate.js +38 -0
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/index.js +37 -4
- package/dist/esm/utils/cli/index.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
- package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +549 -0
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
- package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js +320 -0
- package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
- package/dist/esm/utils/cli/utils/template-generators.js +14 -8
- package/dist/esm/utils/cli/utils/template-generators.js.map +1 -1
- package/dist/esm/utils/dynamic-loader.js +2 -2
- package/dist/esm/utils/dynamic-loader.js.map +1 -1
- package/dist/esm/utils/helpers/routers.helpers.js +2 -3
- package/dist/esm/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +19 -4
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
- package/dist/types/modules/auth/auth.service.d.ts +5 -0
- package/dist/types/modules/auth/utils/services/auth-action.service.d.ts +1 -1
- package/dist/types/modules/base/utils/error-prettifier.d.ts +19 -0
- package/dist/types/modules/email/email.service.d.ts +4 -8
- package/dist/types/types/auth.d.ts +3 -3
- package/dist/types/utils/arkos-router/index.d.ts +3 -1
- package/dist/types/utils/arkos-router/types/index.d.ts +2 -2
- package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +4 -0
- package/dist/types/utils/cli/generate.d.ts +4 -0
- package/dist/types/utils/cli/utils/template-generator/templates/auth-configs-template.d.ts +3 -1
- package/dist/types/utils/cli/utils/template-generator/templates/class-validator-dto-generator.d.ts +18 -0
- package/dist/types/utils/cli/utils/template-generator/templates/zod-schema-generator.d.ts +14 -0
- package/dist/types/utils/helpers/routers.helpers.d.ts +1 -1
- package/package.json +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -187
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -181
- package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -106
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -104
- package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -181
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -175
- package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -100
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -98
- package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
- package/dist/types/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/zod/create-schema-template.d.ts +0 -2
- package/dist/types/utils/cli/utils/template-generator/templates/zod/update-schema-template.d.ts +0 -2
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.ZodSchemaGenerator = void 0;
|
|
7
|
+
const prisma_schema_parser_1 = __importDefault(require("../../../../prisma/prisma-schema-parser"));
|
|
8
|
+
const fs_helpers_1 = require("../../../../helpers/fs.helpers");
|
|
9
|
+
class ZodSchemaGenerator {
|
|
10
|
+
ensureCorrectOptions(options) {
|
|
11
|
+
const { modelName } = options;
|
|
12
|
+
if (!modelName)
|
|
13
|
+
throw new Error("Module name is required for schema template");
|
|
14
|
+
const model = prisma_schema_parser_1.default.models.find((m) => m.name.toLowerCase() === modelName.pascal.toLowerCase());
|
|
15
|
+
if (!model)
|
|
16
|
+
throw new Error(`Model ${modelName.pascal} not found in Prisma schema`);
|
|
17
|
+
return model;
|
|
18
|
+
}
|
|
19
|
+
generateCreateSchema(options) {
|
|
20
|
+
const { modelName } = options;
|
|
21
|
+
const model = this.ensureCorrectOptions(options);
|
|
22
|
+
const ext = (0, fs_helpers_1.getUserFileExtension)();
|
|
23
|
+
const isTypeScript = ext === "ts";
|
|
24
|
+
const restrictedFields = ["id", "createdAt", "updatedAt", "deletedAt"];
|
|
25
|
+
const isUserModule = modelName.kebab === "user";
|
|
26
|
+
const enumsUsed = new Set();
|
|
27
|
+
let schemaFields = [];
|
|
28
|
+
for (const field of model.fields) {
|
|
29
|
+
const isForeignKey = model.fields.some((f) => f.foreignKeyField === field.name);
|
|
30
|
+
if (field.isId || restrictedFields.includes(field.name) || isForeignKey)
|
|
31
|
+
continue;
|
|
32
|
+
if (field.isRelation) {
|
|
33
|
+
if (field.isArray)
|
|
34
|
+
continue;
|
|
35
|
+
const referencedModel = prisma_schema_parser_1.default.models.find((m) => m.name === field.type);
|
|
36
|
+
if (referencedModel) {
|
|
37
|
+
const refField = field.foreignReferenceField || "id";
|
|
38
|
+
const refFieldType = referencedModel.fields.find((f) => f.name === refField);
|
|
39
|
+
const zodType = this.mapPrismaTypeToZod(refFieldType?.type);
|
|
40
|
+
const isOptional = field.isOptional || field.defaultValue !== undefined;
|
|
41
|
+
schemaFields.push(` ${field.name}: z.object({ ${refField}: ${zodType} })${isOptional ? ".optional()" : ""}`);
|
|
42
|
+
}
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (prisma_schema_parser_1.default.isEnum(field.type))
|
|
46
|
+
enumsUsed.add(field.type);
|
|
47
|
+
const zodSchema = this.generateZodField(field, isUserModule, false);
|
|
48
|
+
schemaFields.push(` ${field.name}: ${zodSchema}`);
|
|
49
|
+
}
|
|
50
|
+
const enumImports = enumsUsed.size > 0
|
|
51
|
+
? `import { ${Array.from(enumsUsed).join(", ")} } from "@prisma/client";\n`
|
|
52
|
+
: "";
|
|
53
|
+
const typeExport = isTypeScript
|
|
54
|
+
? `\n\nexport type Create${modelName.pascal}SchemaType = z.infer<typeof Create${modelName.pascal}Schema>;`
|
|
55
|
+
: "";
|
|
56
|
+
return `import { z } from "zod";
|
|
57
|
+
${enumImports}
|
|
58
|
+
const Create${modelName.pascal}Schema = z.object({
|
|
59
|
+
${schemaFields.join(",\n")}
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
export default Create${modelName.pascal}Schema;${typeExport}
|
|
63
|
+
`;
|
|
64
|
+
}
|
|
65
|
+
generateUpdateSchema(options) {
|
|
66
|
+
const { modelName } = options;
|
|
67
|
+
const model = this.ensureCorrectOptions(options);
|
|
68
|
+
const ext = (0, fs_helpers_1.getUserFileExtension)();
|
|
69
|
+
const isTypeScript = ext === "ts";
|
|
70
|
+
const restrictedFields = ["id", "createdAt", "updatedAt", "deletedAt"];
|
|
71
|
+
const isUserModule = modelName.kebab === "user";
|
|
72
|
+
const enumsUsed = new Set();
|
|
73
|
+
let schemaFields = [];
|
|
74
|
+
for (const field of model.fields) {
|
|
75
|
+
const isForeignKey = model.fields.some((f) => f.foreignKeyField === field.name);
|
|
76
|
+
if (field.isId || restrictedFields.includes(field.name) || isForeignKey) {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (field.isRelation) {
|
|
80
|
+
if (field.isArray)
|
|
81
|
+
continue;
|
|
82
|
+
const referencedModel = prisma_schema_parser_1.default.models.find((m) => m.name === field.type);
|
|
83
|
+
if (referencedModel) {
|
|
84
|
+
const refField = field.foreignReferenceField || "id";
|
|
85
|
+
const refFieldType = referencedModel.fields.find((f) => f.name === refField);
|
|
86
|
+
const zodType = this.mapPrismaTypeToZod(refFieldType?.type);
|
|
87
|
+
schemaFields.push(` ${field.name}: z.object({ ${refField}: ${zodType} }).optional()`);
|
|
88
|
+
}
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (prisma_schema_parser_1.default.isEnum(field.type)) {
|
|
92
|
+
enumsUsed.add(field.type);
|
|
93
|
+
}
|
|
94
|
+
const zodSchema = this.generateZodField(field, isUserModule, true);
|
|
95
|
+
schemaFields.push(` ${field.name}: ${zodSchema}`);
|
|
96
|
+
}
|
|
97
|
+
const enumImports = enumsUsed.size > 0
|
|
98
|
+
? `import { ${Array.from(enumsUsed).join(", ")} } from "@prisma/client";\n`
|
|
99
|
+
: "";
|
|
100
|
+
const typeExport = isTypeScript
|
|
101
|
+
? `\n\nexport type Update${modelName.pascal}SchemaType = z.infer<typeof Update${modelName.pascal}Schema>;`
|
|
102
|
+
: "";
|
|
103
|
+
return `import { z } from "zod";
|
|
104
|
+
${enumImports}
|
|
105
|
+
const Update${modelName.pascal}Schema = z.object({
|
|
106
|
+
${schemaFields.join(",\n")}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
export default Update${modelName.pascal}Schema;${typeExport}
|
|
110
|
+
`;
|
|
111
|
+
}
|
|
112
|
+
generateBaseSchema(options) {
|
|
113
|
+
const { modelName } = options;
|
|
114
|
+
const model = this.ensureCorrectOptions(options);
|
|
115
|
+
const ext = (0, fs_helpers_1.getUserFileExtension)();
|
|
116
|
+
const isTypeScript = ext === "ts";
|
|
117
|
+
const isUserModule = modelName.kebab === "user";
|
|
118
|
+
const enumsUsed = new Set();
|
|
119
|
+
let schemaFields = [];
|
|
120
|
+
for (const field of model.fields) {
|
|
121
|
+
if (isUserModule && field.name === "password") {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (field.isRelation) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (prisma_schema_parser_1.default.isEnum(field.type)) {
|
|
128
|
+
enumsUsed.add(field.type);
|
|
129
|
+
}
|
|
130
|
+
const zodSchema = this.generateZodField(field, isUserModule, false);
|
|
131
|
+
schemaFields.push(` ${field.name}: ${zodSchema}`);
|
|
132
|
+
}
|
|
133
|
+
const enumImports = enumsUsed.size > 0
|
|
134
|
+
? `import { ${Array.from(enumsUsed).join(", ")} } from "@prisma/client";\n`
|
|
135
|
+
: "";
|
|
136
|
+
const typeExport = isTypeScript
|
|
137
|
+
? `\n\nexport type ${modelName.pascal}SchemaType = z.infer<typeof ${modelName.pascal}Schema>;`
|
|
138
|
+
: "";
|
|
139
|
+
return `import { z } from "zod";
|
|
140
|
+
${enumImports}
|
|
141
|
+
const ${modelName.pascal}Schema = z.object({
|
|
142
|
+
${schemaFields.join(",\n")}
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
export default ${modelName.pascal}Schema;${typeExport}
|
|
146
|
+
`;
|
|
147
|
+
}
|
|
148
|
+
generateQuerySchema(options) {
|
|
149
|
+
const { modelName } = options;
|
|
150
|
+
const model = this.ensureCorrectOptions(options);
|
|
151
|
+
const ext = (0, fs_helpers_1.getUserFileExtension)();
|
|
152
|
+
const isTypeScript = ext === "ts";
|
|
153
|
+
const isUserModule = modelName.kebab === "user";
|
|
154
|
+
const enumsUsed = new Set();
|
|
155
|
+
const filterSchemasNeeded = new Set();
|
|
156
|
+
let schemaFields = [];
|
|
157
|
+
for (const field of model.fields) {
|
|
158
|
+
if (isUserModule && field.name === "password") {
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (field.isRelation) {
|
|
162
|
+
if (field.isArray)
|
|
163
|
+
continue;
|
|
164
|
+
const referencedModel = prisma_schema_parser_1.default.models.find((m) => m.name === field.type);
|
|
165
|
+
if (referencedModel) {
|
|
166
|
+
const relationFilterFields = [];
|
|
167
|
+
const isUserModel = referencedModel.name.toLowerCase() === "user";
|
|
168
|
+
for (const refField of referencedModel.fields) {
|
|
169
|
+
if (isUserModel && refField.name === "password") {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (refField.isRelation)
|
|
173
|
+
continue;
|
|
174
|
+
const filterSchemaName = this.getFilterSchemaForField(refField, enumsUsed);
|
|
175
|
+
if (filterSchemaName) {
|
|
176
|
+
filterSchemasNeeded.add(filterSchemaName);
|
|
177
|
+
relationFilterFields.push(` ${refField.name}: ${filterSchemaName}.optional()`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (relationFilterFields.length > 0) {
|
|
181
|
+
schemaFields.push(` ${field.name}: z.object({\n${relationFilterFields.join(",\n")}\n }).optional()`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const filterSchemaName = this.getFilterSchemaForField(field, enumsUsed);
|
|
187
|
+
if (filterSchemaName) {
|
|
188
|
+
filterSchemasNeeded.add(filterSchemaName);
|
|
189
|
+
schemaFields.push(` ${field.name}: ${filterSchemaName}.optional()`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const enumImports = enumsUsed.size > 0
|
|
193
|
+
? `import { ${Array.from(enumsUsed).join(", ")} } from "@prisma/client";\n`
|
|
194
|
+
: "";
|
|
195
|
+
const filterSchemas = this.generateFilterSchemas(filterSchemasNeeded, enumsUsed);
|
|
196
|
+
const filterSchemasSection = filterSchemas ? `\n${filterSchemas}\n` : "";
|
|
197
|
+
const typeExport = isTypeScript
|
|
198
|
+
? `\n\nexport type ${modelName.pascal}QuerySchemaType = z.infer<typeof ${modelName.pascal}QuerySchema>;`
|
|
199
|
+
: "";
|
|
200
|
+
return `import { z } from "zod";
|
|
201
|
+
${enumImports}${filterSchemasSection}
|
|
202
|
+
const ${modelName.pascal}QuerySchema = z.object({
|
|
203
|
+
${schemaFields.join(",\n")}
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
export default ${modelName.pascal}QuerySchema;${typeExport}
|
|
207
|
+
`;
|
|
208
|
+
}
|
|
209
|
+
getFilterSchemaForField(field, enumsUsed) {
|
|
210
|
+
if (prisma_schema_parser_1.default.isEnum(field.type)) {
|
|
211
|
+
enumsUsed.add(field.type);
|
|
212
|
+
return `${field.type}FilterSchema`;
|
|
213
|
+
}
|
|
214
|
+
switch (field.type) {
|
|
215
|
+
case "String":
|
|
216
|
+
return "StringFilterSchema";
|
|
217
|
+
case "Int":
|
|
218
|
+
case "Float":
|
|
219
|
+
case "Decimal":
|
|
220
|
+
case "BigInt":
|
|
221
|
+
return "NumberFilterSchema";
|
|
222
|
+
case "Boolean":
|
|
223
|
+
return "BooleanFilterSchema";
|
|
224
|
+
case "DateTime":
|
|
225
|
+
return "DateTimeFilterSchema";
|
|
226
|
+
default:
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
generateFilterSchemas(filterSchemasNeeded, enumsUsed) {
|
|
231
|
+
const schemas = [];
|
|
232
|
+
if (filterSchemasNeeded.has("StringFilterSchema")) {
|
|
233
|
+
schemas.push(`const StringFilterSchema = z.object({
|
|
234
|
+
contains: z.string().optional(),
|
|
235
|
+
icontains: z.string().optional(),
|
|
236
|
+
equals: z.string().optional(),
|
|
237
|
+
in: z.array(z.string()).optional(),
|
|
238
|
+
notIn: z.array(z.string()).optional(),
|
|
239
|
+
});`);
|
|
240
|
+
}
|
|
241
|
+
if (filterSchemasNeeded.has("NumberFilterSchema")) {
|
|
242
|
+
schemas.push(`const NumberFilterSchema = z.object({
|
|
243
|
+
equals: z.number().optional(),
|
|
244
|
+
gte: z.number().optional(),
|
|
245
|
+
lte: z.number().optional(),
|
|
246
|
+
gt: z.number().optional(),
|
|
247
|
+
lt: z.number().optional(),
|
|
248
|
+
in: z.array(z.number()).optional(),
|
|
249
|
+
notIn: z.array(z.number()).optional(),
|
|
250
|
+
});`);
|
|
251
|
+
}
|
|
252
|
+
if (filterSchemasNeeded.has("BooleanFilterSchema")) {
|
|
253
|
+
schemas.push(`const BooleanFilterSchema = z.object({
|
|
254
|
+
equals: z.boolean().optional(),
|
|
255
|
+
});`);
|
|
256
|
+
}
|
|
257
|
+
if (filterSchemasNeeded.has("DateTimeFilterSchema")) {
|
|
258
|
+
schemas.push(`const DateTimeFilterSchema = z.object({
|
|
259
|
+
equals: z.string().optional(),
|
|
260
|
+
gte: z.string().optional(),
|
|
261
|
+
lte: z.string().optional(),
|
|
262
|
+
gt: z.string().optional(),
|
|
263
|
+
lt: z.string().optional(),
|
|
264
|
+
});`);
|
|
265
|
+
}
|
|
266
|
+
for (const enumName of enumsUsed) {
|
|
267
|
+
if (filterSchemasNeeded.has(`${enumName}FilterSchema`)) {
|
|
268
|
+
schemas.push(`const ${enumName}FilterSchema = z.object({
|
|
269
|
+
equals: z.nativeEnum(${enumName}).optional(),
|
|
270
|
+
in: z.array(z.nativeEnum(${enumName})).optional(),
|
|
271
|
+
notIn: z.array(z.nativeEnum(${enumName})).optional(),
|
|
272
|
+
});`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return schemas.join("\n\n");
|
|
276
|
+
}
|
|
277
|
+
generateZodField(field, isUserModule, forceOptional) {
|
|
278
|
+
let zodType = this.mapPrismaTypeToZod(field.type);
|
|
279
|
+
if (field.isArray) {
|
|
280
|
+
zodType = `z.array(${zodType})`;
|
|
281
|
+
}
|
|
282
|
+
if (prisma_schema_parser_1.default.isEnum(field.type)) {
|
|
283
|
+
zodType = field.isArray
|
|
284
|
+
? `z.array(z.nativeEnum(${field.type}))`
|
|
285
|
+
: `z.nativeEnum(${field.type})`;
|
|
286
|
+
}
|
|
287
|
+
if (isUserModule) {
|
|
288
|
+
if (field.name === "email") {
|
|
289
|
+
zodType = `z.string().email()`;
|
|
290
|
+
}
|
|
291
|
+
else if (field.name === "password") {
|
|
292
|
+
zodType = `z.string().min(8).regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)/, "Password must contain at least one uppercase letter, one lowercase letter, and one number")`;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const isOptional = forceOptional || field.isOptional || field.defaultValue !== undefined;
|
|
296
|
+
if (isOptional) {
|
|
297
|
+
zodType += ".optional()";
|
|
298
|
+
}
|
|
299
|
+
return zodType;
|
|
300
|
+
}
|
|
301
|
+
mapPrismaTypeToZod(prismaType) {
|
|
302
|
+
switch (prismaType) {
|
|
303
|
+
case "String":
|
|
304
|
+
return "z.string()";
|
|
305
|
+
case "Int":
|
|
306
|
+
case "Float":
|
|
307
|
+
case "Decimal":
|
|
308
|
+
return "z.number()";
|
|
309
|
+
case "Boolean":
|
|
310
|
+
return "z.boolean()";
|
|
311
|
+
case "DateTime":
|
|
312
|
+
return "z.date().or(z.string()).refine((val) => val instanceof Date || !isNaN(Date.parse(val)), 'Invalid date')";
|
|
313
|
+
case "Json":
|
|
314
|
+
return "z.any()";
|
|
315
|
+
case "Bytes":
|
|
316
|
+
return "z.instanceof(Buffer)";
|
|
317
|
+
case "BigInt":
|
|
318
|
+
return "z.bigint()";
|
|
319
|
+
default:
|
|
320
|
+
return "z.any()";
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
exports.ZodSchemaGenerator = ZodSchemaGenerator;
|
|
325
|
+
const zodSchemaGenerator = new ZodSchemaGenerator();
|
|
326
|
+
exports.default = zodSchemaGenerator;
|
|
327
|
+
//# sourceMappingURL=zod-schema-generator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"zod-schema-generator.js","sourceRoot":"","sources":["../../../../../../../src/utils/cli/utils/template-generator/templates/zod-schema-generator.ts"],"names":[],"mappings":";;;;;;AAAA,mGAAyE;AAEzE,+DAAsE;AAGtE,MAAa,kBAAkB;IACrB,oBAAoB,CAAC,OAAwB;QACnD,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;QAC9B,IAAI,CAAC,SAAS;YACZ,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;QACjE,MAAM,KAAK,GAAG,8BAAkB,CAAC,MAAM,CAAC,IAAI,CAC1C,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,EAAE,CAC/D,CAAC;QACF,IAAI,CAAC,KAAK;YACR,MAAM,IAAI,KAAK,CAAC,SAAS,SAAS,CAAC,MAAM,6BAA6B,CAAC,CAAC;QAC1E,OAAO,KAAK,CAAC;IACf,CAAC;IAED,oBAAoB,CAAC,OAAwB;QAC3C,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;QAC9B,MAAM,KAAK,GAAG,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAEjD,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;QACnC,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,CAAC;QAClC,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC;QACvE,MAAM,YAAY,GAAG,SAAU,CAAC,KAAK,KAAK,MAAM,CAAC;QACjD,MAAM,SAAS,GAAG,IAAI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;gBACT,OAAO,SAAS,CAAC;YACnB,KAAK,OAAO;gBACV,OAAO,sBAAsB,CAAC;YAChC,KAAK,QAAQ;gBACX,OAAO,YAAY,CAAC;YACtB;gBACE,OAAO,SAAS,CAAC;QACrB,CAAC;IACH,CAAC;CACF;AAjbD,gDAibC;AAED,MAAM,kBAAkB,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAEpD,kBAAe,kBAAkB,CAAC","sourcesContent":["import prismaSchemaParser from \"../../../../prisma/prisma-schema-parser\";\nimport { PrismaField } from \"../../../../prisma/types\";\nimport { getUserFileExtension } from \"../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../template-generators\";\n\nexport class ZodSchemaGenerator {\n private ensureCorrectOptions(options: TemplateOptions) {\n const { modelName } = options;\n if (!modelName)\n throw new Error(\"Module name is required for schema template\");\n const model = prismaSchemaParser.models.find(\n (m) => m.name.toLowerCase() === modelName.pascal.toLowerCase()\n );\n if (!model)\n throw new Error(`Model ${modelName.pascal} not found in Prisma schema`);\n return model;\n }\n\n generateCreateSchema(options: TemplateOptions): string {\n const { modelName } = options;\n const model = this.ensureCorrectOptions(options);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const restrictedFields = [\"id\", \"createdAt\", \"updatedAt\", \"deletedAt\"];\n const isUserModule = modelName!.kebab === \"user\";\n const enumsUsed = new Set<string>();\n\n let schemaFields: string[] = [];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (f) => f.foreignKeyField === field.name\n );\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey)\n continue;\n\n if (field.isRelation) {\n if (field.isArray) continue;\n\n const referencedModel = prismaSchemaParser.models.find(\n (m) => m.name === field.type\n );\n\n if (referencedModel) {\n const refField = field.foreignReferenceField || \"id\";\n const refFieldType = referencedModel.fields.find(\n (f) => f.name === refField\n );\n const zodType = this.mapPrismaTypeToZod(refFieldType?.type!);\n const isOptional =\n field.isOptional || field.defaultValue !== undefined;\n schemaFields.push(\n ` ${field.name}: z.object({ ${refField}: ${zodType} })${isOptional ? \".optional()\" : \"\"}`\n );\n }\n continue;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) enumsUsed.add(field.type);\n\n const zodSchema = this.generateZodField(field, isUserModule, false);\n schemaFields.push(` ${field.name}: ${zodSchema}`);\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n const typeExport = isTypeScript\n ? `\\n\\nexport type Create${modelName!.pascal}SchemaType = z.infer<typeof Create${modelName!.pascal}Schema>;`\n : \"\";\n\n return `import { z } from \"zod\";\n${enumImports}\nconst Create${modelName!.pascal}Schema = z.object({\n${schemaFields.join(\",\\n\")}\n});\n\nexport default Create${modelName!.pascal}Schema;${typeExport}\n`;\n }\n\n generateUpdateSchema(options: TemplateOptions): string {\n const { modelName } = options;\n const model = this.ensureCorrectOptions(options);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const restrictedFields = [\"id\", \"createdAt\", \"updatedAt\", \"deletedAt\"];\n const isUserModule = modelName!.kebab === \"user\";\n const enumsUsed = new Set<string>();\n\n let schemaFields: string[] = [];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (f) => f.foreignKeyField === field.name\n );\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey) {\n continue;\n }\n\n if (field.isRelation) {\n if (field.isArray) continue;\n\n const referencedModel = prismaSchemaParser.models.find(\n (m) => m.name === field.type\n );\n\n if (referencedModel) {\n const refField = field.foreignReferenceField || \"id\";\n const refFieldType = referencedModel.fields.find(\n (f) => f.name === refField\n );\n const zodType = this.mapPrismaTypeToZod(refFieldType?.type!);\n // ALL relations are optional in update\n schemaFields.push(\n ` ${field.name}: z.object({ ${refField}: ${zodType} }).optional()`\n );\n }\n continue;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n enumsUsed.add(field.type);\n }\n\n // ALL fields are optional in update\n const zodSchema = this.generateZodField(field, isUserModule, true);\n schemaFields.push(` ${field.name}: ${zodSchema}`);\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n const typeExport = isTypeScript\n ? `\\n\\nexport type Update${modelName!.pascal}SchemaType = z.infer<typeof Update${modelName!.pascal}Schema>;`\n : \"\";\n\n return `import { z } from \"zod\";\n${enumImports}\nconst Update${modelName!.pascal}Schema = z.object({\n${schemaFields.join(\",\\n\")}\n});\n\nexport default Update${modelName!.pascal}Schema;${typeExport}\n`;\n }\n\n generateBaseSchema(options: TemplateOptions): string {\n const { modelName } = options;\n const model = this.ensureCorrectOptions(options);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const isUserModule = modelName!.kebab === \"user\";\n const enumsUsed = new Set<string>();\n\n let schemaFields: string[] = [];\n\n for (const field of model.fields) {\n // Skip password field for user module (sensitive data)\n if (isUserModule && field.name === \"password\") {\n continue;\n }\n\n // Skip all relations - user can add them manually if needed\n if (field.isRelation) {\n continue;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n enumsUsed.add(field.type);\n }\n\n const zodSchema = this.generateZodField(field, isUserModule, false);\n schemaFields.push(` ${field.name}: ${zodSchema}`);\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n const typeExport = isTypeScript\n ? `\\n\\nexport type ${modelName!.pascal}SchemaType = z.infer<typeof ${modelName!.pascal}Schema>;`\n : \"\";\n\n return `import { z } from \"zod\";\n${enumImports}\nconst ${modelName!.pascal}Schema = z.object({\n${schemaFields.join(\",\\n\")}\n});\n\nexport default ${modelName!.pascal}Schema;${typeExport}\n`;\n }\n\n generateQuerySchema(options: TemplateOptions): string {\n const { modelName } = options;\n const model = this.ensureCorrectOptions(options);\n\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n const isUserModule = modelName!.kebab === \"user\";\n const enumsUsed = new Set<string>();\n const filterSchemasNeeded = new Set<string>();\n\n let schemaFields: string[] = [];\n\n for (const field of model.fields) {\n // Skip password field in query schema for user module\n if (isUserModule && field.name === \"password\") {\n continue;\n }\n\n if (field.isRelation) {\n if (field.isArray) continue; // Skip array relations\n\n // Single relation - create inline relation filter\n const referencedModel = prismaSchemaParser.models.find(\n (m) => m.name === field.type\n );\n\n if (referencedModel) {\n const relationFilterFields: string[] = [];\n const isUserModel = referencedModel.name.toLowerCase() === \"user\";\n\n for (const refField of referencedModel.fields) {\n // Skip password for user model in relation filters\n if (isUserModel && refField.name === \"password\") {\n continue;\n }\n\n // Skip relations in relation filters (single level only)\n if (refField.isRelation) continue;\n\n const filterSchemaName = this.getFilterSchemaForField(\n refField,\n enumsUsed\n );\n if (filterSchemaName) {\n filterSchemasNeeded.add(filterSchemaName);\n relationFilterFields.push(\n ` ${refField.name}: ${filterSchemaName}.optional()`\n );\n }\n }\n\n if (relationFilterFields.length > 0) {\n schemaFields.push(\n ` ${field.name}: z.object({\\n${relationFilterFields.join(\",\\n\")}\\n }).optional()`\n );\n }\n }\n continue;\n }\n\n // Regular fields get filter schemas\n const filterSchemaName = this.getFilterSchemaForField(field, enumsUsed);\n if (filterSchemaName) {\n filterSchemasNeeded.add(filterSchemaName);\n schemaFields.push(` ${field.name}: ${filterSchemaName}.optional()`);\n }\n }\n\n const enumImports =\n enumsUsed.size > 0\n ? `import { ${Array.from(enumsUsed).join(\", \")} } from \"@prisma/client\";\\n`\n : \"\";\n\n // Generate filter schemas\n const filterSchemas = this.generateFilterSchemas(\n filterSchemasNeeded,\n enumsUsed\n );\n\n const filterSchemasSection = filterSchemas ? `\\n${filterSchemas}\\n` : \"\";\n\n const typeExport = isTypeScript\n ? `\\n\\nexport type ${modelName!.pascal}QuerySchemaType = z.infer<typeof ${modelName!.pascal}QuerySchema>;`\n : \"\";\n\n return `import { z } from \"zod\";\n${enumImports}${filterSchemasSection}\nconst ${modelName!.pascal}QuerySchema = z.object({\n${schemaFields.join(\",\\n\")}\n});\n\nexport default ${modelName!.pascal}QuerySchema;${typeExport}\n`;\n }\n\n private getFilterSchemaForField(\n field: PrismaField,\n enumsUsed: Set<string>\n ): string | null {\n if (prismaSchemaParser.isEnum(field.type)) {\n enumsUsed.add(field.type);\n return `${field.type}FilterSchema`;\n }\n\n switch (field.type) {\n case \"String\":\n return \"StringFilterSchema\";\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n case \"BigInt\":\n return \"NumberFilterSchema\";\n case \"Boolean\":\n return \"BooleanFilterSchema\";\n case \"DateTime\":\n return \"DateTimeFilterSchema\";\n default:\n return null;\n }\n }\n\n private generateFilterSchemas(\n filterSchemasNeeded: Set<string>,\n enumsUsed: Set<string>\n ): string {\n const schemas: string[] = [];\n\n if (filterSchemasNeeded.has(\"StringFilterSchema\")) {\n schemas.push(`const StringFilterSchema = z.object({\n contains: z.string().optional(),\n icontains: z.string().optional(),\n equals: z.string().optional(),\n in: z.array(z.string()).optional(),\n notIn: z.array(z.string()).optional(),\n});`);\n }\n\n if (filterSchemasNeeded.has(\"NumberFilterSchema\")) {\n schemas.push(`const NumberFilterSchema = z.object({\n equals: z.number().optional(),\n gte: z.number().optional(),\n lte: z.number().optional(),\n gt: z.number().optional(),\n lt: z.number().optional(),\n in: z.array(z.number()).optional(),\n notIn: z.array(z.number()).optional(),\n});`);\n }\n\n if (filterSchemasNeeded.has(\"BooleanFilterSchema\")) {\n schemas.push(`const BooleanFilterSchema = z.object({\n equals: z.boolean().optional(),\n});`);\n }\n\n if (filterSchemasNeeded.has(\"DateTimeFilterSchema\")) {\n schemas.push(`const DateTimeFilterSchema = z.object({\n equals: z.string().optional(),\n gte: z.string().optional(),\n lte: z.string().optional(),\n gt: z.string().optional(),\n lt: z.string().optional(),\n});`);\n }\n\n // Generate enum filter schemas\n for (const enumName of enumsUsed) {\n if (filterSchemasNeeded.has(`${enumName}FilterSchema`)) {\n schemas.push(`const ${enumName}FilterSchema = z.object({\n equals: z.nativeEnum(${enumName}).optional(),\n in: z.array(z.nativeEnum(${enumName})).optional(),\n notIn: z.array(z.nativeEnum(${enumName})).optional(),\n});`);\n }\n }\n\n return schemas.join(\"\\n\\n\");\n }\n\n private generateZodField(\n field: PrismaField,\n isUserModule: boolean,\n forceOptional: boolean\n ): string {\n let zodType = this.mapPrismaTypeToZod(field.type);\n\n if (field.isArray) {\n zodType = `z.array(${zodType})`;\n }\n\n if (prismaSchemaParser.isEnum(field.type)) {\n zodType = field.isArray\n ? `z.array(z.nativeEnum(${field.type}))`\n : `z.nativeEnum(${field.type})`;\n }\n\n // User module special cases\n if (isUserModule) {\n if (field.name === \"email\") {\n zodType = `z.string().email()`;\n } else if (field.name === \"password\") {\n zodType = `z.string().min(8).regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)/, \"Password must contain at least one uppercase letter, one lowercase letter, and one number\")`;\n }\n }\n\n const isOptional =\n forceOptional || field.isOptional || field.defaultValue !== undefined;\n if (isOptional) {\n zodType += \".optional()\";\n }\n\n return zodType;\n }\n\n private mapPrismaTypeToZod(prismaType: string): string {\n switch (prismaType) {\n case \"String\":\n return \"z.string()\";\n case \"Int\":\n case \"Float\":\n case \"Decimal\":\n return \"z.number()\";\n case \"Boolean\":\n return \"z.boolean()\";\n case \"DateTime\":\n return \"z.date().or(z.string()).refine((val) => val instanceof Date || !isNaN(Date.parse(val)), 'Invalid date')\";\n case \"Json\":\n return \"z.any()\";\n case \"Bytes\":\n return \"z.instanceof(Buffer)\";\n case \"BigInt\":\n return \"z.bigint()\";\n default:\n return \"z.any()\";\n }\n }\n}\n\nconst zodSchemaGenerator = new ZodSchemaGenerator();\n\nexport default zodSchemaGenerator;\n"]}
|
|
@@ -11,10 +11,8 @@ const query_options_template_1 = require("./template-generator/templates/query-o
|
|
|
11
11
|
const router_template_1 = require("./template-generator/templates/router-template");
|
|
12
12
|
const service_template_1 = require("./template-generator/templates/service-template");
|
|
13
13
|
const hooks_template_1 = __importDefault(require("./template-generator/templates/hooks-template"));
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const update_dto_template_1 = require("./template-generator/templates/class-validator/update-dto-template");
|
|
17
|
-
const create_dto_template_1 = require("./template-generator/templates/class-validator/create-dto-template");
|
|
14
|
+
const class_validator_dto_generator_1 = __importDefault(require("./template-generator/templates/class-validator-dto-generator"));
|
|
15
|
+
const zod_schema_generator_1 = __importDefault(require("./template-generator/templates/zod-schema-generator"));
|
|
18
16
|
function generateTemplate(type, options) {
|
|
19
17
|
switch (type) {
|
|
20
18
|
case "controller":
|
|
@@ -32,13 +30,21 @@ function generateTemplate(type, options) {
|
|
|
32
30
|
case "hooks":
|
|
33
31
|
return (0, hooks_template_1.default)(options);
|
|
34
32
|
case "create-schema":
|
|
35
|
-
return
|
|
33
|
+
return zod_schema_generator_1.default.generateCreateSchema(options);
|
|
36
34
|
case "update-schema":
|
|
37
|
-
return
|
|
35
|
+
return zod_schema_generator_1.default.generateUpdateSchema(options);
|
|
36
|
+
case "schema":
|
|
37
|
+
return zod_schema_generator_1.default.generateBaseSchema(options);
|
|
38
|
+
case "query-schema":
|
|
39
|
+
return zod_schema_generator_1.default.generateQuerySchema(options);
|
|
38
40
|
case "create-dto":
|
|
39
|
-
return
|
|
41
|
+
return class_validator_dto_generator_1.default.generateCreateDto(options);
|
|
40
42
|
case "update-dto":
|
|
41
|
-
return
|
|
43
|
+
return class_validator_dto_generator_1.default.generateUpdateDto(options);
|
|
44
|
+
case "dto":
|
|
45
|
+
return class_validator_dto_generator_1.default.generateBaseDto(options);
|
|
46
|
+
case "query-dto":
|
|
47
|
+
return class_validator_dto_generator_1.default.generateQueryDto(options);
|
|
42
48
|
default:
|
|
43
49
|
throw new Error(`Unknown template type: ${type}`);
|
|
44
50
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template-generators.js","sourceRoot":"","sources":["../../../../../src/utils/cli/utils/template-generators.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"template-generators.js","sourceRoot":"","sources":["../../../../../src/utils/cli/utils/template-generators.ts"],"names":[],"mappings":";;;;;AA4BA,4CAyCC;AArED,8GAAyG;AACzG,gGAAmG;AACnG,8FAAkG;AAClG,kGAAqG;AACrG,oFAAwF;AACxF,sFAA0F;AAC1F,mGAAkF;AAClF,iIAAsG;AACtG,+GAAqF;AAoBrF,SAAgB,gBAAgB,CAC9B,IAAY,EACZ,OAAwB;IAExB,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,YAAY;YACf,OAAO,IAAA,yDAA0B,EAAC,OAAO,CAAC,CAAC;QAC7C,KAAK,SAAS;YACZ,OAAO,IAAA,0CAAuB,EAAC,OAAO,CAAC,CAAC;QAC1C,KAAK,QAAQ;YACX,OAAO,IAAA,wCAAsB,EAAC,OAAO,CAAC,CAAC;QACzC,KAAK,cAAc;YACjB,OAAO,IAAA,mDAA2B,EAAC,OAAO,CAAC,CAAC;QAC9C,KAAK,eAAe;YAClB,OAAO,IAAA,qDAA4B,EAAC,OAAO,CAAC,CAAC;QAC/C,KAAK,cAAc;YACjB,OAAO,IAAA,kDAA2B,EAAC,OAAO,CAAC,CAAC;QAC9C,KAAK,OAAO;YACV,OAAO,IAAA,wBAAqB,EAAC,OAAO,CAAC,CAAC;QAExC,KAAK,eAAe;YAClB,OAAO,8BAAkB,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAC1D,KAAK,eAAe;YAClB,OAAO,8BAAkB,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAC1D,KAAK,QAAQ;YACX,OAAO,8BAAkB,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;QACxD,KAAK,cAAc;YACjB,OAAO,8BAAkB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAEzD,KAAK,YAAY;YACf,OAAO,uCAA0B,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAC/D,KAAK,YAAY;YACf,OAAO,uCAA0B,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAC/D,KAAK,KAAK;YACR,OAAO,uCAA0B,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;QAC7D,KAAK,WAAW;YACd,OAAO,uCAA0B,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QAE9D;YACE,MAAM,IAAI,KAAK,CAAC,0BAA0B,IAAI,EAAE,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { generateControllerTemplate } from \"./template-generator/templates/generate-controller-template\";\nimport { generateAuthConfigsTemplate } from \"./template-generator/templates/auth-configs-template\";\nimport { generateMiddlewaresTemplate } from \"./template-generator/templates/middlewares-template\";\nimport { generateQueryOptionsTemplate } from \"./template-generator/templates/query-options-template\";\nimport { generateRouterTemplate } from \"./template-generator/templates/router-template\";\nimport { generateServiceTemplate } from \"./template-generator/templates/service-template\";\nimport generateHooksTemplate from \"./template-generator/templates/hooks-template\";\nimport classValidatorDtoGenerator from \"./template-generator/templates/class-validator-dto-generator\";\nimport zodSchemaGenerator from \"./template-generator/templates/zod-schema-generator\";\n\ninterface ModelName {\n pascal: string;\n camel: string;\n kebab: string;\n}\n\ninterface MiddlewareName {\n pascal: string;\n camel: string;\n kebab: string;\n}\n\nexport interface TemplateOptions {\n modelName: ModelName;\n middlewareName?: MiddlewareName;\n imports?: Record<string, string>;\n}\n\nexport function generateTemplate(\n type: string,\n options: TemplateOptions\n): string {\n switch (type) {\n case \"controller\":\n return generateControllerTemplate(options);\n case \"service\":\n return generateServiceTemplate(options);\n case \"router\":\n return generateRouterTemplate(options);\n case \"auth-configs\":\n return generateAuthConfigsTemplate(options);\n case \"query-options\":\n return generateQueryOptionsTemplate(options);\n case \"interceptors\":\n return generateMiddlewaresTemplate(options);\n case \"hooks\":\n return generateHooksTemplate(options);\n\n case \"create-schema\":\n return zodSchemaGenerator.generateCreateSchema(options);\n case \"update-schema\":\n return zodSchemaGenerator.generateUpdateSchema(options);\n case \"schema\":\n return zodSchemaGenerator.generateBaseSchema(options);\n case \"query-schema\":\n return zodSchemaGenerator.generateQuerySchema(options);\n\n case \"create-dto\":\n return classValidatorDtoGenerator.generateCreateDto(options);\n case \"update-dto\":\n return classValidatorDtoGenerator.generateUpdateDto(options);\n case \"dto\":\n return classValidatorDtoGenerator.generateBaseDto(options);\n case \"query-dto\":\n return classValidatorDtoGenerator.generateQueryDto(options);\n\n default:\n throw new Error(`Unknown template type: ${type}`);\n }\n}\n"]}
|
|
@@ -59,7 +59,7 @@ function getFileModuleComponentsFileStructure(modelName) {
|
|
|
59
59
|
update: `update-${kebabModelName}.dto.${ext}`,
|
|
60
60
|
updateOne: `update-${kebabModelName}.dto.${ext}`,
|
|
61
61
|
updateMany: ``,
|
|
62
|
-
query:
|
|
62
|
+
query: ``,
|
|
63
63
|
findOne: ``,
|
|
64
64
|
findMany: ``,
|
|
65
65
|
},
|
|
@@ -79,7 +79,7 @@ function getFileModuleComponentsFileStructure(modelName) {
|
|
|
79
79
|
update: `update-${kebabModelName}.schema.${ext}`,
|
|
80
80
|
updateOne: `update-${kebabModelName}.schema.${ext}`,
|
|
81
81
|
updateMany: ``,
|
|
82
|
-
query:
|
|
82
|
+
query: ``,
|
|
83
83
|
findOne: ``,
|
|
84
84
|
findMany: ``,
|
|
85
85
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic-loader.js","sourceRoot":"","sources":["../../../src/utils/dynamic-loader.ts"],"names":[],"mappings":";;;;;;AAwBA,kDAKC;AAED,kDAEC;AAaD,oFAyDC;AAED,0BAKC;AAED,kCAEC;AAED,sCAqDC;AAuGD,8DAWC;AAQD,oDAgDC;AASD,wDAoFC;AAaD,0DAwCC;AApeD,gDAAwB;AAExB,yDAAiE;AAEjE,kDAA0B;AAC1B,6EAI0C;AAC1C,uEAAsE;AACtE,qDAAiE;AACjE,6DAAwD;AACxD,yFAA+D;AAC/D,4FAAmE;AAMnE,IAAI,mBAAmB,GAAuC,EAAE,CAAC;AAGj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+B,CAAC,CAAC;IAC7E,0BAAe,CAAC,iCAAiC,CAC/C,iBAAiB,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE;QACtC,MAAM,SAAS,GAAG,cAAI,CAAC,OAAO,CAC5B,IAAA,gBAAG,GAAE,EACL,KAAK,EACL,SAAS,EACT,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC,CACzB,CAAC;QAEF,OAAO;YACL,UAAU,EAAE,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC;YACpC,SAAS;YACT,UAAU;SACX,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { z, ZodTypeAny } from \"zod\";\nimport path from \"path\";\nimport { AuthConfigs } from \"../types/auth\";\nimport { killServerChildProcess } from \"./cli/utils/cli.helpers\";\nimport { ArkosConfig, RouterConfig } from \"../exports\";\nimport sheu from \"./sheu\";\nimport {\n applyStrictRoutingRules,\n pathExists,\n validateRouterConfigConsistency,\n} from \"./helpers/dynamic-loader.helpers\";\nimport { kebabCase, pascalCase } from \"./helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./helpers/fs.helpers\";\nimport { importModule } from \"./helpers/global.helpers\";\nimport prismaSchemaParser from \"./prisma/prisma-schema-parser\";\nimport debuggerService from \"../modules/debugger/debugger.service\";\nimport { PrismaQueryOptions } from \"../types\";\nimport { ServiceHook } from \"../modules/base/utils/service-hooks-manager\";\n\ntype AppModuleComponent = Awaited<ReturnType<typeof importModuleComponents>>;\n\nlet prismaModelsModules: Record<string, AppModuleComponent> = {};\n\n/** This was a workaround when testing and also when cjs was generated while `prismaModelsModules` was exported there where some problems */\nexport function setModuleComponents(\n modelName: string,\n modules: AppModuleComponent\n) {\n prismaModelsModules[pascalCase(modelName)] = modules;\n}\n\nexport function getModuleComponents(modelName: string) {\n return prismaModelsModules[pascalCase(modelName)];\n}\n\n/**\n * To be reused on other part of code for correct typing\n *\n * @param key\n * @param fileName\n * @param result\n */\nexport type ValidationFileMappingKey = keyof ReturnType<\n typeof getFileModuleComponentsFileStructure\n>[\"dtos\"];\n\nexport function getFileModuleComponentsFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n hooks: `${kebabModelName}.hooks.${ext}`,\n interceptors: `${kebabModelName}.interceptors.${ext}`,\n interceptorsOld: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n getMe: `get-me.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createOne: `create-${kebabModelName}.dto.${ext}`, // just for sake of completion and reusability around other parts of code\n createMany: ``,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateOne: `update-${kebabModelName}.dto.${ext}`, // same as createOne\n updateMany: ``,\n query: `query-${kebabModelName}.dto.${ext}`,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n getMe: `get-me.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createOne: `create-${kebabModelName}.schema.${ext}`,\n createMany: ``, // just for sake of completion and reusability around other parts of code\n update: `update-${kebabModelName}.schema.${ext}`,\n updateOne: `update-${kebabModelName}.schema.${ext}`, // same as createOne\n updateMany: ``,\n query: `query-${kebabModelName}.schema.${ext}`,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n };\n}\n\nexport function isClass(value: any): boolean {\n return (\n typeof value === \"function\" &&\n /^class\\s/.test(Function.prototype.toString.call(value))\n );\n}\n\nexport function isZodSchema(value: any): value is ZodTypeAny {\n return value?._def?.typeName?.startsWith(\"Zod\");\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\"\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n const result: Record<string, any> = {};\n\n if (!(await pathExists(subdir))) return result;\n\n try {\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n if (!fileName || !(await pathExists(filePath))) return;\n\n try {\n const module = await importModule(filePath).catch(\n async (err: any) => {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}: `);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n }\n );\n\n const cleanFilePath = `src/modules/${kebabCase(modelName)}/${fileName}`;\n if (type === \"dtos\" && !isClass(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid class under ${cleanFilePath}, in order to use as Dto.`\n );\n else if (type === \"schemas\" && !isZodSchema(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid zod schema under ${cleanFilePath}, in order to use as Schema`\n );\n\n if (module && module?.default) result[key] = module.default;\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n })\n );\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n\n return result;\n}\n\nexport type ModuleComponents = Omit<\n ImportModuleComponentsReturnType,\n \"authConfigsNew\" | \"prismaQueryOptionsNew\"\n>;\n\ntype ImportModuleComponentsReturnType = {\n hooks?: Record<string, ServiceHook | ServiceHook[]>;\n interceptors?: Record<string, Function | Function[]>;\n authConfigs?: AuthConfigs;\n interceptorsOld?: any;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: PrismaQueryOptions<any>;\n prismaQueryOptionsNew?: PrismaQueryOptions<any>;\n router?: { config?: RouterConfig<any>; default: RouterConfig };\n dtos?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n schemas?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n};\n\nconst availableInterceptors = {\n auth: [\n \"beforeGetMe\",\n \"afterGetMe\",\n \"onGetMeError\",\n \"beforeUpdateMe\",\n \"afterUpdateMe\",\n \"onUpdateMeError\",\n \"beforeLogin\",\n \"afterLogin\",\n \"onLoginError\",\n \"beforeLogout\",\n \"afterLogout\",\n \"onLogoutError\",\n \"beforeSignup\",\n \"afterSignup\",\n \"onSignupError\",\n \"beforeUpdatePassword\",\n \"afterUpdatePassword\",\n \"onUpdatePasswordError\",\n ],\n \"file-upload\": [\n \"beforeFindFile\",\n \"onFindFileError\",\n \"beforeUploadFile\",\n \"afterUploadFile\",\n \"onUploadFileError\",\n \"beforeUpdateFile\",\n \"afterUpdateFile\",\n \"onUpdateFileError\",\n \"beforeDeleteFile\",\n \"afterDeleteFile\",\n \"onDeleteFileError\",\n ],\n prisma: [\n \"beforeCreateOne\",\n \"afterCreateOne\",\n \"onCreateOneError\",\n \"beforeFindOne\",\n \"afterFindOne\",\n \"onFindOneError\",\n \"beforeFindMany\",\n \"afterFindMany\",\n \"onFindManyError\",\n \"beforeUpdateOne\",\n \"afterUpdateOne\",\n \"onUpdateOneError\",\n \"beforeDeleteOne\",\n \"afterDeleteOne\",\n \"onDeleteOneError\",\n \"beforeCreateMany\",\n \"afterCreateMany\",\n \"onCreateManyError\",\n \"beforeUpdateMany\",\n \"afterUpdateMany\",\n \"onUpdateManyError\",\n \"beforeDeleteMany\",\n \"afterDeleteMany\",\n \"onDeleteManyError\",\n ],\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {ImportModuleComponentsReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: ImportModuleComponentsReturnType\n): void {\n if (key === \"interceptorsOld\") {\n if (!result.interceptors)\n sheu.warn(\n `Found deprecated ${fileName} that will removed from v1.6.0-beta, consider switching to ${fileName.replace(\"middlewares\", \"interceptors\")}`\n );\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {ImportModuleComponentsReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n appModule: string,\n key: string,\n module: any,\n result: ImportModuleComponentsReturnType,\n arkosConfig: ArkosConfig\n): void {\n if (key === \"interceptors\") result.interceptors = module;\n else if (key === \"interceptorsOld\") {\n const kebabCaseAppModule = kebabCase(appModule);\n const moduleName =\n kebabCaseAppModule === \"auth\"\n ? \"auth\"\n : kebabCaseAppModule === \"file-upload\"\n ? \"file-upload\"\n : \"prisma\";\n\n if (\n result.interceptors &&\n Object.keys(module).some((interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n )\n ) {\n const exportedInterceptors = Object.keys(module).filter(\n (interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n );\n const ext = getUserFileExtension();\n sheu.warn(\n `Found ${kebabCaseAppModule}.middlewares.${ext} exporting ${exportedInterceptors.join(\", \")}. Which by convention should go at ${kebabCaseAppModule}.interceptors.${ext} This is simply a warning that will stop from v1.5.0-beta`\n );\n } else if (!result.interceptors) result.interceptors = module;\n } else if (key === \"router\") {\n result[key] = {\n ...module,\n config: applyStrictRoutingRules(\n appModule,\n arkosConfig,\n module?.config || {}\n ),\n };\n validateRouterConfigConsistency(\n kebabCase(appModule),\n result[key]?.config || {}\n );\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importModuleComponents(\n modelName: string,\n arkosConfig: ArkosConfig,\n moduleDirExists?: boolean\n): Promise<ImportModuleComponentsReturnType> {\n const result: ImportModuleComponentsReturnType = {\n dtos: {},\n schemas: {},\n };\n const usingStrictRouting = arkosConfig.routers?.strict;\n\n if (!moduleDirExists && !usingStrictRouting) return result;\n\n if (getModuleComponents(modelName)) return getModuleComponents(modelName);\n\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n\n const validationSubdir = arkosConfig.validation?.resolver\n ? arkosConfig.validation.resolver === \"zod\"\n ? \"schemas\"\n : \"dtos\"\n : null;\n\n const [validators] = await Promise.all([\n validationSubdir && processSubdir(modelName, validationSubdir),\n ...Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n if (\n [\"createMany\", \"findMany\", \"findOne\", \"updateMany\"].includes(key) ||\n !fileName\n )\n return;\n\n const filePath = path.join(moduleDir, fileName);\n\n if (\n key === \"router\" &&\n !usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n else if (\n key !== \"router\" &&\n usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n\n try {\n let module = await importModule(filePath).catch(async (err) => {\n try {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}`);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n } catch (err) {}\n });\n\n if (!module && key === \"router\" && usingStrictRouting) module = {};\n\n if (module) {\n (result as any)[key] = module;\n validateNamingConventions(key, fileName, result);\n assignModuleToResult(modelName, key, module, result, arkosConfig);\n }\n } catch (err: any) {\n if (err.message?.includes(\"Cannot use both\")) throw err;\n console.error(err);\n killServerChildProcess();\n }\n }),\n ]);\n\n prismaModelsModules[pascalCase(modelName)] = {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n\n return {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n}\n\nexport const appModules = Array.from(\n new Set([\n \"auth\",\n \"file-upload\",\n ...(prismaSchemaParser.getModelsAsArrayOfStrings() || []),\n ])\n);\n\n/**\n * Allows to asynchronously load all app modules components at once to speed up app start time.\n */\nexport async function loadAllModuleComponents(arkosConfig: ArkosConfig) {\n const moduleDirExists: string[] = [];\n await Promise.all(\n appModules.map(async (appModule) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModule)\n );\n if (await pathExists(moduleDir)) moduleDirExists.push(appModule);\n })\n );\n\n const modulesComponentsImportPromises = appModules.map(\n async (appModule) =>\n await importModuleComponents(\n appModule,\n arkosConfig,\n moduleDirExists.includes(appModule)\n )\n );\n\n const modulesComponents = await Promise.all(modulesComponentsImportPromises);\n debuggerService.logDynamicLoadedModulesComponents(\n modulesComponents.map((components, i) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModules[i])\n );\n\n return {\n moduleName: kebabCase(appModules[i]),\n moduleDir,\n components,\n };\n })\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"dynamic-loader.js","sourceRoot":"","sources":["../../../src/utils/dynamic-loader.ts"],"names":[],"mappings":";;;;;;AAwBA,kDAKC;AAED,kDAEC;AAaD,oFAyDC;AAED,0BAKC;AAED,kCAEC;AAED,sCAqDC;AAuGD,8DAWC;AAQD,oDAgDC;AASD,wDAoFC;AAaD,0DAwCC;AApeD,gDAAwB;AAExB,yDAAiE;AAEjE,kDAA0B;AAC1B,6EAI0C;AAC1C,uEAAsE;AACtE,qDAAiE;AACjE,6DAAwD;AACxD,yFAA+D;AAC/D,4FAAmE;AAMnE,IAAI,mBAAmB,GAAuC,EAAE,CAAC;AAGjE,SAAgB,mBAAmB,CACjC,SAAiB,EACjB,OAA2B;IAE3B,mBAAmB,CAAC,IAAA,gCAAU,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AAG,cAAI,CAAC,OAAO,CAC5B,IAAA,gBAAG,GAAE,EACL,KAAK,EACL,SAAS,EACT,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC,CACzB,CAAC;QAEF,OAAO;YACL,UAAU,EAAE,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC;YACpC,SAAS;YACT,UAAU;SACX,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { ZodTypeAny } from \"zod\";\nimport path from \"path\";\nimport { AuthConfigs } from \"../types/auth\";\nimport { killServerChildProcess } from \"./cli/utils/cli.helpers\";\nimport { ArkosConfig, RouterConfig } from \"../exports\";\nimport sheu from \"./sheu\";\nimport {\n applyStrictRoutingRules,\n pathExists,\n validateRouterConfigConsistency,\n} from \"./helpers/dynamic-loader.helpers\";\nimport { kebabCase, pascalCase } from \"./helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./helpers/fs.helpers\";\nimport { importModule } from \"./helpers/global.helpers\";\nimport prismaSchemaParser from \"./prisma/prisma-schema-parser\";\nimport debuggerService from \"../modules/debugger/debugger.service\";\nimport { PrismaQueryOptions } from \"../types\";\nimport { ServiceHook } from \"../modules/base/utils/service-hooks-manager\";\n\ntype AppModuleComponent = Awaited<ReturnType<typeof importModuleComponents>>;\n\nlet prismaModelsModules: Record<string, AppModuleComponent> = {};\n\n/** This was a workaround when testing and also when cjs was generated while `prismaModelsModules` was exported there where some problems */\nexport function setModuleComponents(\n modelName: string,\n modules: AppModuleComponent\n) {\n prismaModelsModules[pascalCase(modelName)] = modules;\n}\n\nexport function getModuleComponents(modelName: string) {\n return prismaModelsModules[pascalCase(modelName)];\n}\n\n/**\n * To be reused on other part of code for correct typing\n *\n * @param key\n * @param fileName\n * @param result\n */\nexport type ValidationFileMappingKey = keyof ReturnType<\n typeof getFileModuleComponentsFileStructure\n>[\"dtos\"];\n\nexport function getFileModuleComponentsFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n hooks: `${kebabModelName}.hooks.${ext}`,\n interceptors: `${kebabModelName}.interceptors.${ext}`,\n interceptorsOld: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n getMe: `get-me.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createOne: `create-${kebabModelName}.dto.${ext}`, // just for sake of completion and reusability around other parts of code\n createMany: ``,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateOne: `update-${kebabModelName}.dto.${ext}`, // same as createOne\n updateMany: ``,\n query: ``,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n getMe: `get-me.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createOne: `create-${kebabModelName}.schema.${ext}`,\n createMany: ``, // just for sake of completion and reusability around other parts of code\n update: `update-${kebabModelName}.schema.${ext}`,\n updateOne: `update-${kebabModelName}.schema.${ext}`, // same as createOne\n updateMany: ``,\n query: ``,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n };\n}\n\nexport function isClass(value: any): boolean {\n return (\n typeof value === \"function\" &&\n /^class\\s/.test(Function.prototype.toString.call(value))\n );\n}\n\nexport function isZodSchema(value: any): value is ZodTypeAny {\n return value?._def?.typeName?.startsWith(\"Zod\");\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\"\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n const result: Record<string, any> = {};\n\n if (!(await pathExists(subdir))) return result;\n\n try {\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n if (!fileName || !(await pathExists(filePath))) return;\n\n try {\n const module = await importModule(filePath).catch(\n async (err: any) => {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}: `);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n }\n );\n\n const cleanFilePath = `src/modules/${kebabCase(modelName)}/${fileName}`;\n if (type === \"dtos\" && !isClass(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid class under ${cleanFilePath}, in order to use as Dto.`\n );\n else if (type === \"schemas\" && !isZodSchema(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid zod schema under ${cleanFilePath}, in order to use as Schema`\n );\n\n if (module && module?.default) result[key] = module.default;\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n })\n );\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n\n return result;\n}\n\nexport type ModuleComponents = Omit<\n ImportModuleComponentsReturnType,\n \"authConfigsNew\" | \"prismaQueryOptionsNew\"\n>;\n\ntype ImportModuleComponentsReturnType = {\n hooks?: Record<string, ServiceHook | ServiceHook[]>;\n interceptors?: Record<string, Function | Function[]>;\n authConfigs?: AuthConfigs;\n interceptorsOld?: any;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: PrismaQueryOptions<any>;\n prismaQueryOptionsNew?: PrismaQueryOptions<any>;\n router?: { config?: RouterConfig<any>; default: RouterConfig };\n dtos?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n schemas?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n};\n\nconst availableInterceptors = {\n auth: [\n \"beforeGetMe\",\n \"afterGetMe\",\n \"onGetMeError\",\n \"beforeUpdateMe\",\n \"afterUpdateMe\",\n \"onUpdateMeError\",\n \"beforeLogin\",\n \"afterLogin\",\n \"onLoginError\",\n \"beforeLogout\",\n \"afterLogout\",\n \"onLogoutError\",\n \"beforeSignup\",\n \"afterSignup\",\n \"onSignupError\",\n \"beforeUpdatePassword\",\n \"afterUpdatePassword\",\n \"onUpdatePasswordError\",\n ],\n \"file-upload\": [\n \"beforeFindFile\",\n \"onFindFileError\",\n \"beforeUploadFile\",\n \"afterUploadFile\",\n \"onUploadFileError\",\n \"beforeUpdateFile\",\n \"afterUpdateFile\",\n \"onUpdateFileError\",\n \"beforeDeleteFile\",\n \"afterDeleteFile\",\n \"onDeleteFileError\",\n ],\n prisma: [\n \"beforeCreateOne\",\n \"afterCreateOne\",\n \"onCreateOneError\",\n \"beforeFindOne\",\n \"afterFindOne\",\n \"onFindOneError\",\n \"beforeFindMany\",\n \"afterFindMany\",\n \"onFindManyError\",\n \"beforeUpdateOne\",\n \"afterUpdateOne\",\n \"onUpdateOneError\",\n \"beforeDeleteOne\",\n \"afterDeleteOne\",\n \"onDeleteOneError\",\n \"beforeCreateMany\",\n \"afterCreateMany\",\n \"onCreateManyError\",\n \"beforeUpdateMany\",\n \"afterUpdateMany\",\n \"onUpdateManyError\",\n \"beforeDeleteMany\",\n \"afterDeleteMany\",\n \"onDeleteManyError\",\n ],\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {ImportModuleComponentsReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: ImportModuleComponentsReturnType\n): void {\n if (key === \"interceptorsOld\") {\n if (!result.interceptors)\n sheu.warn(\n `Found deprecated ${fileName} that will removed from v1.6.0-beta, consider switching to ${fileName.replace(\"middlewares\", \"interceptors\")}`\n );\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {ImportModuleComponentsReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n appModule: string,\n key: string,\n module: any,\n result: ImportModuleComponentsReturnType,\n arkosConfig: ArkosConfig\n): void {\n if (key === \"interceptors\") result.interceptors = module;\n else if (key === \"interceptorsOld\") {\n const kebabCaseAppModule = kebabCase(appModule);\n const moduleName =\n kebabCaseAppModule === \"auth\"\n ? \"auth\"\n : kebabCaseAppModule === \"file-upload\"\n ? \"file-upload\"\n : \"prisma\";\n\n if (\n result.interceptors &&\n Object.keys(module).some((interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n )\n ) {\n const exportedInterceptors = Object.keys(module).filter(\n (interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n );\n const ext = getUserFileExtension();\n sheu.warn(\n `Found ${kebabCaseAppModule}.middlewares.${ext} exporting ${exportedInterceptors.join(\", \")}. Which by convention should go at ${kebabCaseAppModule}.interceptors.${ext} This is simply a warning that will stop from v1.5.0-beta`\n );\n } else if (!result.interceptors) result.interceptors = module;\n } else if (key === \"router\") {\n result[key] = {\n ...module,\n config: applyStrictRoutingRules(\n appModule,\n arkosConfig,\n module?.config || {}\n ),\n };\n validateRouterConfigConsistency(\n kebabCase(appModule),\n result[key]?.config || {}\n );\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importModuleComponents(\n modelName: string,\n arkosConfig: ArkosConfig,\n moduleDirExists?: boolean\n): Promise<ImportModuleComponentsReturnType> {\n const result: ImportModuleComponentsReturnType = {\n dtos: {},\n schemas: {},\n };\n const usingStrictRouting = arkosConfig.routers?.strict;\n\n if (!moduleDirExists && !usingStrictRouting) return result;\n\n if (getModuleComponents(modelName)) return getModuleComponents(modelName);\n\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n\n const validationSubdir = arkosConfig.validation?.resolver\n ? arkosConfig.validation.resolver === \"zod\"\n ? \"schemas\"\n : \"dtos\"\n : null;\n\n const [validators] = await Promise.all([\n validationSubdir && processSubdir(modelName, validationSubdir),\n ...Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n if (\n [\"createMany\", \"findMany\", \"findOne\", \"updateMany\"].includes(key) ||\n !fileName\n )\n return;\n\n const filePath = path.join(moduleDir, fileName);\n\n if (\n key === \"router\" &&\n !usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n else if (\n key !== \"router\" &&\n usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n\n try {\n let module = await importModule(filePath).catch(async (err) => {\n try {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}`);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n } catch (err) {}\n });\n\n if (!module && key === \"router\" && usingStrictRouting) module = {};\n\n if (module) {\n (result as any)[key] = module;\n validateNamingConventions(key, fileName, result);\n assignModuleToResult(modelName, key, module, result, arkosConfig);\n }\n } catch (err: any) {\n if (err.message?.includes(\"Cannot use both\")) throw err;\n console.error(err);\n killServerChildProcess();\n }\n }),\n ]);\n\n prismaModelsModules[pascalCase(modelName)] = {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n\n return {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n}\n\nexport const appModules = Array.from(\n new Set([\n \"auth\",\n \"file-upload\",\n ...(prismaSchemaParser.getModelsAsArrayOfStrings() || []),\n ])\n);\n\n/**\n * Allows to asynchronously load all app modules components at once to speed up app start time.\n */\nexport async function loadAllModuleComponents(arkosConfig: ArkosConfig) {\n const moduleDirExists: string[] = [];\n await Promise.all(\n appModules.map(async (appModule) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModule)\n );\n if (await pathExists(moduleDir)) moduleDirExists.push(appModule);\n })\n );\n\n const modulesComponentsImportPromises = appModules.map(\n async (appModule) =>\n await importModuleComponents(\n appModule,\n arkosConfig,\n moduleDirExists.includes(appModule)\n )\n );\n\n const modulesComponents = await Promise.all(modulesComponentsImportPromises);\n debuggerService.logDynamicLoadedModulesComponents(\n modulesComponents.map((components, i) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModules[i])\n );\n\n return {\n moduleName: kebabCase(appModules[i]),\n moduleDir,\n components,\n };\n })\n );\n}\n"]}
|
|
@@ -60,12 +60,11 @@ function getAuthenticationConfig(endpoint, modelName, authConfigs) {
|
|
|
60
60
|
(authenticationControl[action] === true ||
|
|
61
61
|
authenticationControl[action] !== false)) ||
|
|
62
62
|
(!authenticationControl && authenticationControl !== false)) {
|
|
63
|
+
const rule = authConfigs?.accessControl;
|
|
63
64
|
return {
|
|
64
65
|
resource: (0, change_case_helpers_1.kebabCase)(pluralize_1.default.singular(modelName)),
|
|
65
66
|
action: action,
|
|
66
|
-
rule:
|
|
67
|
-
? authConfigs?.accessControl
|
|
68
|
-
: (authConfigs?.accessControl || {})?.[action],
|
|
67
|
+
rule: rule && (action in rule ? rule[action] : rule),
|
|
69
68
|
};
|
|
70
69
|
}
|
|
71
70
|
return false;
|