forked from prisma/prisma
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInit.ts
More file actions
770 lines (656 loc) · 23.3 KB
/
Init.ts
File metadata and controls
770 lines (656 loc) · 23.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
import fs from 'node:fs'
import path from 'node:path'
import { confirm, input, select } from '@inquirer/prompts'
import { PrismaConfigInternal } from '@prisma/config'
import { startPrismaDevServer } from '@prisma/dev'
import { ServerState } from '@prisma/dev/internal/state'
import type { ConnectorType } from '@prisma/generator'
import {
arg,
canConnectToDatabase,
checkUnsupportedDataProxy,
Command,
format,
getCommandWithExecutor,
HelpError,
isError,
link,
logger,
PRISMA_POSTGRES_PROVIDER,
protocolToConnectorType,
} from '@prisma/internals'
import type { operations } from '@prisma/management-api-sdk'
import dotenv from 'dotenv'
import { Schema as Shape } from 'effect'
import { bold, dim, green, red, yellow } from 'kleur/colors'
import ora from 'ora'
import { match, P } from 'ts-pattern'
import { FileWriter } from './init/file-writer'
import { printPpgInitOutput, successMessage } from './init/ppg-output'
import { login } from './management-api/auth'
import { createAuthenticatedManagementAPI } from './management-api/auth-client'
import { FileTokenStorage } from './management-api/token-storage'
import { determineClientOutputPath } from './utils/client-output-path'
import { printError } from './utils/prompt/utils/print'
type Region = NonNullable<operations['postV1Projects']['requestBody']>['content']['application/json']['region']
/**
* Indicates if running in Bun runtime.
*/
export const isBun: boolean =
// @ts-ignore
!!globalThis.Bun || !!globalThis.process?.versions?.bun
export const defaultSchema = (props?: {
datasourceProvider?: ConnectorType
generatorProvider?: string
previewFeatures?: string[]
output?: string
withModel?: boolean
}) => {
const {
datasourceProvider = 'postgresql',
generatorProvider = defaultGeneratorProvider,
previewFeatures = defaultPreviewFeatures,
output = '../generated/prisma',
withModel = false,
} = props ?? {}
let schema = `// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Get a free hosted Postgres database in seconds: \`npx create-db\`
generator client {
provider = "${generatorProvider}"
${
previewFeatures.length > 0
? ` previewFeatures = [${previewFeatures.map((feature) => `"${feature}"`).join(', ')}]\n`
: ''
} output = "${output}"
}
datasource db {
provider = "${datasourceProvider}"
}
`
// We add a model to the schema file if the user passed the --with-model flag
if (withModel) {
const defaultAttributes = `email String @unique
name String?`
switch (datasourceProvider) {
case 'mongodb':
schema += `
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
${defaultAttributes}
}
`
break
case 'cockroachdb':
schema += `
model User {
id BigInt @id @default(sequence())
${defaultAttributes}
}
`
break
default:
schema += `
model User {
id Int @id @default(autoincrement())
${defaultAttributes}
}
`
}
}
return schema
}
export const defaultEnv = async (url: string | undefined, debug = false, comments = true) => {
if (url === undefined) {
let created = false
const state =
(await ServerState.fromServerDump({ debug })) ||
((created = true), await ServerState.createExclusively({ debug, persistenceMode: 'stateful' }))
if (created) {
await state.close()
}
const server = await startPrismaDevServer({
databasePort: state.databasePort,
dryRun: true,
name: state.name,
persistenceMode: 'stateful',
port: state.port,
shadowDatabasePort: state.shadowDatabasePort,
debug,
})
url = server.ppg.url
}
let env = comments
? `# Environment variables declared in this file are NOT automatically loaded by Prisma.
# Please add \`import "dotenv/config";\` to your \`prisma.config.ts\` file, or use the Prisma CLI with Bun
# to load environment variables from .env files: https://pris.ly/prisma-config-env-vars.
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
${
url.startsWith('prisma+postgres:') && url.includes('localhost')
? `# The following \`prisma+postgres\` URL is similar to the URL produced by running a local Prisma Postgres
# server with the \`prisma dev\` CLI command, when not choosing any non-default ports or settings. The API key, unlike the
# one found in a remote Prisma Postgres URL, does not contain any sensitive information.\n\n`
: ''
}`
: ''
env += `DATABASE_URL="${url}"`
return env
}
export const defaultPort = (datasourceProvider: ConnectorType) => {
switch (datasourceProvider) {
case 'mysql':
return 3306
case 'sqlserver':
return 1433
case 'mongodb':
return 27017
case 'postgresql':
return 5432
case 'cockroachdb':
return 26257
case PRISMA_POSTGRES_PROVIDER:
return null
}
return undefined
}
export const defaultURL = (
datasourceProvider: ConnectorType,
port = defaultPort(datasourceProvider),
schema = 'public',
) => {
switch (datasourceProvider) {
case 'postgresql':
return `postgresql://johndoe:randompassword@localhost:${port}/mydb?schema=${schema}`
case 'cockroachdb':
return `postgresql://johndoe:randompassword@localhost:${port}/mydb?schema=${schema}`
case 'mysql':
return `mysql://johndoe:randompassword@localhost:${port}/mydb`
case 'sqlserver':
return `sqlserver://localhost:${port};database=mydb;user=SA;password=randompassword;`
case 'mongodb':
return `mongodb+srv://root:randompassword@cluster0.ab1cd.mongodb.net/mydb?retryWrites=true&w=majority`
case 'sqlite':
return 'file:./dev.db'
default:
return undefined
}
}
const defaultGitIgnore = () => {
return `node_modules
# Keep environment variables out of version control
.env
`
}
export const defaultGeneratorProvider = 'prisma-client'
export const defaultPreviewFeatures = []
function normalizePath(configPath: string) {
return JSON.stringify(configPath.replaceAll(path.sep, '/'))
}
type DefaultConfigInput = {
/**
* The path to the `prisma` folder.
*/
prismaFolder: string
/**
* The runtime to use.
* Currently, this is only used to customize the Bun experience.
*/
runtime: 'bun' | 'other'
}
export const defaultConfig = ({ prismaFolder, runtime }: DefaultConfigInput) => {
const schemaPath = path.relative(process.cwd(), path.join(prismaFolder, 'schema.prisma'))
const migrationsPath = path.relative(process.cwd(), path.join(prismaFolder, 'migrations'))
const configSrc = match({ runtime })
.with({ runtime: 'bun' }, () => {
return `\
// This file was generated by Prisma, and assumes you run Prisma commands using \`bun --bun run prisma [command]\`.
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: ${normalizePath(schemaPath)},
migrations: {
path: ${normalizePath(migrationsPath)},
},
datasource: {
url: env("DATABASE_URL"),
},
});
`
})
.otherwise(() => {
return `\
// This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: ${normalizePath(schemaPath)},
migrations: {
path: ${normalizePath(migrationsPath)},
},
datasource: {
url: process.env["DATABASE_URL"],
},
});
`
})
return configSrc
}
export class Init implements Command {
static new(): Init {
return new Init()
}
private static help = format(`
Set up a new Prisma project
${bold('Usage')}
${dim('$')} prisma init [options]
${bold('Options')}
-h, --help Display this help message
--db Provisions a fully managed Prisma Postgres database on the Prisma Data Platform.
--datasource-provider Define the datasource provider to use: postgresql, mysql, sqlite, sqlserver, mongodb or cockroachdb
--generator-provider Define the generator provider to use. Default: \`prisma-client\`
--preview-feature Define a preview feature to use.
--output Define Prisma Client generator output path to use.
--url Define a custom datasource url
${bold('Flags')}
--with-model Add example model to created schema file
${bold('Examples')}
Set up a new \`prisma dev\`-ready (local Prisma Postgres) Prisma project
${dim('$')} prisma init
Set up a new Prisma project and specify MySQL as the datasource provider to use
${dim('$')} prisma init --datasource-provider mysql
Set up a new \`prisma dev\`-ready (local Prisma Postgres) Prisma project and specify \`prisma-client\` as the generator provider to use
${dim('$')} prisma init --generator-provider prisma-client
Set up a new \`prisma dev\`-ready (local Prisma Postgres) Prisma project and specify \`x\` and \`y\` as the preview features to use
${dim('$')} prisma init --preview-feature x --preview-feature y
Set up a new \`prisma dev\`-ready (local Prisma Postgres) Prisma project and specify \`./generated-client\` as the output path to use
${dim('$')} prisma init --output ./generated-client
Set up a new Prisma project and specify the url that will be used
${dim('$')} prisma init --url mysql://user:password@localhost:3306/mydb
Set up a new \`prisma dev\`-ready (local Prisma Postgres) Prisma project with an example model
${dim('$')} prisma init --with-model
`)
async parse(argv: string[], _config: PrismaConfigInternal): Promise<string | Error> {
const args = arg(argv, {
'--help': Boolean,
'-h': '--help',
'--url': String,
'--datasource-provider': String,
'--generator-provider': String,
'--preview-feature': [String],
'--output': String,
'--with-model': Boolean,
'--db': Boolean,
'--region': String,
'--name': String,
'--non-interactive': Boolean,
'--prompt': String,
'--vibe': String,
'--debug': Boolean,
})
if (isError(args) || args['--help']) {
return this.help()
}
const urlArg = args['--url']
if (urlArg) {
checkUnsupportedDataProxy({
cmd: 'init',
validatedConfig: { datasource: { url: urlArg } },
})
}
/**
* Validation
*/
const outputDirName = args._[0]
if (outputDirName) {
throw Error('The init command does not take any argument.')
}
const { datasourceProvider, url } = await match(args)
.with(
{
'--datasource-provider': P.when((datasourceProvider): datasourceProvider is string =>
Boolean(datasourceProvider),
),
},
(input) => {
const datasourceProvider = input['--datasource-provider'].toLowerCase()
assertDatasourceProvider(datasourceProvider)
const url = defaultURL(datasourceProvider)
return { datasourceProvider, url }
},
)
.with(
{
'--url': P.when((url): url is string => Boolean(url)),
},
async (input) => {
const url = input['--url']
const canConnect = await canConnectToDatabase(url)
if (canConnect !== true) {
const { code, message } = canConnect
// P1003 means that the db doesn't exist but we can connect
if (code !== 'P1003') {
if (code) {
throw new Error(`${code}: ${message}`)
} else {
throw new Error(message)
}
}
}
const datasourceProvider = protocolToConnectorType(`${url.split(':')[0]}:`)
return { datasourceProvider, url }
},
)
.otherwise(() => {
return {
datasourceProvider: 'postgresql' as const,
url: undefined,
}
})
const generatorProvider = args['--generator-provider']
const previewFeatures = args['--preview-feature']
const output = args['--output']
const isPpgCommand =
args['--db'] || datasourceProvider === PRISMA_POSTGRES_PROVIDER || args['--prompt'] || args['--vibe']
if (args['--debug']) {
console.log(`[isBun]`, isBun)
}
let prismaPostgresDatabaseUrl: string | undefined
let workspaceId: string | undefined
let projectId: string | undefined
let environmentId: string | undefined
const outputDir = process.cwd()
const prismaFolder = path.join(outputDir, 'prisma')
const writer = new FileWriter(outputDir)
let generatedSchema: string | undefined
let generatedName: string | undefined
if (isPpgCommand) {
const tokenStorage = new FileTokenStorage()
const tokens = await tokenStorage.getTokens()
if (!tokens) {
if (args['--non-interactive']) {
return 'Please authenticate before creating a Prisma Postgres project.'
}
console.log('This will create a project for you on console.prisma.io and requires you to be authenticated.')
const authAnswer = await confirm({
message: 'Would you like to authenticate?',
})
if (!authAnswer) {
return 'Project creation aborted. You need to authenticate to use Prisma Postgres'
}
await login({ utmMedium: 'command-init-db' })
}
if (args['--prompt'] || args['--vibe']) {
const prompt = args['--prompt'] || args['--vibe'] || ''
const spinner = ora(`Generating a Prisma Schema based on your description ${bold(prompt)} ...`).start()
try {
const serverResponseShape = Shape.Struct({
generatedSchema: Shape.String,
generatedName: Shape.String,
})
;({ generatedSchema, generatedName } = Shape.decodeUnknownSync(serverResponseShape)(
await (
await fetch(`https://prisma-generate-server.prisma.workers.dev/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
description: prompt,
}),
})
).json(),
))
} catch (e) {
spinner.fail()
throw e
}
spinner.succeed('Schema is ready')
}
console.log("Let's set up your Prisma Postgres database!")
const managementAPI = createAuthenticatedManagementAPI()
const client = managementAPI.client
const { data: regionsData, error: regionsError } = await client.GET('/v1/regions/postgres')
if (regionsError) {
const errorMessage = regionsError.error?.message
throw new Error(typeof errorMessage === 'string' ? errorMessage : 'Failed to fetch regions')
}
if (!regionsData) {
throw new Error('No regions data returned')
}
const regions = regionsData.data
const ppgRegionSelection =
(args['--region'] as Region) ||
(await select({
message: 'Select your region:',
default: 'us-east-1',
choices: regions.map((region) => ({
name: `${region.id} - ${region.name}`,
value: region.id as Region,
disabled: region.status !== 'available',
})),
loop: true,
}))
const projectDisplayNameAnswer =
args['--name'] ||
(await input({
message: 'Enter a project name:',
default: generatedName || 'My Prisma Project',
}))
const spinner = ora(`Creating project ${bold(projectDisplayNameAnswer)} (this may take a few seconds)...`).start()
try {
const { data: projectData, error: projectError } = await client.POST('/v1/projects', {
body: {
createDatabase: true,
name: projectDisplayNameAnswer,
region: ppgRegionSelection,
},
})
if (projectError) {
const errorMessage = projectError.error?.message
throw new Error(typeof errorMessage === 'string' ? errorMessage : 'Failed to create project')
}
if (!projectData) {
throw new Error('No project data returned')
}
const project = projectData.data
if (!project.database) {
// This should never happen: `database` should only be `null` when
// the request body has `createDatabase: false`.
throw new Error('Missing database info in response')
}
const connection = project.database.connections?.find(
(c) => Boolean(c.endpoints?.direct?.connectionString) || Boolean(c.endpoints?.pooled?.connectionString),
)
const connectionString =
connection?.endpoints?.direct?.connectionString ?? connection?.endpoints?.pooled?.connectionString
if (!connectionString) {
throw new Error('Missing connection string in response')
}
prismaPostgresDatabaseUrl = connectionString
workspaceId = project.workspace.id.replace(/^wksp_/, '')
projectId = project.id.replace(/^proj_/, '')
environmentId = project.database.id.replace(/^db_/, '')
spinner.succeed(successMessage('Your Prisma Postgres database is ready ✅'))
} catch (error) {
spinner.fail(error instanceof Error ? error.message : 'Something went wrong')
throw error
}
}
if (
fs.existsSync(path.join(outputDir, 'schema.prisma')) ||
fs.existsSync(prismaFolder) ||
fs.existsSync(path.join(prismaFolder, 'schema.prisma'))
) {
if (isPpgCommand) {
return printPpgInitOutput({
databaseUrl: prismaPostgresDatabaseUrl!,
workspaceId: workspaceId!,
projectId: projectId!,
environmentId,
isExistingPrismaProject: true,
})
}
}
if (fs.existsSync(path.join(outputDir, 'schema.prisma'))) {
console.log(
printError(`File ${bold('schema.prisma')} already exists in your project.
Please try again in a project that is not yet using Prisma.
`),
)
process.exit(1)
}
if (fs.existsSync(prismaFolder)) {
console.log(
printError(`A folder called ${bold('prisma')} already exists in your project.
Please try again in a project that is not yet using Prisma.
`),
)
process.exit(1)
}
if (fs.existsSync(path.join(prismaFolder, 'schema.prisma'))) {
console.log(
printError(`File ${bold('prisma/schema.prisma')} already exists in your project.
Please try again in a project that is not yet using Prisma.
`),
)
process.exit(1)
}
/**
* Validation successful? Let's create everything!
*/
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir)
}
if (!fs.existsSync(prismaFolder)) {
fs.mkdirSync(prismaFolder)
}
const clientOutput = output ?? determineClientOutputPath(prismaFolder)
writer.write(
path.join(prismaFolder, 'schema.prisma'),
generatedSchema ||
defaultSchema({
datasourceProvider,
generatorProvider,
previewFeatures,
output: clientOutput,
withModel: args['--with-model'],
}),
)
const databaseUrl = prismaPostgresDatabaseUrl || url
const warnings: string[] = []
writer.write(
path.join(outputDir, 'prisma.config.ts'),
defaultConfig({
prismaFolder,
runtime: isBun ? 'bun' : 'other',
}),
)
const envPath = path.join(outputDir, '.env')
if (!fs.existsSync(envPath)) {
writer.write(envPath, await defaultEnv(databaseUrl, args['--debug']))
} else {
const envFile = fs.readFileSync(envPath, { encoding: 'utf8' })
const config = dotenv.parse(envFile) // will return an object
if (Object.keys(config).includes('DATABASE_URL')) {
warnings.push(
`${yellow('warn')} Prisma would have added DATABASE_URL but it already exists in ${bold(
path.relative(outputDir, envPath),
)}.`,
)
} else {
fs.appendFileSync(
envPath,
`\n\n` + '# This was inserted by `prisma init`:\n' + (await defaultEnv(databaseUrl, args['--debug'])),
)
}
}
const gitignorePath = path.join(outputDir, '.gitignore')
try {
writer.write(gitignorePath, defaultGitIgnore(), { flag: 'wx' })
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'EEXIST') {
warnings.push(
`${yellow(
'warn',
)} You already have a ${bold('.gitignore')} file. Don't forget to add ${bold('.env')} in it to not commit any private information.`,
)
} else {
console.error('Failed to write .gitignore file, reason: ', e)
}
}
// Append the generated client to the .gitignore file regardless of whether we created it
// in the previous step.
const clientPathRelativeToOutputDir = path.relative(outputDir, path.resolve(prismaFolder, clientOutput))
try {
fs.appendFileSync(gitignorePath, `\n/${clientPathRelativeToOutputDir.replaceAll(path.sep, '/')}\n`)
} catch (e) {
console.error('Failed to append client path to .gitignore file, reason: ', e)
}
const connectExistingDatabaseSteps = `\
1. Configure your DATABASE_URL in ${green('prisma.config.ts')}
2. Run ${green(getCommandWithExecutor('prisma db pull'))} to introspect your database.`
const postgresProviders: ConnectorType[] = ['postgres', 'postgresql', 'prisma+postgres']
let setupDatabaseSection: string
if (postgresProviders.includes(datasourceProvider)) {
setupDatabaseSection = `\
Next, choose how you want to set up your database:
CONNECT EXISTING DATABASE:
${connectExistingDatabaseSteps}
CREATE NEW DATABASE:
Local: ${green('npx prisma dev')} (runs Postgres locally in your terminal)
Cloud: ${green('npx create-db')} (creates a free Prisma Postgres database)`
} else {
setupDatabaseSection = `\
Next, set up your database:
${connectExistingDatabaseSteps}`
}
const defaultOutput = `
Initialized Prisma in your project
${writer.format({
level: 0,
printHeadersFromLevel: 1,
indentSize: 2,
})}
${warnings.length > 0 && logger.should.warn() ? `\n${warnings.join('\n')}\n` : ''}
${setupDatabaseSection}
Then, define your models in ${green('prisma/schema.prisma')} and run ${green(getCommandWithExecutor('prisma migrate dev'))} to apply your schema.
Learn more: ${link('https://pris.ly/getting-started')}
`
return isPpgCommand
? printPpgInitOutput({
databaseUrl: prismaPostgresDatabaseUrl!,
workspaceId: workspaceId!,
projectId: projectId!,
environmentId,
})
: defaultOutput
}
// help message
public help(error?: string): string | HelpError {
if (error) {
return new HelpError(`\n${bold(red(`!`))} ${error}\n${Init.help}`)
}
return Init.help
}
}
// order matters for the error message.
const DATASOURCE_PROVIDERS = [
'postgresql',
'mysql',
'sqlite',
'sqlserver',
'mongodb',
'cockroachdb',
'prismapostgres',
'prisma+postgres',
] as const
function assertDatasourceProvider(thing: unknown): asserts thing is ConnectorType {
if (typeof thing !== 'string' || !DATASOURCE_PROVIDERS.includes(thing as never)) {
throw new Error(
`Provider "${thing}" is invalid or not supported. Try again with ${DATASOURCE_PROVIDERS.slice(0, -1)
.map((p) => `"${p}"`)
.join(', ')} or "${DATASOURCE_PROVIDERS.at(-1)}".`,
)
}
}