0
# CLI Utilities and Command Framework
1
2
The CLI utilities domain provides comprehensive command-line interface functionality including argument parsing, schema loading, configuration management, and command framework infrastructure.
3
4
## Functions
5
6
### Schema Context and Loading
7
8
#### `loadSchemaContext(options?)`
9
10
Loads and processes schema context from various sources with comprehensive configuration resolution.
11
12
```typescript { .api }
13
function loadSchemaContext(options?: LoadSchemaContextOptions): Promise<SchemaContext>
14
function loadSchemaContext(options?: LoadSchemaContextOptions & { allowNull: true }): Promise<SchemaContext | null>
15
```
16
17
**Parameters:**
18
- `options?: LoadSchemaContextOptions` - Loading configuration options
19
20
**LoadSchemaContextOptions:**
21
```typescript { .api }
22
interface LoadSchemaContextOptions {
23
cwd?: string // Current working directory
24
allowNull?: boolean // Allow null return if schema not found
25
schemaPath?: string // Explicit schema path
26
ignoreEnvVarErrors?: boolean // Ignore environment variable errors
27
printLoadMessage?: boolean // Print schema load message
28
}
29
```
30
31
**Returns:** `Promise<SchemaContext>` or `Promise<SchemaContext | null>` if `allowNull: true`
32
33
**Example:**
34
```typescript
35
// Load with default options
36
const context = await loadSchemaContext()
37
38
// Load with custom configuration
39
const context = await loadSchemaContext({
40
cwd: './my-project',
41
schemaPath: './custom-schema.prisma',
42
ignoreEnvVarErrors: true
43
})
44
45
// Allow null return if schema not found
46
const context = await loadSchemaContext({ allowNull: true })
47
if (context) {
48
console.log(`Loaded schema from ${context.schemaRootDir}`)
49
}
50
```
51
52
#### `processSchemaResult(options)`
53
54
Processes a loaded schema result into a fully configured SchemaContext.
55
56
```typescript { .api }
57
function processSchemaResult(options: ProcessSchemaResultOptions): Promise<SchemaContext>
58
```
59
60
**ProcessSchemaResultOptions:**
61
```typescript { .api }
62
interface ProcessSchemaResultOptions {
63
schemaResult: GetSchemaResult // The loaded schema result
64
printLoadMessage?: boolean // Whether to print load message
65
ignoreEnvVarErrors?: boolean // Whether to ignore environment variable errors
66
cwd?: string // Current working directory
67
}
68
```
69
70
#### `getSchemaWithPath(schemaPathFromArgs?, schemaPathFromConfig?, options?)`
71
72
Loads Prisma schema from various sources, throwing error if not found.
73
74
```typescript { .api }
75
function getSchemaWithPath(
76
schemaPathFromArgs?: string,
77
schemaPathFromConfig?: string,
78
options?: GetSchemaOptions
79
): Promise<GetSchemaResult>
80
```
81
82
**Parameters:**
83
- `schemaPathFromArgs?: string` - Schema path from command arguments
84
- `schemaPathFromConfig?: string` - Schema path from configuration
85
- `options?: GetSchemaOptions` - Loading options
86
87
**GetSchemaOptions:**
88
```typescript { .api }
89
interface GetSchemaOptions {
90
cwd?: string // Current working directory
91
argumentName?: string // Name of schema argument (default '--schema')
92
}
93
```
94
95
#### `getSchemaWithPathOptional(schemaPathFromArgs?, schemaPathFromConfig?, options?)`
96
97
Loads Prisma schema from various sources, returning null if not found.
98
99
```typescript { .api }
100
function getSchemaWithPathOptional(
101
schemaPathFromArgs?: string,
102
schemaPathFromConfig?: string,
103
options?: GetSchemaOptions
104
): Promise<GetSchemaResult | null>
105
```
106
107
**Parameters:** Same as `getSchemaWithPath`
108
109
**Returns:** `Promise<GetSchemaResult | null>` - Loaded schema result or null
110
111
#### `printSchemaLoadedMessage(schemaPath)`
112
113
Prints a formatted message indicating the schema was loaded from a specific path.
114
115
```typescript { .api }
116
function printSchemaLoadedMessage(schemaPath: string): void
117
```
118
119
**Parameters:**
120
- `schemaPath: string` - Path to the schema file
121
122
**Example:**
123
```typescript
124
printSchemaLoadedMessage('./prisma/schema.prisma')
125
// Output: "Prisma schema loaded from prisma/schema.prisma"
126
```
127
128
### Directory Configuration
129
130
#### `inferDirectoryConfig(schemaContext?, config?, cwd?)`
131
132
Infers directory configuration for views, typedSQL, and migrations based on schema context and configuration.
133
134
```typescript { .api }
135
function inferDirectoryConfig(
136
schemaContext?: SchemaContext | null,
137
config?: PrismaConfigInternal,
138
cwd?: string
139
): DirectoryConfig
140
```
141
142
**Parameters:**
143
- `schemaContext?: SchemaContext | null` - Schema context
144
- `config?: PrismaConfigInternal` - Prisma configuration
145
- `cwd?: string` - Current working directory (defaults to process.cwd())
146
147
**Returns:** `DirectoryConfig` with paths for views, typedSQL, and migrations
148
149
**Example:**
150
```typescript
151
const dirs = inferDirectoryConfig(context, config, './my-project')
152
console.log(dirs.viewsDirPath) // e.g., './my-project/prisma/views'
153
console.log(dirs.typedSqlDirPath) // e.g., './my-project/prisma/sql'
154
console.log(dirs.migrationsDirPath) // e.g., './my-project/prisma/migrations'
155
```
156
157
### Command Framework
158
159
#### `arg(argv, spec, stopAtPositional?, permissive?)`
160
161
Safe wrapper around argument parsing that returns Error instead of throwing.
162
163
```typescript { .api }
164
function arg<T>(
165
argv: string[],
166
spec: Arg.Spec,
167
stopAtPositional?: boolean,
168
permissive?: boolean
169
): Arg.Result<T> | Error
170
```
171
172
**Parameters:**
173
- `argv: string[]` - Arguments to parse
174
- `spec: Arg.Spec` - Argument specification
175
- `stopAtPositional?: boolean` - Whether to stop at positional args (default true)
176
- `permissive?: boolean` - Whether to be permissive (default false)
177
178
**Returns:** `Arg.Result<T>` - Parsed arguments or Error
179
180
**Example:**
181
```typescript
182
const spec = {
183
'--schema': String,
184
'--help': Boolean,
185
'-h': '--help'
186
}
187
188
const result = arg(process.argv.slice(2), spec)
189
if (isError(result)) {
190
console.error('Failed to parse arguments:', result.message)
191
} else {
192
console.log('Schema path:', result['--schema'])
193
}
194
```
195
196
#### `unknownCommand(helpTemplate, cmd)`
197
198
Creates a HelpError for unknown commands.
199
200
```typescript { .api }
201
function unknownCommand(helpTemplate: string, cmd: string): HelpError
202
```
203
204
**Parameters:**
205
- `helpTemplate: string` - Help text template
206
- `cmd: string` - Unknown command name
207
208
**Returns:** `HelpError` - Custom error for unknown commands
209
210
### Validation Functions
211
212
#### `checkUnsupportedDataProxy(options)`
213
214
Validates that data proxy URLs are not being used with unsupported CLI commands.
215
216
```typescript { .api }
217
function checkUnsupportedDataProxy(options: CheckUnsupportedDataProxyOptions): void
218
```
219
220
**CheckUnsupportedDataProxyOptions:**
221
```typescript { .api }
222
interface CheckUnsupportedDataProxyOptions {
223
cmd: string // CLI command name (e.g., "db push")
224
schemaContext?: SchemaContext // Optional schema context
225
urls?: (string | undefined)[] // URLs to validate
226
}
227
```
228
229
#### `checkUnsupportedSchemaEngineWasm(options)`
230
231
Validates that certain flags are not used when an adapter is defined in Prisma config.
232
233
```typescript { .api }
234
function checkUnsupportedSchemaEngineWasm(options: CheckUnsupportedSchemaEngineWasmOptions): void
235
```
236
237
**CheckUnsupportedSchemaEngineWasmOptions:**
238
```typescript { .api }
239
interface CheckUnsupportedSchemaEngineWasmOptions {
240
cmd: string // CLI command name
241
config: PrismaConfigInternal // Prisma configuration
242
args: Record<string, unknown> // Command arguments
243
flags: Array<string> // Flags to check
244
}
245
```
246
247
### Utility Functions
248
249
#### `format(input?)`
250
251
Formats string by removing indentation and ensuring proper line ending.
252
253
```typescript { .api }
254
function format(input?: string): string
255
```
256
257
**Parameters:**
258
- `input?: string` - Input string to format (default '')
259
260
**Returns:** `string` - Formatted string
261
262
**Example:**
263
```typescript
264
const formatted = format(`
265
This is some
266
indented text
267
that will be formatted
268
`)
269
// Returns: "This is some\n indented text\nthat will be formatted\n"
270
```
271
272
#### `isError(result)`
273
274
Type guard to check if result is an Error.
275
276
```typescript { .api }
277
function isError(result: any): result is Error
278
```
279
280
**Parameters:**
281
- `result: any` - Value to check
282
283
**Returns:** `boolean` - True if result is an Error
284
285
### Generator Success Messages
286
287
#### `getGeneratorSuccessMessage(generator, time)`
288
289
Creates formatted success message for generator completion.
290
291
```typescript { .api }
292
function getGeneratorSuccessMessage(generator: Generator, time: number): string
293
```
294
295
**Parameters:**
296
- `generator: Generator` - The generator instance
297
- `time: number` - Generation time in milliseconds
298
299
**Returns:** `string` - Formatted success message
300
301
**Example:**
302
```typescript
303
const message = getGeneratorSuccessMessage(generator, 1500)
304
// Returns: "✔ Generated Prisma Client (1.5s)"
305
```
306
307
### Version and Hash Functions
308
309
#### `getTypescriptVersion()`
310
311
Detects and returns the TypeScript version across different runtimes.
312
313
```typescript { .api }
314
function getTypescriptVersion(): Promise<string>
315
```
316
317
**Returns:** `Promise<string>` - TypeScript version or "unknown"
318
319
#### `getCLIPathHash()`
320
321
Creates a unique identifier for the CLI installation path.
322
323
```typescript { .api }
324
function getCLIPathHash(): string
325
```
326
327
**Returns:** `string` - 8-character hash of CLI path
328
329
#### `getProjectHash(schemaPathFromArgs?, schemaPathFromConfig?)`
330
331
Creates a unique identifier for the project by hashing the schema directory.
332
333
```typescript { .api }
334
function getProjectHash(
335
schemaPathFromArgs?: string,
336
schemaPathFromConfig?: string
337
): Promise<string>
338
```
339
340
**Parameters:**
341
- `schemaPathFromArgs?: string` - Schema path from arguments
342
- `schemaPathFromConfig?: string` - Schema path from config
343
344
**Returns:** `Promise<string>` - 8-character project hash
345
346
## Types and Interfaces
347
348
### Core Types
349
350
#### `SchemaContext`
351
352
Complete schema context with all loaded files and configuration.
353
354
```typescript { .api }
355
interface SchemaContext {
356
schemaFiles: LoadedFile[] // All loaded schema files
357
schemaRootDir: string // Root directory of schema files
358
primaryDatasourceDirectory: string // Directory of primary datasource
359
loadedFromPathForLogMessages: string // Path for logging
360
primaryDatasource: DataSource | undefined // Primary datasource
361
warnings: string[] // Schema parsing warnings
362
datasources: DataSource[] // All datasources
363
generators: GeneratorConfig[] // All generators
364
schemaPath: string // @deprecated Schema path
365
}
366
```
367
368
#### `DirectoryConfig`
369
370
Directory paths configuration for Prisma project structure.
371
372
```typescript { .api }
373
interface DirectoryConfig {
374
viewsDirPath: string // Path to views directory
375
typedSqlDirPath: string // Path to typed SQL directory
376
migrationsDirPath: string // Path to migrations directory
377
}
378
```
379
380
#### `GeneratorConfig`
381
382
Configuration for a Prisma generator.
383
384
```typescript { .api }
385
interface GeneratorConfig {
386
output: string | null // Generator output path
387
name: string // Generator name
388
provider: string // Generator provider
389
config: Dictionary<string> // Generator configuration
390
binaryTargets: string[] // Binary targets
391
pinnedBinaryTargets?: string | null // Pinned binary targets
392
}
393
```
394
395
#### `GeneratorOptions`
396
397
Options passed to generator functions during execution.
398
399
```typescript { .api }
400
interface GeneratorOptions {
401
generator: GeneratorConfig // Generator configuration
402
otherGenerators: GeneratorConfig[] // Other generators
403
cwd: string // Current working directory
404
dmmf: any // Data Model Meta Format
405
datasources: any // Datasources
406
datamodel: string // Data model string
407
}
408
```
409
410
### Command System Types
411
412
#### `Command`
413
414
Interface for CLI command implementations.
415
416
```typescript { .api }
417
interface Command {
418
parse(argv: string[], config: PrismaConfigInternal): Promise<string | Error>
419
}
420
```
421
422
#### `Commands`
423
424
Collection of available commands.
425
426
```typescript { .api }
427
type Commands = { [command: string]: Command }
428
```
429
430
#### `Dictionary<T>`
431
432
Generic dictionary type for key-value collections.
433
434
```typescript { .api }
435
type Dictionary<T> = { [key: string]: T }
436
```
437
438
### Generator System Types
439
440
#### `GeneratorFunction`
441
442
Function signature for generator implementations.
443
444
```typescript { .api }
445
type GeneratorFunction = (options: GeneratorOptions) => Promise<string>
446
```
447
448
#### `GeneratorDefinition`
449
450
Definition structure for generators.
451
452
```typescript { .api }
453
interface GeneratorDefinition {
454
prettyName?: string // Display name for generator
455
generate: GeneratorFunction // Generation function
456
defaultOutput: string // Default output path
457
}
458
```
459
460
#### `GeneratorDefinitionWithPackage`
461
462
Generator definition with package path information.
463
464
```typescript { .api }
465
interface GeneratorDefinitionWithPackage {
466
definition: GeneratorDefinition // Generator definition
467
packagePath: string // Package path
468
}
469
```
470
471
#### `CompiledGeneratorDefinition`
472
473
Compiled generator ready for execution.
474
475
```typescript { .api }
476
interface CompiledGeneratorDefinition {
477
prettyName?: string // Display name
478
output?: string | null // Output path
479
generate: () => Promise<string> // Compiled generation function
480
}
481
```
482
483
### Error Handling
484
485
#### `HelpError`
486
487
Custom error class for displaying help without stack traces.
488
489
```typescript { .api }
490
class HelpError extends Error {
491
constructor(message: string)
492
}
493
```
494
495
## Examples
496
497
### Complete Schema Loading Workflow
498
499
```typescript
500
import {
501
loadSchemaContext,
502
inferDirectoryConfig,
503
getSchemaWithPath
504
} from '@prisma/internals'
505
506
async function setupPrismaProject() {
507
try {
508
// Load schema context
509
const context = await loadSchemaContext({
510
cwd: process.cwd(),
511
ignoreEnvVarErrors: false,
512
printLoadMessage: true
513
})
514
515
// Get directory configuration
516
const directories = inferDirectoryConfig(context)
517
518
console.log('Schema loaded successfully:')
519
console.log(`- Root: ${context.schemaRootDir}`)
520
console.log(`- Views: ${directories.viewsDirPath}`)
521
console.log(`- Migrations: ${directories.migrationsDirPath}`)
522
console.log(`- Generators: ${context.generators.length}`)
523
console.log(`- Datasources: ${context.datasources.length}`)
524
525
return context
526
527
} catch (error) {
528
console.error('Failed to load schema:', error)
529
throw error
530
}
531
}
532
```
533
534
### Command-Line Argument Processing
535
536
```typescript
537
import { arg, isError, format } from '@prisma/internals'
538
539
function parseCliArgs() {
540
const spec = {
541
'--schema': String,
542
'--help': Boolean,
543
'--verbose': Boolean,
544
'-h': '--help',
545
'-v': '--verbose'
546
}
547
548
const result = arg(process.argv.slice(2), spec)
549
550
if (isError(result)) {
551
const helpText = format(`
552
Usage: prisma-tool [options]
553
554
Options:
555
--schema Path to schema file
556
--help Show help
557
--verbose Verbose output
558
`)
559
console.error(helpText)
560
process.exit(1)
561
}
562
563
return result
564
}
565
```