@stryke/prisma-trpc-generator 0.2.1 → 0.2.3

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.
@@ -1,523 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/prisma-generator.ts
32
- var prisma_generator_exports = {};
33
- __export(prisma_generator_exports, {
34
- generate: () => generate
35
- });
36
- module.exports = __toCommonJS(prisma_generator_exports);
37
- var import_internals2 = require("@prisma/internals");
38
- var import_node_fs2 = require("fs");
39
- var import_node_path3 = __toESM(require("path"), 1);
40
- var import_pluralize = __toESM(require("pluralize"), 1);
41
- var import_prisma_generator = require("prisma-trpc-shield-generator/lib/prisma-generator");
42
- var import_prisma_generator2 = require("prisma-zod-generator/lib/prisma-generator");
43
-
44
- // src/config.ts
45
- var import_generator_helper = require("@prisma/generator-helper");
46
- var import_zod = require("zod");
47
- var configBoolean = import_zod.z.enum([
48
- "true",
49
- "false"
50
- ]).transform((arg) => JSON.parse(arg));
51
- var configMiddleware = import_zod.z.union([
52
- configBoolean,
53
- import_zod.z.string().default("../../../../src/middleware")
54
- ]);
55
- var configShield = import_zod.z.union([
56
- configBoolean,
57
- import_zod.z.string().default("../../../../src/shield")
58
- ]);
59
- var modelActionEnum = import_zod.z.nativeEnum(import_generator_helper.DMMF.ModelAction);
60
- var configSchema = import_zod.z.object({
61
- withMiddleware: configMiddleware.default("true"),
62
- withShield: configShield.default("true"),
63
- withZod: configBoolean.default("true"),
64
- contextPath: import_zod.z.string().default("../../../../src/context"),
65
- trpcOptionsPath: import_zod.z.string().optional(),
66
- showModelNameInProcedure: configBoolean.default("true"),
67
- generateModelActions: import_zod.z.string().default(Object.values(import_generator_helper.DMMF.ModelAction).join(",")).transform((arg) => {
68
- return arg.split(",").map((action) => modelActionEnum.parse(action.trim()));
69
- })
70
- });
71
-
72
- // src/helpers.ts
73
- var import_internals = require("@prisma/internals");
74
-
75
- // src/utils/getRelativePath.ts
76
- var import_node_path = __toESM(require("path"), 1);
77
- function getRelativePath(outputPath, filePath, isOutsideOutputPath, schemaPath) {
78
- const fromPath = import_node_path.default.join(outputPath, "routers", "helpers");
79
- let toPath = import_node_path.default.join(outputPath, filePath);
80
- if (isOutsideOutputPath) {
81
- const schemaPathSplit = schemaPath?.split(import_node_path.default.sep);
82
- const schemaPathWithoutFileAndExtension = schemaPathSplit.slice(0, schemaPathSplit.length - 1).join(import_node_path.default.posix.sep);
83
- toPath = import_node_path.default.join(schemaPathWithoutFileAndExtension, filePath);
84
- }
85
- const newPath = import_node_path.default.relative(fromPath, toPath).split(import_node_path.default.sep).join(import_node_path.default.posix.sep);
86
- return newPath;
87
- }
88
- __name(getRelativePath, "getRelativePath");
89
-
90
- // src/utils/uncapitalizeFirstLetter.ts
91
- var uncapitalizeFirstLetter = /* @__PURE__ */ __name((str) => {
92
- return str.charAt(0).toLowerCase() + str.slice(1);
93
- }, "uncapitalizeFirstLetter");
94
-
95
- // src/helpers.ts
96
- var getProcedureName = /* @__PURE__ */ __name((config) => {
97
- return config.withShield ? "shieldedProcedure" : config.withMiddleware ? "protectedProcedure" : "publicProcedure";
98
- }, "getProcedureName");
99
- var generateCreateRouterImport = /* @__PURE__ */ __name(({ sourceFile, config }) => {
100
- const imports = [
101
- "t"
102
- ];
103
- if (config) {
104
- imports.push(getProcedureName(config));
105
- }
106
- sourceFile.addImportDeclaration({
107
- moduleSpecifier: "./helpers/createRouter",
108
- namedImports: imports
109
- });
110
- }, "generateCreateRouterImport");
111
- var generateRPCImport = /* @__PURE__ */ __name((sourceFile) => {
112
- sourceFile.addImportDeclaration({
113
- moduleSpecifier: "@trpc/server",
114
- namespaceImport: "trpc"
115
- });
116
- }, "generateRPCImport");
117
- var generateShieldImport = /* @__PURE__ */ __name((sourceFile, options, value) => {
118
- const outputDir = (0, import_internals.parseEnvValue)(options.generator.output);
119
- let shieldPath = getRelativePath(outputDir, "shield/shield");
120
- if (typeof value === "string") {
121
- shieldPath = getRelativePath(outputDir, value, true, options.schemaPath);
122
- }
123
- sourceFile.addImportDeclaration({
124
- moduleSpecifier: shieldPath,
125
- namedImports: [
126
- "permissions"
127
- ]
128
- });
129
- }, "generateShieldImport");
130
- var generateRouterImport = /* @__PURE__ */ __name((sourceFile, modelNamePlural, modelNameCamelCase) => {
131
- sourceFile.addImportDeclaration({
132
- moduleSpecifier: `./${modelNameCamelCase}.router`,
133
- namedImports: [
134
- `${modelNamePlural}Router`
135
- ]
136
- });
137
- }, "generateRouterImport");
138
- function generateBaseRouter(sourceFile, config, options) {
139
- const outputDir = (0, import_internals.parseEnvValue)(options.generator.output);
140
- sourceFile.addStatements(
141
- /* ts */
142
- `
143
- import type { Context } from '${getRelativePath(outputDir, config.contextPath, true, options.schemaPath)}';
144
- `
145
- );
146
- if (config.trpcOptionsPath) {
147
- sourceFile.addStatements(
148
- /* ts */
149
- `
150
- import trpcOptions from '${getRelativePath(outputDir, config.trpcOptionsPath, true, options.schemaPath)}';
151
- `
152
- );
153
- }
154
- sourceFile.addStatements(
155
- /* ts */
156
- `
157
- export const t = trpc.initTRPC.context<Context>().create(${config.trpcOptionsPath ? "trpcOptions" : ""});
158
- `
159
- );
160
- const middlewares = [];
161
- if (config.withMiddleware && typeof config.withMiddleware === "boolean") {
162
- sourceFile.addStatements(
163
- /* ts */
164
- `
165
- export const globalMiddleware = t.middleware(async ({ ctx, next }) => {
166
- console.log('inside middleware!')
167
- return next()
168
- });`
169
- );
170
- middlewares.push({
171
- type: "global",
172
- value: (
173
- /* ts */
174
- `.use(globalMiddleware)`
175
- )
176
- });
177
- }
178
- if (config.withMiddleware && typeof config.withMiddleware === "string") {
179
- sourceFile.addStatements(
180
- /* ts */
181
- `
182
- import defaultMiddleware from '${getRelativePath(outputDir, config.withMiddleware, true, options.schemaPath)}';
183
- `
184
- );
185
- sourceFile.addStatements(
186
- /* ts */
187
- `
188
- export const globalMiddleware = t.middleware(defaultMiddleware);`
189
- );
190
- middlewares.push({
191
- type: "global",
192
- value: (
193
- /* ts */
194
- `.use(globalMiddleware)`
195
- )
196
- });
197
- }
198
- if (config.withShield) {
199
- sourceFile.addStatements(
200
- /* ts */
201
- `
202
- export const permissionsMiddleware = t.middleware(permissions); `
203
- );
204
- middlewares.push({
205
- type: "shield",
206
- value: (
207
- /* ts */
208
- `
209
- .use(permissions)`
210
- )
211
- });
212
- }
213
- sourceFile.addStatements(
214
- /* ts */
215
- `
216
- export const publicProcedure = t.procedure; `
217
- );
218
- if (middlewares.length > 0) {
219
- const procName = getProcedureName(config);
220
- middlewares.forEach((middleware, i) => {
221
- if (i === 0) {
222
- sourceFile.addStatements(
223
- /* ts */
224
- `
225
- export const ${procName} = t.procedure
226
- `
227
- );
228
- }
229
- sourceFile.addStatements(
230
- /* ts */
231
- `
232
- .use(${middleware.type === "shield" ? "permissionsMiddleware" : "globalMiddleware"})
233
- `
234
- );
235
- });
236
- }
237
- }
238
- __name(generateBaseRouter, "generateBaseRouter");
239
- function generateProcedure(sourceFile, name, typeName, modelName, opType, baseOpType, config) {
240
- let input = `input${!config.withZod ? " as any" : ""}`;
241
- const nameWithoutModel = name.replace(modelName, "");
242
- if (nameWithoutModel === "groupBy" && config.withZod) {
243
- input = "{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }";
244
- }
245
- sourceFile.addStatements(
246
- /* ts */
247
- `${config.showModelNameInProcedure ? name : nameWithoutModel}: ${getProcedureName(config)}
248
- ${config.withZod ? `.input(${typeName})` : ""}.${getProcedureTypeByOpName(baseOpType)}(async ({ ctx, input }) => {
249
- const ${name} = await ctx.prisma.${uncapitalizeFirstLetter(modelName)}.${opType.replace("One", "")}(${input});
250
- return ${name};
251
- }),`
252
- );
253
- }
254
- __name(generateProcedure, "generateProcedure");
255
- function generateRouterSchemaImports(sourceFile, modelName, modelActions) {
256
- sourceFile.addStatements(
257
- /* ts */
258
- [
259
- // remove any duplicate import statements
260
- ...new Set(modelActions.map((opName) => getRouterSchemaImportByOpName(opName, modelName)))
261
- ].join("\n")
262
- );
263
- }
264
- __name(generateRouterSchemaImports, "generateRouterSchemaImports");
265
- var getRouterSchemaImportByOpName = /* @__PURE__ */ __name((opName, modelName) => {
266
- const opType = opName.replace("OrThrow", "");
267
- const inputType = getInputTypeByOpName(opType, modelName);
268
- return inputType ? `import { ${inputType} } from "../schemas/${opType}${modelName}.schema"; ` : "";
269
- }, "getRouterSchemaImportByOpName");
270
- var getInputTypeByOpName = /* @__PURE__ */ __name((opName, modelName) => {
271
- let inputType;
272
- switch (opName) {
273
- case "findUnique":
274
- inputType = `${modelName}FindUniqueSchema`;
275
- break;
276
- case "findFirst":
277
- inputType = `${modelName}FindFirstSchema`;
278
- break;
279
- case "findMany":
280
- inputType = `${modelName}FindManySchema`;
281
- break;
282
- case "findRaw":
283
- inputType = `${modelName}FindRawObjectSchema`;
284
- break;
285
- case "createOne":
286
- inputType = `${modelName}CreateOneSchema`;
287
- break;
288
- case "createMany":
289
- inputType = `${modelName}CreateManySchema`;
290
- break;
291
- case "deleteOne":
292
- inputType = `${modelName}DeleteOneSchema`;
293
- break;
294
- case "updateOne":
295
- inputType = `${modelName}UpdateOneSchema`;
296
- break;
297
- case "deleteMany":
298
- inputType = `${modelName}DeleteManySchema`;
299
- break;
300
- case "updateMany":
301
- inputType = `${modelName}UpdateManySchema`;
302
- break;
303
- case "upsertOne":
304
- inputType = `${modelName}UpsertSchema`;
305
- break;
306
- case "aggregate":
307
- inputType = `${modelName}AggregateSchema`;
308
- break;
309
- case "aggregateRaw":
310
- inputType = `${modelName}AggregateRawObjectSchema`;
311
- break;
312
- case "groupBy":
313
- inputType = `${modelName}GroupBySchema`;
314
- break;
315
- default:
316
- console.log("getInputTypeByOpName: ", {
317
- opName,
318
- modelName
319
- });
320
- }
321
- return inputType;
322
- }, "getInputTypeByOpName");
323
- var getProcedureTypeByOpName = /* @__PURE__ */ __name((opName) => {
324
- let procType;
325
- switch (opName) {
326
- case "findUnique":
327
- case "findFirst":
328
- case "findMany":
329
- case "findRaw":
330
- case "aggregate":
331
- case "aggregateRaw":
332
- case "groupBy":
333
- procType = "query";
334
- break;
335
- case "createOne":
336
- case "createMany":
337
- case "deleteOne":
338
- case "updateOne":
339
- case "deleteMany":
340
- case "updateMany":
341
- case "upsertOne":
342
- procType = "mutation";
343
- break;
344
- default:
345
- console.log("getProcedureTypeByOpName: ", {
346
- opName
347
- });
348
- }
349
- return procType;
350
- }, "getProcedureTypeByOpName");
351
- function resolveModelsComments(models, hiddenModels) {
352
- const modelAttributeRegex = /(?:@@Gen\.)+[A-z]+\(.+\)/;
353
- const attributeNameRegex = /\.+[A-Z]+\(+/i;
354
- const attributeArgsRegex = /\(+[A-Z]+:.+\)/i;
355
- for (const model of models) {
356
- if (model.documentation) {
357
- const attribute = model.documentation?.match(modelAttributeRegex)?.[0];
358
- const attributeName = attribute?.match(attributeNameRegex)?.[0]?.slice(1, -1);
359
- if (attributeName !== "model") continue;
360
- const rawAttributeArgs = attribute?.match(attributeArgsRegex)?.[0]?.slice(1, -1);
361
- const parsedAttributeArgs = {};
362
- if (rawAttributeArgs) {
363
- const rawAttributeArgsParts = rawAttributeArgs.split(":").map((it) => it.trim()).map((part) => part.startsWith("[") ? part : part.split(",")).flat().map((it) => it.trim());
364
- for (let i = 0; i < rawAttributeArgsParts.length; i += 2) {
365
- const key = rawAttributeArgsParts[i];
366
- const value = rawAttributeArgsParts[i + 1];
367
- parsedAttributeArgs[key] = JSON.parse(value);
368
- }
369
- }
370
- if (parsedAttributeArgs.hide) {
371
- hiddenModels.push(model.name);
372
- }
373
- }
374
- }
375
- }
376
- __name(resolveModelsComments, "resolveModelsComments");
377
-
378
- // src/project.ts
379
- var import_ts_morph = require("ts-morph");
380
- var compilerOptions = {
381
- target: import_ts_morph.ScriptTarget.ES2019,
382
- module: import_ts_morph.ModuleKind.CommonJS,
383
- emitDecoratorMetadata: true,
384
- experimentalDecorators: true,
385
- esModuleInterop: true
386
- };
387
- var project = new import_ts_morph.Project({
388
- compilerOptions: {
389
- ...compilerOptions
390
- }
391
- });
392
-
393
- // src/utils/removeDir.ts
394
- var import_node_fs = require("fs");
395
- var import_node_path2 = __toESM(require("path"), 1);
396
- async function removeDir(dirPath, onlyContent) {
397
- const dirEntries = await import_node_fs.promises.readdir(dirPath, {
398
- withFileTypes: true
399
- });
400
- await Promise.all(dirEntries.map(async (dirEntry) => {
401
- const fullPath = import_node_path2.default.join(dirPath, dirEntry.name);
402
- return dirEntry.isDirectory() ? removeDir(fullPath, false) : import_node_fs.promises.unlink(fullPath);
403
- }));
404
- if (!onlyContent) {
405
- await import_node_fs.promises.rmdir(dirPath);
406
- }
407
- }
408
- __name(removeDir, "removeDir");
409
-
410
- // src/prisma-generator.ts
411
- async function generate(options) {
412
- const outputDir = (0, import_internals2.parseEnvValue)(options.generator.output);
413
- const results = configSchema.safeParse(options.generator.config);
414
- if (!results.success) throw new Error("Invalid options passed");
415
- const config = results.data;
416
- await import_node_fs2.promises.mkdir(outputDir, {
417
- recursive: true
418
- });
419
- await removeDir(outputDir, true);
420
- if (config.withZod) {
421
- await (0, import_prisma_generator2.generate)(options);
422
- }
423
- if (config.withShield === true) {
424
- const shieldOutputPath = import_node_path3.default.join(outputDir, "./shield");
425
- await (0, import_prisma_generator.generate)({
426
- ...options,
427
- generator: {
428
- ...options.generator,
429
- output: {
430
- ...options.generator.output,
431
- value: shieldOutputPath
432
- },
433
- config: {
434
- ...options.generator.config,
435
- contextPath: config.contextPath
436
- }
437
- }
438
- });
439
- }
440
- const prismaClientProvider = options.otherGenerators.find((it) => (0, import_internals2.parseEnvValue)(it.provider) === "prisma-client-js");
441
- const prismaClientDmmf = await (0, import_internals2.getDMMF)({
442
- datamodel: options.datamodel,
443
- previewFeatures: prismaClientProvider.previewFeatures
444
- });
445
- const modelOperations = prismaClientDmmf.mappings.modelOperations;
446
- const models = prismaClientDmmf.datamodel.models;
447
- const hiddenModels = [];
448
- resolveModelsComments(models, hiddenModels);
449
- const createRouter = project.createSourceFile(import_node_path3.default.resolve(outputDir, "routers", "helpers", "createRouter.ts"), void 0, {
450
- overwrite: true
451
- });
452
- generateRPCImport(createRouter);
453
- if (config.withShield) {
454
- generateShieldImport(createRouter, options, config.withShield);
455
- }
456
- generateBaseRouter(createRouter, config, options);
457
- createRouter.formatText({
458
- indentSize: 2
459
- });
460
- const appRouter = project.createSourceFile(import_node_path3.default.resolve(outputDir, "routers", `index.ts`), void 0, {
461
- overwrite: true
462
- });
463
- generateCreateRouterImport({
464
- sourceFile: appRouter
465
- });
466
- const routerStatements = [];
467
- for (const modelOperation of modelOperations) {
468
- const { model, ...operations } = modelOperation;
469
- if (hiddenModels.includes(model)) continue;
470
- const modelActions = Object.keys(operations).filter((opType) => config.generateModelActions.includes(opType.replace("One", "")));
471
- if (!modelActions.length) continue;
472
- const plural = (0, import_pluralize.default)(model.toLowerCase());
473
- generateRouterImport(appRouter, plural, model);
474
- const modelRouter = project.createSourceFile(import_node_path3.default.resolve(outputDir, "routers", `${model}.router.ts`), void 0, {
475
- overwrite: true
476
- });
477
- generateCreateRouterImport({
478
- sourceFile: modelRouter,
479
- config
480
- });
481
- if (config.withZod) {
482
- generateRouterSchemaImports(modelRouter, model, modelActions);
483
- }
484
- modelRouter.addStatements(
485
- /* ts */
486
- `
487
- export const ${plural}Router = t.router({`
488
- );
489
- for (const opType of modelActions) {
490
- const opNameWithModel = operations[opType];
491
- const baseOpType = opType.replace("OrThrow", "");
492
- generateProcedure(modelRouter, opNameWithModel, getInputTypeByOpName(baseOpType, model), model, opType, baseOpType, config);
493
- }
494
- modelRouter.addStatements(
495
- /* ts */
496
- `
497
- })`
498
- );
499
- modelRouter.formatText({
500
- indentSize: 2
501
- });
502
- routerStatements.push(
503
- /* ts */
504
- `
505
- ${model.toLowerCase()}: ${plural}Router`
506
- );
507
- }
508
- appRouter.addStatements(
509
- /* ts */
510
- `
511
- export const appRouter = t.router({${routerStatements}})
512
- `
513
- );
514
- appRouter.formatText({
515
- indentSize: 2
516
- });
517
- await project.save();
518
- }
519
- __name(generate, "generate");
520
- // Annotate the CommonJS export names for ESM import in node:
521
- 0 && (module.exports = {
522
- generate
523
- });
@@ -1,10 +0,0 @@
1
- import {
2
- generate
3
- } from "./chunk-GQ7ABBSV.js";
4
- import "./chunk-V6DNCMCB.js";
5
- import "./chunk-RYVIOFDO.js";
6
- import "./chunk-LVOPI6NH.js";
7
- import "./chunk-SHUYVCID.js";
8
- export {
9
- generate
10
- };
package/dist/project.cjs DELETED
@@ -1,42 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/project.ts
21
- var project_exports = {};
22
- __export(project_exports, {
23
- project: () => project
24
- });
25
- module.exports = __toCommonJS(project_exports);
26
- var import_ts_morph = require("ts-morph");
27
- var compilerOptions = {
28
- target: import_ts_morph.ScriptTarget.ES2019,
29
- module: import_ts_morph.ModuleKind.CommonJS,
30
- emitDecoratorMetadata: true,
31
- experimentalDecorators: true,
32
- esModuleInterop: true
33
- };
34
- var project = new import_ts_morph.Project({
35
- compilerOptions: {
36
- ...compilerOptions
37
- }
38
- });
39
- // Annotate the CommonJS export names for ESM import in node:
40
- 0 && (module.exports = {
41
- project
42
- });
package/dist/project.js DELETED
@@ -1,7 +0,0 @@
1
- import {
2
- project
3
- } from "./chunk-LVOPI6NH.js";
4
- import "./chunk-SHUYVCID.js";
5
- export {
6
- project
7
- };