Comprehensive internal utility library for Prisma's CLI operations, schema management, generator handling, and engine interactions
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The CLI utilities domain provides comprehensive command-line interface functionality including argument parsing, schema loading, configuration management, and command framework infrastructure.
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 optionsLoadSchemaContextOptions:
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 argumentsschemaPathFromConfig?: string - Schema path from configurationoptions?: GetSchemaOptions - Loading optionsGetSchemaOptions:
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): voidParameters:
schemaPath: string - Path to the schema fileExample:
printSchemaLoadedMessage('./prisma/schema.prisma')
// Output: "Prisma schema loaded from prisma/schema.prisma"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
): DirectoryConfigParameters:
schemaContext?: SchemaContext | null - Schema contextconfig?: PrismaConfigInternal - Prisma configurationcwd?: 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'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> | ErrorParameters:
argv: string[] - Arguments to parsespec: Arg.Spec - Argument specificationstopAtPositional?: 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): HelpErrorParameters:
helpTemplate: string - Help text templatecmd: string - Unknown command nameReturns: HelpError - Custom error for unknown commands
checkUnsupportedDataProxy(options)Validates that data proxy URLs are not being used with unsupported CLI commands.
function checkUnsupportedDataProxy(options: CheckUnsupportedDataProxyOptions): voidCheckUnsupportedDataProxyOptions:
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): voidCheckUnsupportedSchemaEngineWasmOptions:
interface CheckUnsupportedSchemaEngineWasmOptions {
cmd: string // CLI command name
config: PrismaConfigInternal // Prisma configuration
args: Record<string, unknown> // Command arguments
flags: Array<string> // Flags to check
}format(input?)Formats string by removing indentation and ensuring proper line ending.
function format(input?: string): stringParameters:
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 ErrorParameters:
result: any - Value to checkReturns: boolean - True if result is an Error
getGeneratorSuccessMessage(generator, time)Creates formatted success message for generator completion.
function getGeneratorSuccessMessage(generator: Generator, time: number): stringParameters:
generator: Generator - The generator instancetime: number - Generation time in millisecondsReturns: string - Formatted success message
Example:
const message = getGeneratorSuccessMessage(generator, 1500)
// Returns: "✔ Generated Prisma Client (1.5s)"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(): stringReturns: 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 argumentsschemaPathFromConfig?: string - Schema path from configReturns: Promise<string> - 8-character project hash
SchemaContextComplete 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
}DirectoryConfigDirectory 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
}GeneratorConfigConfiguration 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
}GeneratorOptionsOptions 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
}CommandInterface for CLI command implementations.
interface Command {
parse(argv: string[], config: PrismaConfigInternal): Promise<string | Error>
}CommandsCollection of available commands.
type Commands = { [command: string]: Command }Dictionary<T>Generic dictionary type for key-value collections.
type Dictionary<T> = { [key: string]: T }GeneratorFunctionFunction signature for generator implementations.
type GeneratorFunction = (options: GeneratorOptions) => Promise<string>GeneratorDefinitionDefinition structure for generators.
interface GeneratorDefinition {
prettyName?: string // Display name for generator
generate: GeneratorFunction // Generation function
defaultOutput: string // Default output path
}GeneratorDefinitionWithPackageGenerator definition with package path information.
interface GeneratorDefinitionWithPackage {
definition: GeneratorDefinition // Generator definition
packagePath: string // Package path
}CompiledGeneratorDefinitionCompiled generator ready for execution.
interface CompiledGeneratorDefinition {
prettyName?: string // Display name
output?: string | null // Output path
generate: () => Promise<string> // Compiled generation function
}HelpErrorCustom error class for displaying help without stack traces.
class HelpError extends Error {
constructor(message: string)
}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
}
}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