0
# File System and Utility Functions
1
2
The utilities domain provides comprehensive cross-platform file system operations, environment handling, formatting utilities, and general-purpose helper functions for the Prisma ecosystem.
3
4
## Environment and Configuration
5
6
### Environment File Loading
7
8
#### `loadEnvFile({ schemaPath, config, printMessage? })`
9
10
Loads environment variables from files next to the schema with comprehensive configuration support.
11
12
```typescript { .api }
13
function loadEnvFile({
14
schemaPath,
15
config,
16
printMessage = false,
17
}: {
18
schemaPath?: string
19
printMessage?: boolean
20
config: PrismaConfigInternal
21
}): Promise<void>
22
```
23
24
**Parameters:**
25
- `schemaPath?: string` - Path to the Prisma schema
26
- `config: PrismaConfigInternal` - Prisma configuration object
27
- `printMessage?: boolean` - Whether to print loading messages
28
29
**Returns:** `Promise<void>` - Loads variables into process.env
30
31
**Example:**
32
```typescript
33
await loadEnvFile({
34
schemaPath: './prisma/schema.prisma',
35
config: loadedConfig,
36
printMessage: true
37
})
38
```
39
40
#### `tryLoadEnvs({ rootEnvPath, schemaEnvPath }, opts?)`
41
42
Attempts to load environment files with comprehensive error handling and conflict detection.
43
44
```typescript { .api }
45
function tryLoadEnvs(
46
{
47
rootEnvPath,
48
schemaEnvPath,
49
}: {
50
rootEnvPath: string | null | undefined
51
schemaEnvPath: string | null | undefined
52
},
53
opts: { conflictCheck: 'warn' | 'error' | 'none' } = {
54
conflictCheck: 'none',
55
}
56
): LoadedEnv
57
```
58
59
**Parameters:**
60
- `rootEnvPath: string | null | undefined` - Path to root .env file
61
- `schemaEnvPath: string | null | undefined` - Path to schema-specific .env file
62
- `opts: { conflictCheck: 'warn' | 'error' | 'none' }` - Conflict handling options
63
64
**Returns:** `LoadedEnv` - Information about loaded environment files
65
66
**LoadedEnv Type:**
67
```typescript { .api }
68
type LoadedEnv =
69
| {
70
message?: string
71
parsed: {
72
[x: string]: string
73
}
74
}
75
| undefined
76
```
77
78
#### `getEnvPaths(schemaPath, options?)`
79
80
Gets paths for environment files relative to schema location.
81
82
```typescript { .api }
83
function getEnvPaths(
84
schemaPath: string,
85
options?: { cwd?: string }
86
): string[]
87
```
88
89
**Parameters:**
90
- `schemaPath: string` - Path to the Prisma schema
91
- `options?: { cwd?: string }` - Current working directory
92
93
**Returns:** `string[]` - Array of potential env file paths
94
95
### Configuration and Directories
96
97
#### `getMigrateConfigDir(schemaPath)`
98
99
Gets the migration configuration directory path based on schema location.
100
101
```typescript { .api }
102
function getMigrateConfigDir(schemaPath: string): string
103
```
104
105
**Parameters:**
106
- `schemaPath: string` - Path to the Prisma schema
107
108
**Returns:** `string` - Path to migrations directory
109
110
#### `extractPreviewFeatures(generators)`
111
112
Extracts preview features from generator configurations.
113
114
```typescript { .api }
115
function extractPreviewFeatures(generators: GeneratorConfig[]): string[]
116
```
117
118
**Parameters:**
119
- `generators: GeneratorConfig[]` - Array of generator configurations
120
121
**Returns:** `string[]` - Array of preview feature names
122
123
## File System Operations
124
125
### Path Utilities
126
127
#### `pathToPosix(path)`
128
129
Converts Windows-style paths to POSIX format for cross-platform compatibility.
130
131
```typescript { .api }
132
function pathToPosix(path: string): string
133
```
134
135
**Parameters:**
136
- `path: string` - Path to convert
137
138
**Returns:** `string` - POSIX-style path
139
140
#### `longestCommonPathPrefix(paths)`
141
142
Finds the longest common path prefix among multiple paths.
143
144
```typescript { .api }
145
function longestCommonPathPrefix(paths: string[]): string
146
```
147
148
**Parameters:**
149
- `paths: string[]` - Array of file paths
150
151
**Returns:** `string` - Longest common prefix
152
153
**Example:**
154
```typescript
155
const paths = [
156
'/home/user/project/src/file1.ts',
157
'/home/user/project/src/file2.ts',
158
'/home/user/project/tests/test1.ts'
159
]
160
const commonPrefix = longestCommonPathPrefix(paths)
161
console.log(commonPrefix) // '/home/user/project/'
162
```
163
164
#### `chmodPlusX(file)`
165
166
Makes a file executable by adding execute permissions (cross-platform).
167
168
```typescript { .api }
169
function chmodPlusX(file: string): void
170
```
171
172
**Parameters:**
173
- `file: string` - Path to the file to make executable
174
175
### File System Namespaces
176
177
#### `fsFunctional`
178
179
Namespace containing functional file system utilities.
180
181
```typescript { .api }
182
namespace fsFunctional {
183
// Functional file system operations
184
function readFile(path: string): Promise<string>
185
function writeFile(path: string, content: string): Promise<void>
186
function exists(path: string): Promise<boolean>
187
// Additional functional utilities...
188
}
189
```
190
191
#### `fsUtils`
192
193
Namespace containing general file system utility functions.
194
195
```typescript { .api }
196
namespace fsUtils {
197
// File system utility functions
198
function ensureDir(path: string): Promise<void>
199
function copyFile(src: string, dest: string): Promise<void>
200
function removeFile(path: string): Promise<void>
201
// Additional utilities...
202
}
203
```
204
205
## Data Processing and Validation
206
207
### Data Structure Utilities
208
209
#### `keyBy<T>(array, getKey)`
210
211
Creates an object from an array using a key extraction function.
212
213
```typescript { .api }
214
function keyBy<T>(
215
array: T[],
216
getKey: (item: T) => string
217
): { [key: string]: T }
218
```
219
220
**Parameters:**
221
- `array: T[]` - Array to process
222
- `getKey: (item: T) => string` - Function to extract keys
223
224
**Returns:** `{ [key: string]: T }` - Object indexed by extracted keys
225
226
**Example:**
227
```typescript
228
const users = [
229
{ id: '1', name: 'Alice' },
230
{ id: '2', name: 'Bob' }
231
]
232
const usersById = keyBy(users, user => user.id)
233
console.log(usersById['1'].name) // 'Alice'
234
```
235
236
#### `pick(obj, keys)`
237
238
Creates a new object with only the specified keys from the source object.
239
240
```typescript { .api }
241
function pick<T, K extends keyof T>(
242
obj: T,
243
keys: K[]
244
): Pick<T, K>
245
```
246
247
**Parameters:**
248
- `obj: T` - Source object
249
- `keys: K[]` - Keys to include in the new object
250
251
**Returns:** `Pick<T, K>` - Object with only specified keys
252
253
#### `mapObjectValues(obj, mapper)`
254
255
Maps object values using a transformation function.
256
257
```typescript { .api }
258
function mapObjectValues<T, U>(
259
obj: { [key: string]: T },
260
mapper: (value: T, key: string) => U
261
): { [key: string]: U }
262
```
263
264
**Parameters:**
265
- `obj: { [key: string]: T }` - Source object
266
- `mapper: (value: T, key: string) => U` - Value transformation function
267
268
**Returns:** `{ [key: string]: U }` - Object with transformed values
269
270
#### `maxBy<T>(array, getValue)`
271
272
Finds the maximum element in an array using a value extraction function.
273
274
```typescript { .api }
275
function maxBy<T>(
276
array: T[],
277
getValue: (item: T) => number
278
): T | undefined
279
```
280
281
**Parameters:**
282
- `array: T[]` - Array to search
283
- `getValue: (item: T) => number` - Function to extract comparison values
284
285
**Returns:** `T | undefined` - Element with maximum value or undefined if array is empty
286
287
#### `maxWithComparator<T>(array, comparator)`
288
289
Finds the maximum element using a custom comparator function.
290
291
```typescript { .api }
292
function maxWithComparator<T>(
293
array: T[],
294
comparator: (a: T, b: T) => number
295
): T | undefined
296
```
297
298
### Validation Functions
299
300
#### `hasOwnProperty(obj, prop)`
301
302
Type-safe Object.hasOwnProperty check with proper typing.
303
304
```typescript { .api }
305
function hasOwnProperty<T>(
306
obj: T,
307
prop: PropertyKey
308
): prop is keyof T
309
```
310
311
**Parameters:**
312
- `obj: T` - Object to check
313
- `prop: PropertyKey` - Property to check for
314
315
**Returns:** `prop is keyof T` - Type guard indicating property existence
316
317
#### `isValidJsIdentifier(name)`
318
319
Validates if a string is a valid JavaScript identifier.
320
321
```typescript { .api }
322
function isValidJsIdentifier(name: string): boolean
323
```
324
325
**Parameters:**
326
- `name: string` - String to validate
327
328
**Returns:** `boolean` - True if valid JavaScript identifier
329
330
#### `isPromiseLike(value)`
331
332
Type guard to check if a value is Promise-like (has `.then` method).
333
334
```typescript { .api }
335
function isPromiseLike(value: any): value is PromiseLike<any>
336
```
337
338
**Parameters:**
339
- `value: any` - Value to check
340
341
**Returns:** `value is PromiseLike<any>` - Type guard for Promise-like objects
342
343
## Environment Detection
344
345
### Runtime Environment
346
347
#### `isCi()`
348
349
Detects if the code is running in a Continuous Integration environment.
350
351
```typescript { .api }
352
function isCi(): boolean
353
```
354
355
**Returns:** `boolean` - True if running in CI
356
357
#### `isInteractive()`
358
359
Detects if the terminal supports interactive input/output.
360
361
```typescript { .api }
362
function isInteractive(): boolean
363
```
364
365
**Returns:** `boolean` - True if terminal is interactive
366
367
#### `canPrompt()`
368
369
Determines if interactive prompts are available and appropriate.
370
371
```typescript { .api }
372
function canPrompt(): boolean
373
```
374
375
**Returns:** `boolean` - True if prompts can be shown
376
377
#### `isInContainer()`
378
379
Detects if the process is running inside a container (Docker, etc.).
380
381
```typescript { .api }
382
function isInContainer(): boolean
383
```
384
385
**Returns:** `boolean` - True if running in a container
386
387
#### `isCurrentBinInstalledGlobally()`
388
389
Checks if the current binary is globally installed.
390
391
```typescript { .api }
392
function isCurrentBinInstalledGlobally(): boolean
393
```
394
395
**Returns:** `boolean` - True if globally installed
396
397
#### `isInNpmLifecycleHook()`
398
399
Detects if the code is running within an npm lifecycle hook.
400
401
```typescript { .api }
402
function isInNpmLifecycleHook(): boolean
403
```
404
405
**Returns:** `boolean` - True if in npm lifecycle hook
406
407
#### `maybeInGitHook()`
408
409
Detects if the code might be running in a Git hook.
410
411
```typescript { .api }
412
function maybeInGitHook(): boolean
413
```
414
415
**Returns:** `boolean` - True if possibly in Git hook
416
417
## Formatting and Display
418
419
### Text Formatting
420
421
#### `formatms(ms)`
422
423
Formats milliseconds into human-readable time duration.
424
425
```typescript { .api }
426
function formatms(ms: number): string
427
```
428
429
**Parameters:**
430
- `ms: number` - Milliseconds to format
431
432
**Returns:** `string` - Formatted duration string
433
434
**Example:**
435
```typescript
436
console.log(formatms(1000)) // '1s'
437
console.log(formatms(60000)) // '1m'
438
console.log(formatms(1500)) // '1.5s'
439
console.log(formatms(90000)) // '1m 30s'
440
```
441
442
#### `formatTable(data)`
443
444
Formats data into a console-friendly table layout.
445
446
```typescript { .api }
447
function formatTable(data: Array<{ [key: string]: any }>): string
448
```
449
450
**Parameters:**
451
- `data: Array<{ [key: string]: any }>` - Array of objects to format as table
452
453
**Returns:** `string` - Formatted table string
454
455
#### `drawBox(options)`
456
457
Draws a decorative text box around content for console output.
458
459
```typescript { .api }
460
function drawBox(options: DrawBoxOptions): string
461
```
462
463
**DrawBoxOptions:**
464
```typescript { .api }
465
interface DrawBoxOptions {
466
content: string // Content to box
467
title?: string // Optional title
468
padding?: number // Internal padding (default: 1)
469
borderStyle?: 'single' | 'double' | 'rounded' // Border style
470
}
471
```
472
473
#### `link(url)`
474
475
Creates a formatted clickable link for console output.
476
477
```typescript { .api }
478
function link(url: string): string
479
```
480
481
**Parameters:**
482
- `url: string` - URL to format
483
484
**Returns:** `string` - Formatted link string
485
486
### Schema and Data Masking
487
488
#### `maskSchema(schema)`
489
490
Masks sensitive information in Prisma schema strings for logging.
491
492
```typescript { .api }
493
function maskSchema(schema: string): string
494
```
495
496
**Parameters:**
497
- `schema: string` - Schema content to mask
498
499
**Returns:** `string` - Schema with sensitive data masked
500
501
**Example:**
502
```typescript
503
const schema = `
504
datasource db {
505
provider = "postgresql"
506
url = "postgresql://user:secret@localhost:5432/db"
507
}
508
`
509
const masked = maskSchema(schema)
510
// Returns schema with URL credentials masked
511
```
512
513
## Library Loading and System Integration
514
515
### Library Loading
516
517
#### `load<T>(id, platformInfo)`
518
519
Wrapper around `require` for loading Node-API libraries with enhanced error handling and platform-specific troubleshooting.
520
521
```typescript { .api }
522
function load<T>(id: string, platformInfo: PlatformInfo): T
523
```
524
525
**Parameters:**
526
- `id: string` - Module identifier to load
527
- `platformInfo: PlatformInfo` - Platform information for error reporting
528
529
**Returns:** `T` - Loaded library/module
530
531
**Throws:** Enhanced error with platform-specific troubleshooting information
532
533
**Example:**
534
```typescript
535
import { load } from '@prisma/internals'
536
import { getPlatform } from '@prisma/get-platform'
537
538
try {
539
const platformInfo = await getPlatform()
540
const queryEngine = load<QueryEngine>('@prisma/query-engine', platformInfo)
541
console.log('Query engine loaded successfully')
542
} catch (error) {
543
console.error('Failed to load query engine:', error.message)
544
// Error includes platform-specific troubleshooting steps
545
}
546
```
547
548
### Cloudflare D1 Integration
549
550
#### `locateLocalCloudflareD1(options)`
551
552
Locates local Cloudflare D1 SQLite database files created by Wrangler for development.
553
554
```typescript { .api }
555
function locateLocalCloudflareD1(options: {
556
arg: '--to-local-d1' | '--from-local-d1'
557
}): Promise<string>
558
```
559
560
**Parameters:**
561
- `options.arg: '--to-local-d1' | '--from-local-d1'` - Command flag determining operation direction
562
563
**Returns:** `Promise<string>` - Path to the local D1 database file
564
565
**Throws:**
566
- Error if no D1 databases found in `.wrangler/state/v3/d1/miniflare-D1DatabaseObject/`
567
- Error if multiple D1 databases found (requires manual specification)
568
569
**Example:**
570
```typescript
571
import { locateLocalCloudflareD1 } from '@prisma/internals'
572
573
try {
574
const d1Path = await locateLocalCloudflareD1({
575
arg: '--to-local-d1'
576
})
577
console.log('Found local D1 database:', d1Path)
578
// Use file:// URL format: `file:${d1Path}`
579
} catch (error) {
580
if (error.message.includes('No Cloudflare D1 databases found')) {
581
console.log('Run `wrangler d1 create <DATABASE_NAME>` and `wrangler dev` first')
582
} else if (error.message.includes('Multiple Cloudflare D1 databases found')) {
583
console.log('Use --to-url or --from-url with explicit file path instead')
584
}
585
}
586
```
587
588
**Directory Structure:**
589
```
590
.wrangler/
591
state/
592
v3/
593
d1/
594
miniflare-D1DatabaseObject/
595
<uuid1>.sqlite ← Located by this function
596
<uuid2>.sqlite ← Multiple files cause error
597
```
598
599
## Command Execution and System
600
601
### Command Utilities
602
603
#### `getCommandWithExecutor(command)`
604
605
Gets command with appropriate executor (npx, yarn, pnpm, etc.) based on project setup.
606
607
```typescript { .api }
608
function getCommandWithExecutor(command: string): string
609
```
610
611
**Parameters:**
612
- `command: string` - Base command to execute
613
614
**Returns:** `string` - Command prefixed with appropriate executor
615
616
**Example:**
617
```typescript
618
const cmd = getCommandWithExecutor('prisma generate')
619
console.log(cmd) // 'npx prisma generate' or 'yarn prisma generate'
620
```
621
622
#### `callOnceOnSuccess<T>(fn)`
623
624
Ensures a function is called only once on successful execution.
625
626
```typescript { .api }
627
function callOnceOnSuccess<T>(fn: () => T): () => T
628
```
629
630
**Parameters:**
631
- `fn: () => T` - Function to wrap
632
633
**Returns:** `() => T` - Wrapped function that executes only once successfully
634
635
## Platform and Version Detection
636
637
### Platform Utilities
638
639
#### `parseAWSNodejsRuntimeEnvVarVersion(version)`
640
641
Parses AWS Lambda Node.js runtime version from environment variables.
642
643
```typescript { .api }
644
function parseAWSNodejsRuntimeEnvVarVersion(version: string): string | null
645
```
646
647
**Parameters:**
648
- `version: string` - AWS runtime version string
649
650
**Returns:** `string | null` - Parsed Node.js version or null
651
652
### URL and Connection Utilities
653
654
#### `serializeQueryEngineName(name)`
655
656
Serializes query engine name for consistent identification.
657
658
```typescript { .api }
659
function serializeQueryEngineName(name: string): string
660
```
661
662
**Parameters:**
663
- `name: string` - Query engine name
664
665
**Returns:** `string` - Serialized name
666
667
### Prisma Postgres Utilities
668
669
#### `isPrismaPostgres(url)`
670
671
Detects if a URL is for Prisma Postgres service.
672
673
```typescript { .api }
674
function isPrismaPostgres(url: string): boolean
675
```
676
677
#### `isPrismaPostgresDev(url)`
678
679
Detects if a URL is for Prisma Postgres development environment.
680
681
```typescript { .api }
682
function isPrismaPostgresDev(url: string): boolean
683
```
684
685
### Constants
686
687
#### `PRISMA_POSTGRES_PROTOCOL`
688
689
Protocol constant for Prisma Postgres connections.
690
691
```typescript { .api }
692
const PRISMA_POSTGRES_PROTOCOL: string
693
```
694
695
#### `PRISMA_POSTGRES_PROVIDER`
696
697
Provider constant for Prisma Postgres.
698
699
```typescript { .api }
700
const PRISMA_POSTGRES_PROVIDER: string
701
```
702
703
## Logging and Output
704
705
### Logger Namespace
706
707
#### `logger`
708
709
Comprehensive logging namespace providing structured logging with color-coded output and environment-aware controls.
710
711
```typescript { .api }
712
namespace logger {
713
// Core logging functions
714
function log(...data: any[]): void
715
function info(message: any, ...optionalParams: any[]): void
716
function warn(message: any, ...optionalParams: any[]): void
717
function error(message: any, ...optionalParams: any[]): void
718
function query(message: any, ...optionalParams: any[]): void
719
720
// Configuration
721
const tags: {
722
error: string // red('prisma:error')
723
warn: string // yellow('prisma:warn')
724
info: string // cyan('prisma:info')
725
query: string // blue('prisma:query')
726
}
727
728
const should: {
729
warn(): boolean // Returns !process.env.PRISMA_DISABLE_WARNINGS
730
}
731
}
732
```
733
734
#### `logger.log(...data)`
735
736
Direct console.log wrapper for general output.
737
738
```typescript { .api }
739
function log(...data: any[]): void
740
```
741
742
**Parameters:**
743
- `...data: any[]` - Data to log
744
745
**Example:**
746
```typescript
747
import { logger } from '@prisma/internals'
748
749
logger.log('Starting Prisma operation...')
750
logger.log('User:', { id: 1, name: 'Alice' })
751
```
752
753
#### `logger.info(message, ...optionalParams)`
754
755
Logs informational messages with cyan-colored `prisma:info` tag.
756
757
```typescript { .api }
758
function info(message: any, ...optionalParams: any[]): void
759
```
760
761
**Parameters:**
762
- `message: any` - Primary message
763
- `...optionalParams: any[]` - Additional parameters
764
765
**Example:**
766
```typescript
767
logger.info('Database connected successfully')
768
logger.info('Found models:', modelNames)
769
```
770
771
#### `logger.warn(message, ...optionalParams)`
772
773
Logs warning messages with yellow-colored `prisma:warn` tag. Respects `PRISMA_DISABLE_WARNINGS` environment variable.
774
775
```typescript { .api }
776
function warn(message: any, ...optionalParams: any[]): void
777
```
778
779
**Parameters:**
780
- `message: any` - Warning message
781
- `...optionalParams: any[]` - Additional parameters
782
783
**Environment Control:**
784
- Set `PRISMA_DISABLE_WARNINGS=1` to suppress warnings
785
786
**Example:**
787
```typescript
788
logger.warn('Deprecated feature usage detected')
789
logger.warn('Migration will affect', affectedTables.length, 'tables')
790
```
791
792
#### `logger.error(message, ...optionalParams)`
793
794
Logs error messages with red-colored `prisma:error` tag.
795
796
```typescript { .api }
797
function error(message: any, ...optionalParams: any[]): void
798
```
799
800
**Parameters:**
801
- `message: any` - Error message
802
- `...optionalParams: any[]` - Additional parameters
803
804
**Example:**
805
```typescript
806
logger.error('Connection failed:', error.message)
807
logger.error('Invalid schema format at line', lineNumber)
808
```
809
810
#### `logger.query(message, ...optionalParams)`
811
812
Logs database query information with blue-colored `prisma:query` tag.
813
814
```typescript { .api }
815
function query(message: any, ...optionalParams: any[]): void
816
```
817
818
**Parameters:**
819
- `message: any` - Query information
820
- `...optionalParams: any[]` - Additional parameters
821
822
**Example:**
823
```typescript
824
logger.query('SELECT * FROM users WHERE id = $1', [userId])
825
logger.query('Migration completed in', duration, 'ms')
826
```
827
828
#### `logger.tags`
829
830
Color-coded tag constants for consistent logging format.
831
832
```typescript { .api }
833
const tags: {
834
error: string // red('prisma:error')
835
warn: string // yellow('prisma:warn')
836
info: string // cyan('prisma:info')
837
query: string // blue('prisma:query')
838
}
839
```
840
841
#### `logger.should`
842
843
Environment-aware logging controls.
844
845
```typescript { .api }
846
const should: {
847
warn(): boolean // Returns !process.env.PRISMA_DISABLE_WARNINGS
848
}
849
```
850
851
**Example Usage:**
852
```typescript
853
import { logger } from '@prisma/internals'
854
855
// Complete logging example
856
async function runMigration() {
857
logger.info('Starting migration process')
858
859
try {
860
if (logger.should.warn() && hasWarnings) {
861
logger.warn('Migration contains potential data loss operations')
862
}
863
864
logger.query('BEGIN TRANSACTION')
865
await runMigrationSteps()
866
logger.query('COMMIT TRANSACTION')
867
868
logger.info('Migration completed successfully')
869
} catch (error) {
870
logger.query('ROLLBACK TRANSACTION')
871
logger.error('Migration failed:', error.message)
872
throw error
873
}
874
}
875
876
// Environment control
877
process.env.PRISMA_DISABLE_WARNINGS = '1'
878
logger.warn('This warning will not be shown')
879
```
880
881
## Error Handling and Logging
882
883
### Error Utilities
884
885
#### `handleLibraryLoadingErrors(error)`
886
887
Handles errors that occur when loading engine libraries with helpful messaging.
888
889
```typescript { .api }
890
function handleLibraryLoadingErrors(error: Error): never
891
```
892
893
**Parameters:**
894
- `error: Error` - Library loading error
895
896
**Throws:** Enhanced error with helpful troubleshooting information
897
898
#### `handlePanic(error)`
899
900
Handles panic errors with appropriate user-friendly messaging.
901
902
```typescript { .api }
903
function handlePanic(error: Error): never
904
```
905
906
**Parameters:**
907
- `error: Error` - Panic error to handle
908
909
**Throws:** User-friendly panic error
910
911
#### `printConfigWarnings(warnings)`
912
913
Prints configuration warnings to the console with proper formatting.
914
915
```typescript { .api }
916
function printConfigWarnings(warnings: string[]): void
917
```
918
919
**Parameters:**
920
- `warnings: string[]` - Array of warning messages
921
922
### Utility Functions
923
924
#### `setClassName(obj, className)`
925
926
Sets the class name property for error objects and debugging.
927
928
```typescript { .api }
929
function setClassName(obj: any, className: string): void
930
```
931
932
**Parameters:**
933
- `obj: any` - Object to set class name on
934
- `className: string` - Class name to set
935
936
#### `missingGeneratorMessage(provider?)`
937
938
Creates an informative message about missing generators.
939
940
```typescript { .api }
941
function missingGeneratorMessage(provider?: string): string
942
```
943
944
**Parameters:**
945
- `provider?: string` - Optional generator provider name
946
947
**Returns:** `string` - Formatted missing generator message
948
949
## Parsing and Conversion
950
951
### Environment Value Parsing
952
953
#### `parseEnvValue(value)`
954
955
Parses environment variable values with proper type conversion.
956
957
```typescript { .api }
958
function parseEnvValue(value: string): EnvValue
959
```
960
961
**Parameters:**
962
- `value: string` - Environment variable value
963
964
**Returns:** `EnvValue` - Parsed environment value object
965
966
#### `parseBinaryTargetsEnvValue(value)`
967
968
Parses binary targets from environment variable values.
969
970
```typescript { .api }
971
function parseBinaryTargetsEnvValue(value: string): BinaryTargetsEnvValue[]
972
```
973
974
**Parameters:**
975
- `value: string` - Environment variable containing binary targets
976
977
**Returns:** `BinaryTargetsEnvValue[]` - Parsed binary targets array
978
979
### Schema Processing
980
981
#### `extractSchemaContent(input)`
982
983
Extracts schema content from various input formats.
984
985
```typescript { .api }
986
function extractSchemaContent(input: SchemaFileInput): string
987
```
988
989
**Parameters:**
990
- `input: SchemaFileInput` - Schema input (string or multiple files)
991
992
**Returns:** `string` - Extracted schema content
993
994
#### `toSchemasContainer(schemas)`
995
996
Converts schemas to internal container format.
997
998
```typescript { .api }
999
function toSchemasContainer(schemas: MultipleSchemas): SchemasContainer
1000
```
1001
1002
#### `toSchemasWithConfigDir(schemas, configDir)`
1003
1004
Converts schemas to container format with configuration directory.
1005
1006
```typescript { .api }
1007
function toSchemasWithConfigDir(
1008
schemas: MultipleSchemas,
1009
configDir: string
1010
): SchemasContainer
1011
```
1012
1013
## Constants and Regex
1014
1015
### Version Information
1016
1017
#### `version`
1018
1019
Package version from package.json.
1020
1021
```typescript { .api }
1022
const version: string
1023
```
1024
1025
### Regular Expressions
1026
1027
#### `binaryTargetRegex`
1028
1029
Regular expression for validating binary target formats.
1030
1031
```typescript { .api }
1032
const binaryTargetRegex: RegExp
1033
```
1034
1035
#### `vercelPkgPathRegex`
1036
1037
Regular expression for detecting Vercel package paths.
1038
1039
```typescript { .api }
1040
const vercelPkgPathRegex: RegExp
1041
```
1042
1043
## Stream Processing
1044
1045
### Line Processing
1046
1047
#### `byline`
1048
1049
Default export providing line-by-line stream reading utility.
1050
1051
```typescript { .api }
1052
const byline: {
1053
createStream(): NodeJS.ReadWriteStream
1054
// Additional stream processing methods
1055
}
1056
```
1057
1058
## Examples
1059
1060
### Complete Environment Setup
1061
1062
```typescript
1063
import {
1064
tryLoadEnvs,
1065
getEnvPaths,
1066
isCi,
1067
isInteractive,
1068
canPrompt,
1069
formatms
1070
} from '@prisma/internals'
1071
1072
async function setupEnvironment(schemaPath: string) {
1073
const startTime = Date.now()
1074
1075
// Detect environment
1076
console.log('Environment Detection:')
1077
console.log(`CI: ${isCi()}`)
1078
console.log(`Interactive: ${isInteractive()}`)
1079
console.log(`Can Prompt: ${canPrompt()}`)
1080
1081
// Load environment files
1082
console.log('\nLoading environment files...')
1083
const envPaths = getEnvPaths(schemaPath)
1084
console.log('Potential env paths:', envPaths)
1085
1086
const loadedEnv = await tryLoadEnvs(schemaPath, {
1087
printMessage: true
1088
})
1089
1090
console.log('Environment loading result:', loadedEnv.message)
1091
console.log('Loaded from:', loadedEnv.paths)
1092
1093
const setupTime = Date.now() - startTime
1094
console.log(`Environment setup completed in ${formatms(setupTime)}`)
1095
1096
return loadedEnv
1097
}
1098
```
1099
1100
### Data Processing Pipeline
1101
1102
```typescript
1103
import {
1104
keyBy,
1105
pick,
1106
mapObjectValues,
1107
maxBy,
1108
hasOwnProperty,
1109
isValidJsIdentifier
1110
} from '@prisma/internals'
1111
1112
interface Model {
1113
name: string
1114
fields: Array<{ name: string; type: string; isOptional: boolean }>
1115
createdAt: Date
1116
}
1117
1118
function processModels(models: Model[]) {
1119
// Index models by name
1120
const modelsByName = keyBy(models, model => model.name)
1121
1122
// Get basic model info
1123
const modelSummaries = models.map(model =>
1124
pick(model, ['name', 'createdAt'])
1125
)
1126
1127
// Transform field types
1128
const modelsWithTransformedFields = mapObjectValues(
1129
modelsByName,
1130
model => ({
1131
...model,
1132
fields: model.fields.map(field => ({
1133
...field,
1134
isValidIdentifier: isValidJsIdentifier(field.name)
1135
}))
1136
})
1137
)
1138
1139
// Find most recent model
1140
const newestModel = maxBy(models, model => model.createdAt.getTime())
1141
1142
// Validate model names
1143
for (const model of models) {
1144
if (!hasOwnProperty(modelsByName, model.name)) {
1145
console.warn(`Model ${model.name} not found in index`)
1146
}
1147
}
1148
1149
return {
1150
byName: modelsWithTransformedFields,
1151
summaries: modelSummaries,
1152
newest: newestModel
1153
}
1154
}
1155
```
1156
1157
### File System Operations
1158
1159
```typescript
1160
import {
1161
chmodPlusX,
1162
pathToPosix,
1163
longestCommonPathPrefix,
1164
fsFunctional,
1165
fsUtils
1166
} from '@prisma/internals'
1167
1168
async function setupProjectFiles(projectPath: string) {
1169
// Convert to POSIX paths for cross-platform compatibility
1170
const posixPath = pathToPosix(projectPath)
1171
1172
// Generate script paths
1173
const scriptPaths = [
1174
`${posixPath}/scripts/generate.sh`,
1175
`${posixPath}/scripts/migrate.sh`,
1176
`${posixPath}/scripts/deploy.sh`
1177
]
1178
1179
// Find common directory
1180
const commonPrefix = longestCommonPathPrefix(scriptPaths)
1181
console.log('Scripts directory:', commonPrefix)
1182
1183
// Ensure directory exists
1184
await fsUtils.ensureDir(commonPrefix)
1185
1186
// Create and make scripts executable
1187
for (const scriptPath of scriptPaths) {
1188
const scriptName = scriptPath.split('/').pop()
1189
const scriptContent = `#!/bin/bash\necho "Running ${scriptName}..."`
1190
1191
await fsFunctional.writeFile(scriptPath, scriptContent)
1192
chmodPlusX(scriptPath)
1193
1194
console.log(`Created executable script: ${scriptPath}`)
1195
}
1196
}
1197
```