CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-prisma--generator-helper

Helper utility for creating Prisma generators with JSON-RPC communication

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

@prisma/generator-helper

@prisma/generator-helper provides a standardized way to build custom code generation tools that extend Prisma's capabilities. It abstracts the complexity of the generator protocol by managing JSON-RPC communication between Prisma CLI and generator processes, offering interfaces for manifest retrieval and code generation handlers.

Package Information

  • Package Name: @prisma/generator-helper
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @prisma/generator-helper

Core Imports

import { generatorHandler } from "@prisma/generator-helper";

For CommonJS:

const { generatorHandler } = require("@prisma/generator-helper");

Advanced imports:

import { 
  generatorHandler, 
  GeneratorProcess, 
  GeneratorError 
} from "@prisma/generator-helper";

Basic Usage

import { generatorHandler } from "@prisma/generator-helper";

// Simple generator implementation
generatorHandler({
  onManifest: () => ({
    prettyName: "My Custom Generator",
    defaultOutput: "./generated"
  }),
  onGenerate: async (options) => {
    // Access the Prisma schema structure
    const { dmmf } = options;
    
    // Generate code based on models
    dmmf.datamodel.models.forEach(model => {
      console.log(`Generating code for model: ${model.name}`);
      // Your code generation logic here
    });
    
    // Write generated files to options.generator.output.value
  }
});

Architecture

@prisma/generator-helper is built around several key components:

  • Handler Interface: Simple callback-based API for implementing generators with onGenerate and optional onManifest methods
  • JSON-RPC Protocol: Automatic handling of communication between Prisma CLI and generator processes over stdin/stderr
  • Process Management: GeneratorProcess class for advanced scenarios requiring direct process control
  • Type Integration: Full TypeScript support with types from @prisma/generator and @prisma/dmmf packages
  • Error Handling: Standardized error reporting with GeneratorError class and automatic exception marshaling

Capabilities

Generator Handler

Core handler function that sets up JSON-RPC communication and manages the generator lifecycle. Use this for most generator implementations.

/**
 * Sets up JSON-RPC communication for a Prisma generator
 * @param handler - Handler object with lifecycle methods
 */
function generatorHandler(handler: Handler): void;

interface Handler {
  /** Required: Handle code generation requests */
  onGenerate(options: GeneratorOptions): Promise<any>;
  /** Optional: Provide generator metadata */
  onManifest?(config: GeneratorConfig): GeneratorManifest | Promise<GeneratorManifest>;
}

Process Management

Advanced generator process management for scenarios requiring direct control over subprocess communication.

class GeneratorProcess {
  constructor(pathOrCommand: string, options?: GeneratorProcessOptions);
  
  /** Initialize the generator process */
  init(): Promise<void>;
  /** Get generator manifest information */
  getManifest(config: GeneratorConfig): Promise<GeneratorManifest | null>;
  /** Execute code generation */
  generate(options: GeneratorOptions): Promise<void>;
  /** Stop the generator process */
  stop(): void;
}

interface GeneratorProcessOptions {
  isNode?: boolean;
}

Process Management

Error Handling

Custom error class for generator-specific failures with support for error codes and additional data.

class GeneratorError extends Error {
  name: "GeneratorError";
  
  constructor(
    message: string,
    code?: number,
    data?: any
  );
  
  code?: number;
  data?: any;
}

Core Types

interface GeneratorOptions {
  generator: GeneratorConfig;
  otherGenerators: GeneratorConfig[];
  schemaPath: string;
  dmmf: DMMF.Document;
  datasources: DataSource[];
  datamodel: string;
  version: string;
  binaryPaths?: BinaryPaths;
  postinstall?: boolean;
  noEngine?: boolean;
  noHints?: boolean;
  allowNoModels?: boolean;
  envPaths?: EnvPaths;
  typedSql?: SqlQueryOutput[];
}

interface GeneratorConfig {
  name: string;
  output: EnvValue | null;
  isCustomOutput?: boolean;
  provider: EnvValue;
  config: { [key: string]: string | string[] | undefined };
  binaryTargets: BinaryTargetsEnvValue[];
  previewFeatures: string[];
  envPaths?: EnvPaths;
  sourceFilePath: string;
}

interface GeneratorManifest {
  prettyName?: string;
  defaultOutput?: string;
  denylists?: {
    models?: string[];
    fields?: string[];
  };
  requiresGenerators?: string[];
  requiresEngines?: EngineType[];
  version?: string;
  requiresEngineVersion?: string;
}

interface EnvValue {
  fromEnvVar: null | string;
  value: null | string;
}

interface BinaryTargetsEnvValue {
  fromEnvVar: string | null;
  value: string;
  native?: boolean;
}

interface DataSource {
  name: string;
  provider: ConnectorType;
  activeProvider: ActiveConnectorType;
  url: EnvValue;
  directUrl?: EnvValue;
  schemas: string[];
  sourceFilePath: string;
}

type ConnectorType = 
  | "mysql" 
  | "mongodb" 
  | "sqlite" 
  | "postgresql" 
  | "postgres"
  | "prisma+postgres"
  | "sqlserver" 
  | "cockroachdb";

type ActiveConnectorType = Exclude<ConnectorType, "postgres" | "prisma+postgres">;

type EngineType = "queryEngine" | "libqueryEngine" | "schemaEngine";

type BinaryPaths = {
  schemaEngine?: { [binaryTarget: string]: string };
  queryEngine?: { [binaryTarget: string]: string };
  libqueryEngine?: { [binaryTarget: string]: string };
};

type EnvPaths = {
  rootEnvPath: string | null;
  schemaEnvPath: string | undefined;
};

type SqlQueryOutput = {
  name: string;
  source: string;
  documentation: string | null;
  parameters: SqlQueryParameterOutput[];
  resultColumns: SqlQueryColumnOutput[];
};

type SqlQueryParameterOutput = {
  name: string;
  typ: QueryIntrospectionType;
  documentation: string | null;
  nullable: boolean;
};

type SqlQueryColumnOutput = {
  name: string;
  typ: QueryIntrospectionType;
  nullable: boolean;
};

type QueryIntrospectionType = QueryIntrospectionBuiltinType | (string & {});

type QueryIntrospectionBuiltinType =
  | "int" | "bigint" | "float" | "double" | "string" | "enum" | "bytes" 
  | "bool" | "char" | "decimal" | "json" | "xml" | "uuid" | "datetime" 
  | "date" | "time" | "int-array" | "bigint-array" | "float-array" 
  | "double-array" | "string-array" | "char-array" | "bytes-array" 
  | "bool-array" | "decimal-array" | "json-array" | "xml-array" 
  | "uuid-array" | "datetime-array" | "date-array" | "time-array" 
  | "null" | "unknown";

Legacy Exports

The package includes deprecated re-exports for backwards compatibility:

/** @deprecated Use @prisma/dmmf package directly */
type DMMF = typeof import("@prisma/dmmf");

/** DMMF Document contains the complete Prisma schema structure */
namespace DMMF {
  interface Document {
    datamodel: Datamodel;
    schema: Schema;
    mappings: Mappings;
  }
  
  interface Datamodel {
    models: Model[];
    enums: DatamodelEnum[];
    types: Model[];
  }
  
  interface Model {
    name: string;
    dbName?: string;
    fields: Field[];
    primaryKey?: PrimaryKey;
    uniqueFields: string[][];
    uniqueIndexes: UniqueIndex[];
    documentation?: string;
  }
  
  interface Field {
    name: string;
    kind: FieldKind;
    isList: boolean;
    isRequired: boolean;
    isUnique: boolean;
    isId: boolean;
    isReadOnly: boolean;
    hasDefaultValue: boolean;
    type: string;
    documentation?: string;
  }
  
  type FieldKind = "scalar" | "object" | "enum" | "unsupported";
}

/** @deprecated Generators shouldn't need JSON-RPC internals */
namespace JsonRPC {
  type Request = {
    jsonrpc: "2.0";
    method: string;
    params?: any;
    id: number;
  };
  
  type Response = SuccessResponse | ErrorResponse;
  
  type SuccessResponse = {
    jsonrpc: "2.0";
    result: any;
    id: number;
  };
  
  type ErrorResponse = {
    jsonrpc: "2.0";
    error: {
      code: number;
      message: string;
      data: any;
    };
    id: number;
  };
  
  function isErrorResponse(response: Response): response is ErrorResponse;
}

docs

index.md

process-management.md

tile.json