Skip to content

fix: clean up generation of logical prisma client #1082

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/plugins/openapi/src/generator-base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { DMMF } from '@prisma/generator-helper';
import { PluginError, PluginOptions, getDataModels, hasAttribute } from '@zenstackhq/sdk';
import { PluginError, PluginOptions, PluginResult, getDataModels, hasAttribute } from '@zenstackhq/sdk';
import { Model } from '@zenstackhq/sdk/ast';
import type { OpenAPIV3_1 as OAPI } from 'openapi-types';
import semver from 'semver';
Expand All @@ -12,7 +12,7 @@ export abstract class OpenAPIGeneratorBase {

constructor(protected model: Model, protected options: PluginOptions, protected dmmf: DMMF.Document) {}

abstract generate(): string[];
abstract generate(): PluginResult;

protected get includedModels() {
return getDataModels(this.model).filter((d) => !hasAttribute(d, '@@openapi.ignore'));
Expand Down
14 changes: 9 additions & 5 deletions packages/plugins/openapi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import type { DMMF } from '@prisma/generator-helper';
import { PluginError, PluginOptions } from '@zenstackhq/sdk';
import { Model } from '@zenstackhq/sdk/ast';
import { PluginError, PluginFunction } from '@zenstackhq/sdk';
import { RESTfulOpenAPIGenerator } from './rest-generator';
import { RPCOpenAPIGenerator } from './rpc-generator';

export const name = 'OpenAPI';

export default async function run(model: Model, options: PluginOptions, dmmf: DMMF.Document) {
const run: PluginFunction = async (model, options, dmmf) => {
if (!dmmf) {
throw new Error('DMMF is required');
}

const flavor = options.flavor ? (options.flavor as string) : 'rpc';

switch (flavor) {
Expand All @@ -17,4 +19,6 @@ export default async function run(model: Model, options: PluginOptions, dmmf: DM
default:
throw new PluginError(name, `Unknown flavor: ${flavor}`);
}
}
};

export default run;
2 changes: 1 addition & 1 deletion packages/plugins/openapi/src/rest-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export class RESTfulOpenAPIGenerator extends OpenAPIGeneratorBase {
fs.writeFileSync(output, JSON.stringify(openapi, undefined, 2));
}

return this.warnings;
return { warnings: this.warnings };
}

private generatePaths(): OAPI.PathsObject {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/openapi/src/rpc-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase {
fs.writeFileSync(output, JSON.stringify(openapi, undefined, 2));
}

return this.warnings;
return { warnings: this.warnings };
}

private generatePaths(components: OAPI.ComponentsObject): OAPI.PathsObject {
Expand Down
9 changes: 5 additions & 4 deletions packages/plugins/swr/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,26 +49,27 @@ export async function generate(model: Model, options: PluginOptions, dmmf: DMMF.
warnings.push(`Unable to find mapping for model ${dataModel.name}`);
return;
}
generateModelHooks(project, outDir, dataModel, mapping, legacyMutations);
generateModelHooks(project, outDir, dataModel, mapping, legacyMutations, options);
});

await saveProject(project);
return warnings;
return { warnings };
}

function generateModelHooks(
project: Project,
outDir: string,
model: DataModel,
mapping: DMMF.ModelMapping,
legacyMutations: boolean
legacyMutations: boolean,
options: PluginOptions
) {
const fileName = paramCase(model.name);
const sf = project.createSourceFile(path.join(outDir, `${fileName}.ts`), undefined, { overwrite: true });

sf.addStatements('/* eslint-disable */');

const prismaImport = getPrismaClientImportSpec(model.$container, outDir);
const prismaImport = getPrismaClientImportSpec(outDir, options);
sf.addImportDeclaration({
namedImports: ['Prisma'],
isTypeOnly: true,
Comment on lines 49 to 75
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [40-40]

Detected potential security risk related to path traversal vulnerabilities due to user input being used in path.join or path.resolve functions. Ensure that the outDir and other path-related inputs are properly sanitized or validated to prevent unauthorized file system access.

- let outDir = requireOption<string>(options, 'output', name);
+ let outDir = sanitizePath(requireOption<string>(options, 'output', name));

Consider implementing a sanitizePath function that checks and cleans the input path to mitigate this risk.

Also applies to: 68-68, 279-279

Expand Down
13 changes: 8 additions & 5 deletions packages/plugins/swr/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import type { DMMF } from '@prisma/generator-helper';
import type { PluginOptions } from '@zenstackhq/sdk';
import type { Model } from '@zenstackhq/sdk/ast';
import type { PluginFunction } from '@zenstackhq/sdk';
import { generate } from './generator';

export const name = 'SWR';

export default async function run(model: Model, options: PluginOptions, dmmf: DMMF.Document) {
const run: PluginFunction = async (model, options, dmmf) => {
if (!dmmf) {
throw new Error('DMMF is required');
}
return generate(model, options, dmmf);
}
};

export default run;
9 changes: 5 additions & 4 deletions packages/plugins/tanstack-query/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ export async function generate(model: Model, options: PluginOptions, dmmf: DMMF.
warnings.push(`Unable to find mapping for model ${dataModel.name}`);
return;
}
generateModelHooks(target, version, project, outDir, dataModel, mapping);
generateModelHooks(target, version, project, outDir, dataModel, mapping, options);
});

await saveProject(project);
return warnings;
return { warnings };
}

function generateQueryHook(
Comment on lines 55 to 65
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [46-46]

Potential security risk: Ensure that user input passed to path.join or path.resolve is properly sanitized or validated to prevent path traversal vulnerabilities.


📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [295-295]

Potential security risk: Ensure that user input passed to path.join or path.resolve is properly sanitized or validated to prevent path traversal vulnerabilities.


📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [531-531]

Potential security risk: Ensure that user input passed to path.join or path.resolve is properly sanitized or validated to prevent path traversal vulnerabilities.

Expand Down Expand Up @@ -286,7 +286,8 @@ function generateModelHooks(
project: Project,
outDir: string,
model: DataModel,
mapping: DMMF.ModelMapping
mapping: DMMF.ModelMapping,
options: PluginOptions
) {
const modelNameCap = upperCaseFirst(model.name);
const prismaVersion = getPrismaVersion();
Expand All @@ -295,7 +296,7 @@ function generateModelHooks(

sf.addStatements('/* eslint-disable */');

const prismaImport = getPrismaClientImportSpec(model.$container, outDir);
const prismaImport = getPrismaClientImportSpec(outDir, options);
sf.addImportDeclaration({
namedImports: ['Prisma', model.name],
isTypeOnly: true,
Expand Down
13 changes: 8 additions & 5 deletions packages/plugins/tanstack-query/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import type { DMMF } from '@prisma/generator-helper';
import type { PluginOptions } from '@zenstackhq/sdk';
import type { Model } from '@zenstackhq/sdk/ast';
import type { PluginFunction } from '@zenstackhq/sdk';
import { generate } from './generator';

export const name = 'Tanstack Query';

export default async function run(model: Model, options: PluginOptions, dmmf: DMMF.Document) {
const run: PluginFunction = async (model, options, dmmf) => {
if (!dmmf) {
throw new Error('DMMF is required');
}
return generate(model, options, dmmf);
}
};

export default run;
18 changes: 10 additions & 8 deletions packages/plugins/trpc/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ export async function generate(model: Model, options: PluginOptions, dmmf: DMMF.
generateModelActions,
generateClientHelpers,
model,
zodSchemasImport
zodSchemasImport,
options
);
createHelper(outDir);

Expand All @@ -86,7 +87,8 @@ function createAppRouter(
generateModelActions: string[] | undefined,
generateClientHelpers: string[] | undefined,
zmodel: Model,
zodSchemasImport: string
zodSchemasImport: string,
options: PluginOptions
) {
const indexFile = path.resolve(outDir, 'routers', `index.ts`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Detected potential security risk related to path traversal vulnerabilities. Ensure that user input influencing file paths, such as outputDir and other parameters, is properly sanitized or validated to prevent unauthorized access to the file system. Consider implementing strict validation rules or using a whitelist approach for allowed paths.

Also applies to: 213-213, 222-222, 230-230, 247-247, 327-327

const appRouter = project.createSourceFile(indexFile, undefined, {
Expand All @@ -95,7 +97,7 @@ function createAppRouter(

appRouter.addStatements('/* eslint-disable */');

const prismaImport = getPrismaClientImportSpec(zmodel, path.dirname(indexFile));
const prismaImport = getPrismaClientImportSpec(path.dirname(indexFile), options);
appRouter.addImportDeclarations([
{
namedImports: [
Expand Down Expand Up @@ -169,8 +171,8 @@ function createAppRouter(
outDir,
generateModelActions,
generateClientHelpers,
zmodel,
zodSchemasImport
zodSchemasImport,
options
);

appRouter.addImportDeclaration({
Expand Down Expand Up @@ -239,8 +241,8 @@ function generateModelCreateRouter(
outputDir: string,
generateModelActions: string[] | undefined,
generateClientHelpers: string[] | undefined,
zmodel: Model,
zodSchemasImport: string
zodSchemasImport: string,
options: PluginOptions
) {
const modelRouter = project.createSourceFile(path.resolve(outputDir, 'routers', `${model}.router.ts`), undefined, {
overwrite: true,
Expand All @@ -258,7 +260,7 @@ function generateModelCreateRouter(
generateRouterSchemaImport(modelRouter, zodSchemasImport);
generateHelperImport(modelRouter);
if (generateClientHelpers) {
generateRouterTypingImports(modelRouter, zmodel);
generateRouterTypingImports(modelRouter, options);
}

const createRouterFunc = modelRouter.addFunction({
Expand Down
7 changes: 3 additions & 4 deletions packages/plugins/trpc/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { DMMF } from '@prisma/generator-helper';
import { PluginError, getPrismaClientImportSpec } from '@zenstackhq/sdk';
import { Model } from '@zenstackhq/sdk/ast';
import { PluginError, getPrismaClientImportSpec, type PluginOptions } from '@zenstackhq/sdk';
import { lowerCaseFirst } from 'lower-case-first';
import { CodeBlockWriter, SourceFile } from 'ts-morph';
import { upperCaseFirst } from 'upper-case-first';
Expand Down Expand Up @@ -225,9 +224,9 @@ export function generateRouterTyping(writer: CodeBlockWriter, opType: string, mo
});
}

export function generateRouterTypingImports(sourceFile: SourceFile, model: Model) {
export function generateRouterTypingImports(sourceFile: SourceFile, options: PluginOptions) {
const importingDir = sourceFile.getDirectoryPath();
const prismaImport = getPrismaClientImportSpec(model, importingDir);
const prismaImport = getPrismaClientImportSpec(importingDir, options);
sourceFile.addStatements([
`import type { Prisma } from '${prismaImport}';`,
`import type { UseTRPCMutationOptions, UseTRPCMutationResult, UseTRPCQueryOptions, UseTRPCQueryResult, UseTRPCInfiniteQueryOptions, UseTRPCInfiniteQueryResult } from '@trpc/react-query/shared';`,
Expand Down
13 changes: 8 additions & 5 deletions packages/plugins/trpc/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type { DMMF } from '@prisma/generator-helper';
import { PluginOptions } from '@zenstackhq/sdk';
import { Model } from '@zenstackhq/sdk/ast';
import type { PluginFunction } from '@zenstackhq/sdk';
import { generate } from './generator';

export const name = 'tRPC';
export const dependencies = ['@core/zod'];

export default async function run(model: Model, options: PluginOptions, dmmf: DMMF.Document) {
const run: PluginFunction = async (model, options, dmmf) => {
if (!dmmf) {
throw new Error('DMMF is required');
}
return generate(model, options, dmmf);
}
};

export default run;
3 changes: 3 additions & 0 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@
"import": "./cross/index.mjs",
"require": "./cross/index.js",
"default": "./cross/index.js"
},
"./prisma": {
"types": "./prisma.d.ts"
}
},
"publishConfig": {
Expand Down
1 change: 1 addition & 0 deletions packages/runtime/res/prisma.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type * from '.zenstack/prisma';
2 changes: 2 additions & 0 deletions packages/runtime/src/prisma.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// @ts-expect-error stub for re-exporting PrismaClient
export type * from '.zenstack/prisma';
Loading