CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-prisma--internals

Comprehensive internal utility library for Prisma's CLI operations, schema management, generator handling, and engine interactions

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

cli-utilities.mddocs/

CLI Utilities and Command Framework

The CLI utilities domain provides comprehensive command-line interface functionality including argument parsing, schema loading, configuration management, and command framework infrastructure.

Functions

Schema Context and Loading

loadSchemaContext(options?)

Loads and processes schema context from various sources with comprehensive configuration resolution.

function loadSchemaContext(options?: LoadSchemaContextOptions): Promise<SchemaContext>
function loadSchemaContext(options?: LoadSchemaContextOptions & { allowNull: true }): Promise<SchemaContext | null>

Parameters:

  • options?: LoadSchemaContextOptions - Loading configuration options

LoadSchemaContextOptions:

interface LoadSchemaContextOptions {
  cwd?: string                    // Current working directory
  allowNull?: boolean             // Allow null return if schema not found
  schemaPath?: string             // Explicit schema path
  ignoreEnvVarErrors?: boolean    // Ignore environment variable errors
  printLoadMessage?: boolean      // Print schema load message
}

Returns: Promise<SchemaContext> or Promise<SchemaContext | null> if allowNull: true

Example:

// Load with default options
const context = await loadSchemaContext()

// Load with custom configuration
const context = await loadSchemaContext({
  cwd: './my-project',
  schemaPath: './custom-schema.prisma',
  ignoreEnvVarErrors: true
})

// Allow null return if schema not found
const context = await loadSchemaContext({ allowNull: true })
if (context) {
  console.log(`Loaded schema from ${context.schemaRootDir}`)
}

processSchemaResult(options)

Processes a loaded schema result into a fully configured SchemaContext.

function processSchemaResult(options: ProcessSchemaResultOptions): Promise<SchemaContext>

ProcessSchemaResultOptions:

interface ProcessSchemaResultOptions {
  schemaResult: GetSchemaResult     // The loaded schema result
  printLoadMessage?: boolean        // Whether to print load message
  ignoreEnvVarErrors?: boolean      // Whether to ignore environment variable errors  
  cwd?: string                      // Current working directory
}

getSchemaWithPath(schemaPathFromArgs?, schemaPathFromConfig?, options?)

Loads Prisma schema from various sources, throwing error if not found.

function getSchemaWithPath(
  schemaPathFromArgs?: string,
  schemaPathFromConfig?: string, 
  options?: GetSchemaOptions
): Promise<GetSchemaResult>

Parameters:

  • schemaPathFromArgs?: string - Schema path from command arguments
  • schemaPathFromConfig?: string - Schema path from configuration
  • options?: GetSchemaOptions - Loading options

GetSchemaOptions:

interface GetSchemaOptions {
  cwd?: string          // Current working directory
  argumentName?: string // Name of schema argument (default '--schema')
}

getSchemaWithPathOptional(schemaPathFromArgs?, schemaPathFromConfig?, options?)

Loads Prisma schema from various sources, returning null if not found.

function getSchemaWithPathOptional(
  schemaPathFromArgs?: string,
  schemaPathFromConfig?: string,
  options?: GetSchemaOptions
): Promise<GetSchemaResult | null>

Parameters: Same as getSchemaWithPath

Returns: Promise<GetSchemaResult | null> - Loaded schema result or null

printSchemaLoadedMessage(schemaPath)

Prints a formatted message indicating the schema was loaded from a specific path.

function printSchemaLoadedMessage(schemaPath: string): void

Parameters:

  • schemaPath: string - Path to the schema file

Example:

printSchemaLoadedMessage('./prisma/schema.prisma')
// Output: "Prisma schema loaded from prisma/schema.prisma"

Directory Configuration

inferDirectoryConfig(schemaContext?, config?, cwd?)

Infers directory configuration for views, typedSQL, and migrations based on schema context and configuration.

function inferDirectoryConfig(
  schemaContext?: SchemaContext | null,
  config?: PrismaConfigInternal,
  cwd?: string
): DirectoryConfig

Parameters:

  • schemaContext?: SchemaContext | null - Schema context
  • config?: PrismaConfigInternal - Prisma configuration
  • cwd?: string - Current working directory (defaults to process.cwd())

Returns: DirectoryConfig with paths for views, typedSQL, and migrations

Example:

const dirs = inferDirectoryConfig(context, config, './my-project')
console.log(dirs.viewsDirPath)        // e.g., './my-project/prisma/views'
console.log(dirs.typedSqlDirPath)     // e.g., './my-project/prisma/sql'
console.log(dirs.migrationsDirPath)   // e.g., './my-project/prisma/migrations'

Command Framework

arg(argv, spec, stopAtPositional?, permissive?)

Safe wrapper around argument parsing that returns Error instead of throwing.

function arg<T>(
  argv: string[],
  spec: Arg.Spec,
  stopAtPositional?: boolean,
  permissive?: boolean
): Arg.Result<T> | Error

Parameters:

  • argv: string[] - Arguments to parse
  • spec: Arg.Spec - Argument specification
  • stopAtPositional?: boolean - Whether to stop at positional args (default true)
  • permissive?: boolean - Whether to be permissive (default false)

Returns: Arg.Result<T> - Parsed arguments or Error

Example:

const spec = {
  '--schema': String,
  '--help': Boolean,
  '-h': '--help'
}

const result = arg(process.argv.slice(2), spec)
if (isError(result)) {
  console.error('Failed to parse arguments:', result.message)
} else {
  console.log('Schema path:', result['--schema'])
}

unknownCommand(helpTemplate, cmd)

Creates a HelpError for unknown commands.

function unknownCommand(helpTemplate: string, cmd: string): HelpError

Parameters:

  • helpTemplate: string - Help text template
  • cmd: string - Unknown command name

Returns: HelpError - Custom error for unknown commands

Validation Functions

checkUnsupportedDataProxy(options)

Validates that data proxy URLs are not being used with unsupported CLI commands.

function checkUnsupportedDataProxy(options: CheckUnsupportedDataProxyOptions): void

CheckUnsupportedDataProxyOptions:

interface CheckUnsupportedDataProxyOptions {
  cmd: string                           // CLI command name (e.g., "db push")
  schemaContext?: SchemaContext        // Optional schema context
  urls?: (string | undefined)[]        // URLs to validate
}

checkUnsupportedSchemaEngineWasm(options)

Validates that certain flags are not used when an adapter is defined in Prisma config.

function checkUnsupportedSchemaEngineWasm(options: CheckUnsupportedSchemaEngineWasmOptions): void

CheckUnsupportedSchemaEngineWasmOptions:

interface CheckUnsupportedSchemaEngineWasmOptions {
  cmd: string                           // CLI command name
  config: PrismaConfigInternal         // Prisma configuration
  args: Record<string, unknown>        // Command arguments
  flags: Array<string>                 // Flags to check
}

Utility Functions

format(input?)

Formats string by removing indentation and ensuring proper line ending.

function format(input?: string): string

Parameters:

  • input?: string - Input string to format (default '')

Returns: string - Formatted string

Example:

const formatted = format(`
  This is some
    indented text
  that will be formatted
`)
// Returns: "This is some\n  indented text\nthat will be formatted\n"

isError(result)

Type guard to check if result is an Error.

function isError(result: any): result is Error

Parameters:

  • result: any - Value to check

Returns: boolean - True if result is an Error

Generator Success Messages

getGeneratorSuccessMessage(generator, time)

Creates formatted success message for generator completion.

function getGeneratorSuccessMessage(generator: Generator, time: number): string

Parameters:

  • generator: Generator - The generator instance
  • time: number - Generation time in milliseconds

Returns: string - Formatted success message

Example:

const message = getGeneratorSuccessMessage(generator, 1500)
// Returns: "✔ Generated Prisma Client (1.5s)"

Version and Hash Functions

getTypescriptVersion()

Detects and returns the TypeScript version across different runtimes.

function getTypescriptVersion(): Promise<string>

Returns: Promise<string> - TypeScript version or "unknown"

getCLIPathHash()

Creates a unique identifier for the CLI installation path.

function getCLIPathHash(): string

Returns: string - 8-character hash of CLI path

getProjectHash(schemaPathFromArgs?, schemaPathFromConfig?)

Creates a unique identifier for the project by hashing the schema directory.

function getProjectHash(
  schemaPathFromArgs?: string,
  schemaPathFromConfig?: string
): Promise<string>

Parameters:

  • schemaPathFromArgs?: string - Schema path from arguments
  • schemaPathFromConfig?: string - Schema path from config

Returns: Promise<string> - 8-character project hash

Types and Interfaces

Core Types

SchemaContext

Complete schema context with all loaded files and configuration.

interface SchemaContext {
  schemaFiles: LoadedFile[]                    // All loaded schema files
  schemaRootDir: string                       // Root directory of schema files
  primaryDatasourceDirectory: string          // Directory of primary datasource
  loadedFromPathForLogMessages: string        // Path for logging
  primaryDatasource: DataSource | undefined   // Primary datasource
  warnings: string[]                          // Schema parsing warnings
  datasources: DataSource[]                   // All datasources
  generators: GeneratorConfig[]               // All generators
  schemaPath: string                          // @deprecated Schema path
}

DirectoryConfig

Directory paths configuration for Prisma project structure.

interface DirectoryConfig {
  viewsDirPath: string      // Path to views directory
  typedSqlDirPath: string   // Path to typed SQL directory
  migrationsDirPath: string // Path to migrations directory
}

GeneratorConfig

Configuration for a Prisma generator.

interface GeneratorConfig {
  output: string | null              // Generator output path
  name: string                       // Generator name
  provider: string                   // Generator provider
  config: Dictionary<string>         // Generator configuration
  binaryTargets: string[]            // Binary targets
  pinnedBinaryTargets?: string | null // Pinned binary targets
}

GeneratorOptions

Options passed to generator functions during execution.

interface GeneratorOptions {
  generator: GeneratorConfig       // Generator configuration
  otherGenerators: GeneratorConfig[] // Other generators
  cwd: string                      // Current working directory
  dmmf: any                        // Data Model Meta Format
  datasources: any                 // Datasources
  datamodel: string                // Data model string
}

Command System Types

Command

Interface for CLI command implementations.

interface Command {
  parse(argv: string[], config: PrismaConfigInternal): Promise<string | Error>
}

Commands

Collection of available commands.

type Commands = { [command: string]: Command }

Dictionary<T>

Generic dictionary type for key-value collections.

type Dictionary<T> = { [key: string]: T }

Generator System Types

GeneratorFunction

Function signature for generator implementations.

type GeneratorFunction = (options: GeneratorOptions) => Promise<string>

GeneratorDefinition

Definition structure for generators.

interface GeneratorDefinition {
  prettyName?: string           // Display name for generator
  generate: GeneratorFunction   // Generation function
  defaultOutput: string         // Default output path
}

GeneratorDefinitionWithPackage

Generator definition with package path information.

interface GeneratorDefinitionWithPackage {
  definition: GeneratorDefinition // Generator definition
  packagePath: string             // Package path
}

CompiledGeneratorDefinition

Compiled generator ready for execution.

interface CompiledGeneratorDefinition {
  prettyName?: string                    // Display name
  output?: string | null                 // Output path
  generate: () => Promise<string>        // Compiled generation function
}

Error Handling

HelpError

Custom error class for displaying help without stack traces.

class HelpError extends Error {
  constructor(message: string)
}

Examples

Complete Schema Loading Workflow

import { 
  loadSchemaContext, 
  inferDirectoryConfig,
  getSchemaWithPath 
} from '@prisma/internals'

async function setupPrismaProject() {
  try {
    // Load schema context
    const context = await loadSchemaContext({
      cwd: process.cwd(),
      ignoreEnvVarErrors: false,
      printLoadMessage: true
    })
    
    // Get directory configuration
    const directories = inferDirectoryConfig(context)
    
    console.log('Schema loaded successfully:')
    console.log(`- Root: ${context.schemaRootDir}`)
    console.log(`- Views: ${directories.viewsDirPath}`)
    console.log(`- Migrations: ${directories.migrationsDirPath}`)
    console.log(`- Generators: ${context.generators.length}`)
    console.log(`- Datasources: ${context.datasources.length}`)
    
    return context
    
  } catch (error) {
    console.error('Failed to load schema:', error)
    throw error
  }
}

Command-Line Argument Processing

import { arg, isError, format } from '@prisma/internals'

function parseCliArgs() {
  const spec = {
    '--schema': String,
    '--help': Boolean,
    '--verbose': Boolean,
    '-h': '--help',
    '-v': '--verbose'
  }
  
  const result = arg(process.argv.slice(2), spec)
  
  if (isError(result)) {
    const helpText = format(`
      Usage: prisma-tool [options]
      
      Options:
        --schema   Path to schema file
        --help     Show help
        --verbose  Verbose output
    `)
    console.error(helpText)
    process.exit(1)
  }
  
  return result
}

Install with Tessl CLI

npx tessl i tessl/npm-prisma--internals

docs

binary-resolution.md

cli-utilities.md

database-operations.md

engine-commands.md

error-handling.md

generators.md

index.md

syntax-highlighting.md

tracing.md

utilities.md

tile.json