@prisma/cli-init 0.0.0-dev.202505142350 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1487 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/platform/_lib/utils.ts
8
- import internals2 from "@prisma/internals";
9
- import { bold, green } from "kleur/colors";
10
-
11
- // src/platform/_lib/cli/parameters.ts
12
- import internals from "@prisma/internals";
13
- var getRequiredParameter = (args, names, environmentVariable) => {
14
- const value = getOptionalParameter(args, names, environmentVariable);
15
- if (value === void 0)
16
- return new Error(`Missing ${names.join(" or ")} parameter`);
17
- return value;
18
- };
19
- function argOrThrow(argv, spec) {
20
- const args = internals.arg(argv, spec);
21
- if (internals.isError(args))
22
- throw args;
23
- return args;
24
- }
25
- var getRequiredParameterOrThrow = (args, names, environmentVariable) => {
26
- const value = getRequiredParameter(args, names, environmentVariable);
27
- if (value instanceof Error)
28
- throw new Error(`Missing ${names.join(" or ")} parameter`);
29
- return value;
30
- };
31
- var getOptionalParameter = (args, names, environmentVariable) => {
32
- const entry = Object.entries(args).find(([key]) => names.includes(key));
33
- if (!entry) {
34
- if (environmentVariable) {
35
- const value = process.env[environmentVariable];
36
- if (value) {
37
- return value;
38
- }
39
- }
40
- }
41
- return entry?.[1] ?? void 0;
42
- };
43
-
44
- // src/platform/_lib/credentials.ts
45
- import fs2 from "fs-extra";
46
- import path from "path";
47
- import XdgAppPaths from "xdg-app-paths";
48
-
49
- // src/platform/_lib/jsonFile.ts
50
- import fs from "fs-extra";
51
- var parse = (buffer, { beforeParse, reviver } = {}) => {
52
- let data = new TextDecoder().decode(buffer);
53
- if (typeof beforeParse === "function") {
54
- data = beforeParse(data);
55
- }
56
- return JSON.parse(data, reviver);
57
- };
58
- var loadJsonFile = async (filePath, options) => {
59
- const buffer = await fs.readFile(filePath);
60
- return parse(buffer, options);
61
- };
62
-
63
- // src/platform/_lib/prelude.ts
64
- var unknownToError = (unknown) => {
65
- if (unknown instanceof Error)
66
- return unknown;
67
- return new Error(`Unknown error: ${unknown}`);
68
- };
69
- var id = (value) => value;
70
- var isObject = (obj) => {
71
- return obj !== null && typeof obj === "object" && !Array.isArray(obj);
72
- };
73
- var tryCatch = (fn, catcher) => {
74
- try {
75
- return fn();
76
- } catch (e) {
77
- return catcher ? catcher(unknownToError(e)) : unknownToError(e);
78
- }
79
- };
80
-
81
- // src/platform/_lib/credentials.ts
82
- var credentialsFileDirectoryPath = new XdgAppPaths("prisma-platform-cli").config();
83
- var credentialsFilePath = path.join(credentialsFileDirectoryPath, "auth.json");
84
- var parseCredentials = (data) => {
85
- if (typeof data !== "object" || data === null)
86
- throw new Error("Invalid credentials");
87
- if (!("token" in data) || typeof data["token"] !== "string")
88
- throw new Error("Invalid credentials");
89
- return data;
90
- };
91
- var credentialsFile = {
92
- path: credentialsFilePath,
93
- save: async (data) => fs2.mkdirp(credentialsFileDirectoryPath).then(() => fs2.writeJSON(credentialsFilePath, data)).catch(unknownToError),
94
- load: async () => fs2.pathExists(credentialsFilePath).then((exists) => exists ? loadJsonFile(credentialsFilePath).then(parseCredentials) : null).catch(unknownToError),
95
- delete: async () => fs2.pathExists(credentialsFilePath).then((exists) => exists ? fs2.remove(credentialsFilePath) : void 0).then(() => null).catch(unknownToError)
96
- };
97
-
98
- // src/platform/_lib/utils.ts
99
- var platformParameters = {
100
- global: {
101
- // TODO Remove this from global once we have a way for parents to strip out flags upon parsing.
102
- "--token": String,
103
- "--json": Boolean
104
- },
105
- workspace: {
106
- "--token": String,
107
- "--workspace": String,
108
- "--json": Boolean,
109
- "-w": "--workspace"
110
- },
111
- project: {
112
- "--token": String,
113
- "--project": String,
114
- "-p": "--project"
115
- },
116
- environment: {
117
- "--token": String,
118
- "--environment": String,
119
- "-e": "--environment"
120
- },
121
- serviceToken: {
122
- "--token": String,
123
- "--serviceToken": String,
124
- "-s": "--serviceToken"
125
- },
126
- apikey: {
127
- "--token": String,
128
- "--apikey": String
129
- }
130
- };
131
- var ErrorPlatformUnauthorized = new Error(
132
- `No platform credentials found. Run ${green(internals2.getCommandWithExecutor("prisma platform auth login --early-access"))} first. Alternatively you can provide a token via the \`--token\` or \`-t\` parameters, or set the 'PRISMA_TOKEN' environment variable with a token.`
133
- // prettier-ignore
134
- );
135
- var getTokenOrThrow = async (args) => {
136
- const token = getOptionalParameter(args, ["--token", "-t"], "PRISMA_TOKEN");
137
- if (token)
138
- return token;
139
- const credentials = await credentialsFile.load();
140
- if (internals2.isError(credentials))
141
- throw credentials;
142
- if (!credentials)
143
- throw ErrorPlatformUnauthorized;
144
- return credentials.token;
145
- };
146
- var accelerateConnectionStringUrl = "prisma://accelerate.prisma-data.net";
147
- var generateConnectionString = (apiKey) => {
148
- const url = new URL(accelerateConnectionStringUrl);
149
- url.searchParams.set("api_key", apiKey);
150
- return bold(url.href);
151
- };
152
- var poll = async (fn, until, waitMs, timeoutMs, message) => {
153
- const endTime = (/* @__PURE__ */ new Date()).getMilliseconds() + timeoutMs;
154
- const wait = () => new Promise((resolve) => {
155
- setTimeout(resolve, waitMs);
156
- });
157
- let result = await fn();
158
- while (!until(result)) {
159
- const waitTime = (/* @__PURE__ */ new Date()).getMilliseconds() + waitMs;
160
- if (waitTime > endTime) {
161
- throw new Error(`polling timed out after ${timeoutMs}ms`);
162
- }
163
- if (message)
164
- console.log(message);
165
- result = await wait().then(fn);
166
- }
167
- if (internals2.isError(result))
168
- throw result;
169
- return result;
170
- };
171
- var printPpgInitOutput = ({
172
- databaseUrl,
173
- workspaceId,
174
- projectId,
175
- environmentId,
176
- isExistingPrismaProject = false
177
- }) => {
178
- const newPrismaProjectOutput = `
179
- We created an initial ${green("schema.prisma")} file and a ${green(".env")} file with your ${green(
180
- "DATABASE_URL"
181
- )} environment variable already set.
182
-
183
- ${bold("--- Next steps ---")}
184
-
185
- Go to ${internals2.link("https://pris.ly/ppg-init")} for detailed instructions.
186
-
187
- ${bold("1. Define your database schema")}
188
- Open the ${green("schema.prisma")} file and define your first models. Check the docs if you need inspiration: ${internals2.link(
189
- "https://pris.ly/ppg-init"
190
- )}.
191
-
192
- ${bold("2. Apply migrations")}
193
- Run the following command to create and apply a migration:
194
- ${green("npx prisma migrate dev --name init")}
195
-
196
- ${bold(`3. Manage your data`)}
197
- View and edit your data locally by running this command:
198
- ${green("npx prisma studio")}
199
-
200
- ...or online in Console:
201
- ${internals2.link(`https://console.prisma.io/${workspaceId}/${projectId}/${environmentId}/studio`)}
202
-
203
- ${bold(`4. Send queries from your app`)}
204
- To access your database from a JavaScript/TypeScript app, you need to use Prisma ORM. Go here for step-by-step instructions: ${internals2.link(
205
- "https://pris.ly/ppg-init"
206
- )}
207
- `;
208
- const existingPrismaProjectOutput = `
209
- We found an existing ${green("schema.prisma")} file in your current project directory.
210
-
211
- ${bold("--- Database URL ---")}
212
-
213
- Connect Prisma ORM to your Prisma Postgres database with this URL:
214
-
215
- ${green(databaseUrl)}
216
-
217
- ${bold("--- Next steps ---")}
218
-
219
- Go to ${internals2.link("https://pris.ly/ppg-init")} for detailed instructions.
220
-
221
- ${bold("1. Install and use the Prisma Accelerate extension")}
222
- Prisma Postgres requires the Prisma Accelerate extension for querying. If you haven't already installed it, install it in your project:
223
- ${green("npm install @prisma/extension-accelerate")}
224
-
225
- ...and add it to your Prisma Client instance:
226
- ${green('import { withAccelerate } from "@prisma/extension-accelerate"')}
227
-
228
- ${green("const prisma = new PrismaClient().$extends(withAccelerate())")}
229
-
230
- ${bold("2. Apply migrations")}
231
- Run the following command to create and apply a migration:
232
- ${green("npx prisma migrate dev")}
233
-
234
- ${bold(`3. Manage your data`)}
235
- View and edit your data locally by running this command:
236
- ${green("npx prisma studio")}
237
-
238
- ...or online in Console:
239
- ${internals2.link(`https://console.prisma.io/${workspaceId}/${projectId}/${environmentId}/studio`)}
240
-
241
- ${bold(`4. Send queries from your app`)}
242
- If you already have an existing app with Prisma ORM, you can now run it and it will send queries against your newly created Prisma Postgres instance.
243
-
244
- ${bold(`5. Learn more`)}
245
- For more info, visit the Prisma Postgres docs: ${internals2.link("https://pris.ly/ppg-docs")}
246
- `;
247
- return isExistingPrismaProject ? existingPrismaProjectOutput : newPrismaProjectOutput;
248
- };
249
-
250
- // src/platform/accelerate/_.ts
251
- var __exports = {};
252
- __export(__exports, {
253
- $: () => $,
254
- Disable: () => Disable,
255
- Enable: () => Enable
256
- });
257
-
258
- // src/platform/_lib/cli/dispatchToSubCommand.ts
259
- import internals3 from "@prisma/internals";
260
- var { HelpError, link } = internals3;
261
- var dispatchToSubCommand = async (commands, argv, config) => {
262
- const commandName = argv[0];
263
- if (!commandName)
264
- return new HelpError(`Unknown command.`);
265
- const command = commands[commandName];
266
- if (!command)
267
- return new HelpError(`Unknown command or parameter "${commandName}"`);
268
- const hasHelpFlag = Boolean(argv.find((it) => ["-h", "--help"].includes(it)));
269
- if (hasHelpFlag)
270
- return `Help output for this command will be available soon. In the meantime, visit ${link("https://pris.ly/cli/platform-docs")} for more information.`;
271
- const result = await command.parse(argv.slice(1), config);
272
- return result;
273
- };
274
-
275
- // src/platform/_lib/cli/namespace.ts
276
- var createNamespace = () => {
277
- return class $7 {
278
- constructor(commands) {
279
- this.commands = commands;
280
- }
281
- static new(commands) {
282
- return new $7(commands);
283
- }
284
- async parse(argv, config) {
285
- return await dispatchToSubCommand(this.commands, argv, config);
286
- }
287
- };
288
- };
289
-
290
- // src/platform/accelerate/$.ts
291
- var $ = createNamespace();
292
-
293
- // src/platform/_lib/messages.ts
294
- import internals4 from "@prisma/internals";
295
- import { bold as bold2, dim, green as green2, white } from "kleur/colors";
296
- var table = (object, renderersInput) => {
297
- const renderers = {
298
- key: renderersInput.key ?? dim,
299
- // eslint-disable-next-line
300
- values: internals4.mapObjectValues(
301
- renderersInput.values ?? {},
302
- (_) => _ === true ? id : _
303
- )
304
- };
305
- return internals4.formatTable(
306
- Object.entries(renderers.values).map(([propertyName, renderer]) => {
307
- const valueRendered = renderer(object[propertyName]);
308
- if (valueRendered === null)
309
- return null;
310
- return [renderers.key(String(propertyName)), valueRendered];
311
- }).filter(Boolean)
312
- );
313
- };
314
- var successMessage = (message) => `${green2("Success!")} ${message}`;
315
- var messages = {
316
- resourceCreated: (resource) => successMessage(`${resource.__typename} ${resource.displayName} - ${resource.id} created.`),
317
- resourceDeleted: (resource) => successMessage(`${resource.__typename} ${resource.displayName} - ${resource.id} deleted.`),
318
- resource: (resource, renderers) => {
319
- return messages.table(resource, {
320
- values: {
321
- displayName: (_) => white(bold2(_)),
322
- id: true,
323
- createdAt: (_) => _ ? Intl.DateTimeFormat().format(new Date(_)) : null,
324
- ...renderers
325
- }
326
- });
327
- },
328
- resourceList: (records) => {
329
- if (records.length === 0)
330
- return messages.info("No records found.");
331
- return records.map((record) => messages.resource(record)).join("\n\n\n");
332
- },
333
- info: (message) => message,
334
- sections: (sections) => sections.join("\n\n"),
335
- table,
336
- success: successMessage
337
- };
338
-
339
- // src/platform/_lib/pdp.ts
340
- import fetch, { Headers } from "node-fetch";
341
-
342
- // src/platform/_lib/userAgent.ts
343
- import Debug from "@prisma/debug";
344
- import internals5 from "@prisma/internals";
345
- import * as Checkpoint from "checkpoint-client";
346
-
347
- // package.json
348
- var version = "0.0.0-dev.202505142350";
349
-
350
- // src/platform/_lib/userAgent.ts
351
- var debug = Debug("prisma:cli:platform:_lib:userAgent");
352
- var getUserAgent = async () => {
353
- const signature = await Checkpoint.getSignature().catch(unknownToError);
354
- if (internals5.isError(signature))
355
- debug(`await checkpoint.getSignature() failed silently with ${signature.message}`);
356
- const signatureString = internals5.isError(signature) ? "unknown" : signature;
357
- return `prisma-cli-init/${version} (Signature: ${signatureString})`;
358
- };
359
-
360
- // src/platform/_lib/pdp.ts
361
- var platformAPIEndpoint = new URL("https://console.prisma.io/api");
362
- var consoleUrl = new URL("https://console.prisma.io");
363
- var requestOrThrow = async (params) => {
364
- const userAgent = await getUserAgent();
365
- const method = "POST";
366
- const headers = new Headers({
367
- "Content-Type": "application/json",
368
- Authorization: `Bearer ${params.token}`,
369
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
370
- "User-Agent": userAgent
371
- });
372
- const body = JSON.stringify(params.body);
373
- const response = await fetch(platformAPIEndpoint.href, { method, headers, body });
374
- const text = await response.text();
375
- if (response.status >= 400)
376
- throw new Error(text);
377
- const json = JSON.parse(text);
378
- if (json.error)
379
- throw new Error(`Error from PDP Platform API: ${text}`);
380
- const error = Object.values(json.data).filter(
381
- (rootFieldValue) => typeof rootFieldValue === "object" && rootFieldValue !== null && rootFieldValue["__typename"]?.startsWith("Error")
382
- )[0];
383
- if (error)
384
- throw errorFromPlatformError({ message: "<message not selected from server>", ...error });
385
- return json.data;
386
- };
387
- var errorFromPlatformError = (error) => {
388
- return new Error(error.message);
389
- };
390
-
391
- // src/platform/accelerate/disable.ts
392
- var Disable = class _Disable {
393
- static new() {
394
- return new _Disable();
395
- }
396
- async parse(argv, _config) {
397
- const args = argOrThrow(argv, {
398
- ...platformParameters.environment
399
- });
400
- const token = await getTokenOrThrow(args);
401
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
402
- await requestOrThrow({
403
- token,
404
- body: {
405
- query: (
406
- /* GraphQL */
407
- `
408
- mutation ($input: MutationAccelerateDisableInput!) {
409
- accelerateDisable(input: $input) {
410
- __typename
411
- ... on Error {
412
- message
413
- }
414
- }
415
- }
416
- `
417
- ),
418
- variables: {
419
- input: { environmentId }
420
- }
421
- }
422
- });
423
- return messages.success(
424
- `Accelerate disabled. Prisma clients connected to ${environmentId} will not be able to send queries through Accelerate.`
425
- );
426
- }
427
- };
428
-
429
- // src/platform/accelerate/enable.ts
430
- import internals6 from "@prisma/internals";
431
- var Enable = class _Enable {
432
- static new() {
433
- return new _Enable();
434
- }
435
- async parse(argv, _config) {
436
- const args = internals6.arg(argv, {
437
- ...platformParameters.environment,
438
- "--url": String,
439
- // TODO rename to "serviceToken" in a future release.
440
- "--apikey": Boolean,
441
- "--region": String
442
- });
443
- if (internals6.isError(args))
444
- return args;
445
- const token = await getTokenOrThrow(args);
446
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
447
- const connectionString = getRequiredParameterOrThrow(args, ["--url"]);
448
- const withServiceToken = getOptionalParameter(args, ["--apikey"]) ?? false;
449
- const regionId = getOptionalParameter(args, ["--region"]);
450
- const { databaseLinkCreate } = await requestOrThrow({
451
- token,
452
- body: {
453
- query: (
454
- /* GraphQL */
455
- `
456
- mutation ($input: MutationDatabaseLinkCreateInput!) {
457
- databaseLinkCreate(input: $input) {
458
- __typename
459
- ... on Error {
460
- message
461
- }
462
- ... on DatabaseLink {
463
- id
464
- }
465
- }
466
- }
467
- `
468
- ),
469
- variables: {
470
- input: {
471
- environmentId,
472
- connectionString,
473
- ...regionId && { regionId }
474
- }
475
- }
476
- }
477
- });
478
- const { serviceTokenCreate } = await requestOrThrow({
479
- token,
480
- body: {
481
- query: (
482
- /* GraphQL */
483
- `
484
- mutation (
485
- $accelerateEnableInput: MutationAccelerateEnableInput!
486
- $serviceTokenCreateInput: MutationServiceTokenCreateInput!
487
- $withServiceToken: Boolean!
488
- ) {
489
- accelerateEnable(input: $accelerateEnableInput) {
490
- __typename
491
- ... on Error {
492
- message
493
- }
494
- }
495
- serviceTokenCreate(input: $serviceTokenCreateInput) @include(if: $withServiceToken) {
496
- __typename
497
- ... on Error {
498
- message
499
- }
500
- ... on ServiceTokenWithValue {
501
- value
502
- }
503
- }
504
- }
505
- `
506
- ),
507
- variables: {
508
- withServiceToken,
509
- accelerateEnableInput: { databaseLinkId: databaseLinkCreate.id },
510
- serviceTokenCreateInput: { environmentId }
511
- }
512
- }
513
- });
514
- const gettingStartedUrl = internals6.link("https://pris.ly/d/accelerate-getting-started");
515
- if (serviceTokenCreate) {
516
- return messages.success(
517
- `Accelerate enabled. Use this Accelerate connection string to authenticate requests:
518
-
519
- ${generateConnectionString(serviceTokenCreate.value)}
520
-
521
- For more information, check out the Getting started guide here: ${gettingStartedUrl}`
522
- );
523
- } else {
524
- return messages.success(
525
- `Accelerate enabled. Use your secure API key in your Accelerate connection string to authenticate requests.
526
-
527
- For more information, check out the Getting started guide here: ${gettingStartedUrl}`
528
- );
529
- }
530
- }
531
- };
532
-
533
- // src/platform/auth/_.ts
534
- var __exports2 = {};
535
- __export(__exports2, {
536
- $: () => $2,
537
- Login: () => Login,
538
- Logout: () => Logout,
539
- Show: () => Show,
540
- loginOrSignup: () => loginOrSignup
541
- });
542
-
543
- // src/platform/auth/$.ts
544
- var $2 = createNamespace();
545
-
546
- // src/platform/auth/login.ts
547
- import { select } from "@inquirer/prompts";
548
- import Debug2 from "@prisma/debug";
549
- import internals7 from "@prisma/internals";
550
- import listen from "async-listen";
551
- import http from "http";
552
- import { green as green3 } from "kleur/colors";
553
- import open from "open";
554
- var debug2 = Debug2("prisma:cli:platform:login");
555
- var Login = class _Login {
556
- static new() {
557
- return new _Login();
558
- }
559
- async parse(argv, _config) {
560
- const args = internals7.arg(argv, {
561
- // internal optimize flag to track signup attribution
562
- "--optimize": Boolean
563
- });
564
- if (internals7.isError(args))
565
- return args;
566
- if (args["--optimize"]) {
567
- console.warn("The '--optimize' flag is deprecated. Use API keys instead.");
568
- }
569
- const credentials = await credentialsFile.load();
570
- if (internals7.isError(credentials))
571
- throw credentials;
572
- if (credentials)
573
- return `Already authenticated. Run ${green3(internals7.getCommandWithExecutor("prisma platform auth show --early-access"))} to see the current user.`;
574
- console.info("Authenticating to Prisma Platform CLI via browser.\n");
575
- const server = http.createServer();
576
- const randomPort = 0;
577
- const redirectUrl = await listen(server, randomPort, "127.0.0.1");
578
- const loginUrl = await createLoginUrl({ connection: "github", redirectTo: redirectUrl.href });
579
- console.info("Visit the following URL in your browser to authenticate:");
580
- console.info(internals7.link(loginUrl.href));
581
- const callbackResult = await Promise.all([
582
- new Promise((resolve, reject) => {
583
- server.once("request", (req, res) => {
584
- server.close();
585
- res.setHeader("connection", "close");
586
- const searchParams = new URL(req.url || "/", "http://localhost").searchParams;
587
- const token = searchParams.get("token") ?? "";
588
- const error = searchParams.get("error");
589
- const location = getBaseAuthUrl();
590
- if (error) {
591
- location.pathname += "/error";
592
- location.searchParams.set("error", error);
593
- reject(new Error(error));
594
- } else {
595
- const user = decodeUser(searchParams.get("user") ?? "");
596
- if (user) {
597
- searchParams.delete("token");
598
- searchParams.delete("user");
599
- location.pathname += "/success";
600
- const nextSearchParams = new URLSearchParams({
601
- ...Object.fromEntries(searchParams.entries()),
602
- email: user.email
603
- });
604
- location.search = nextSearchParams.toString();
605
- resolve({ token, user });
606
- } else {
607
- location.pathname += "/error";
608
- location.searchParams.set("error", "Invalid user");
609
- reject(new Error("Invalid user"));
610
- }
611
- }
612
- res.statusCode = 302;
613
- res.setHeader("location", location.href);
614
- res.end();
615
- });
616
- server.once("error", reject);
617
- }),
618
- open(loginUrl.href)
619
- ]).then((results) => results[0]).catch(unknownToError);
620
- if (internals7.isError(callbackResult))
621
- throw new Error(`Authentication failed: ${callbackResult.message}`);
622
- {
623
- const writeResult = await credentialsFile.save({ token: callbackResult.token });
624
- if (internals7.isError(writeResult))
625
- throw new Error("Writing credentials to disk failed", { cause: writeResult });
626
- }
627
- return successMessage(`Authentication successful for ${callbackResult.user.email}`);
628
- }
629
- };
630
- var getBaseAuthUrl = () => new URL("/auth/cli", consoleUrl);
631
- var createLoginUrl = async (params) => {
632
- const userAgent = await getUserAgent();
633
- const state = {
634
- client: userAgent,
635
- ...params
636
- };
637
- const stateEncoded = encodeState(state);
638
- const url = getBaseAuthUrl();
639
- url.searchParams.set("state", stateEncoded);
640
- return url;
641
- };
642
- var encodeState = (state) => Buffer.from(JSON.stringify(state), "utf-8").toString("base64");
643
- var decodeUser = (stringifiedUser) => {
644
- try {
645
- const maybeUser = JSON.parse(Buffer.from(stringifiedUser, `base64`).toString(`utf-8`));
646
- if (typeof maybeUser !== "object" || maybeUser === null)
647
- return false;
648
- const isUser = typeof maybeUser.id === "string" && typeof maybeUser.displayName === "string" && typeof maybeUser.email === "string";
649
- return isUser ? maybeUser : null;
650
- } catch (e) {
651
- debug2(`parseUser() failed silently with ${e}`);
652
- return null;
653
- }
654
- };
655
- var loginOrSignup = async () => {
656
- const providerAnswer = await select({
657
- message: "Select an authentication method",
658
- default: "google",
659
- choices: [
660
- { name: "Google", value: "google" },
661
- { name: "GitHub", value: "github" }
662
- ]
663
- });
664
- console.info("Authenticating to Prisma Platform via browser.\n");
665
- const server = http.createServer();
666
- const randomPort = 0;
667
- const redirectUrl = await listen(server, randomPort, "127.0.0.1");
668
- const loginUrl = await createLoginUrl({ connection: providerAnswer, redirectTo: redirectUrl.href });
669
- console.info("Visit the following URL in your browser to authenticate:");
670
- console.info(internals7.link(loginUrl.href));
671
- const callbackResult = await Promise.all([
672
- new Promise((resolve, reject) => {
673
- server.once("request", (req, res) => {
674
- server.close();
675
- res.setHeader("connection", "close");
676
- const searchParams = new URL(req.url || "/", "http://localhost").searchParams;
677
- const token = searchParams.get("token") ?? "";
678
- const error = searchParams.get("error");
679
- const location = getBaseAuthUrl();
680
- if (error) {
681
- location.pathname += "/error";
682
- location.searchParams.set("error", error);
683
- reject(new Error(error));
684
- } else {
685
- const user = decodeUser(searchParams.get("user") ?? "");
686
- if (user) {
687
- searchParams.delete("token");
688
- searchParams.delete("user");
689
- location.pathname += "/success";
690
- const nextSearchParams = new URLSearchParams({
691
- ...Object.fromEntries(searchParams.entries()),
692
- email: user.email
693
- });
694
- location.search = nextSearchParams.toString();
695
- resolve({ token, user });
696
- } else {
697
- location.pathname += "/error";
698
- location.searchParams.set("error", "Invalid user");
699
- reject(new Error("Invalid user"));
700
- }
701
- }
702
- res.statusCode = 302;
703
- res.setHeader("location", location.href);
704
- res.end();
705
- });
706
- server.once("error", reject);
707
- }),
708
- open(loginUrl.href)
709
- ]).then((results) => results[0]).catch(unknownToError);
710
- if (internals7.isError(callbackResult))
711
- throw new Error(`Authentication failed: ${callbackResult.message}`);
712
- {
713
- const writeResult = await credentialsFile.save({ token: callbackResult.token });
714
- if (internals7.isError(writeResult))
715
- throw new Error("Writing credentials to disk failed", { cause: writeResult });
716
- }
717
- return {
718
- message: successMessage(`Authentication successful for ${callbackResult.user.email}`),
719
- email: callbackResult.user.email,
720
- token: callbackResult.token
721
- };
722
- };
723
-
724
- // src/platform/auth/logout.ts
725
- import internals9 from "@prisma/internals";
726
- import { green as green4 } from "kleur/colors";
727
-
728
- // src/platform/_lib/jwt.ts
729
- import internals8 from "@prisma/internals";
730
- var decodeJwt = (jwt) => {
731
- if (typeof jwt !== "string")
732
- throw new Error("JWTs must use Compact JWS serialization, JWT must be a string");
733
- const { 1: payload, length } = jwt.split(".");
734
- if (length === 5)
735
- throw new Error("Only JWTs using Compact JWS serialization can be decoded");
736
- if (length !== 3)
737
- throw new Error("Invalid JWT");
738
- if (!payload)
739
- throw new Error("JWTs must contain a payload");
740
- const decoded = tryCatch(
741
- () => atob(payload),
742
- () => new Error("Failed to base64 decode the payload.")
743
- );
744
- if (internals8.isError(decoded))
745
- return decoded;
746
- const result = tryCatch(
747
- () => JSON.parse(decoded),
748
- () => new Error("Failed to parse the decoded payload as JSON.")
749
- );
750
- if (internals8.isError(result))
751
- return result;
752
- if (!isObject(result))
753
- throw new Error("Invalid JWT Claims Set.");
754
- return result;
755
- };
756
-
757
- // src/platform/auth/logout.ts
758
- var Logout = class _Logout {
759
- static new() {
760
- return new _Logout();
761
- }
762
- async parse() {
763
- const credentials = await credentialsFile.load();
764
- if (internals9.isError(credentials))
765
- throw credentials;
766
- if (!credentials)
767
- return `You are not currently logged in. Run ${green4(internals9.getCommandWithExecutor("prisma platform auth login --early-access"))} to log in.`;
768
- if (credentials.token) {
769
- const jwt = decodeJwt(credentials.token);
770
- if (!internals9.isError(jwt) && jwt.jti) {
771
- await requestOrThrow({
772
- token: credentials.token,
773
- body: {
774
- query: (
775
- /* GraphQL */
776
- `
777
- mutation ($input: MutationManagementTokenDeleteInput!) {
778
- managementTokenDelete(input: $input) {
779
- __typename
780
- ... on Error {
781
- message
782
- }
783
- }
784
- }
785
- `
786
- ),
787
- variables: {
788
- input: {
789
- id: jwt.jti
790
- }
791
- }
792
- }
793
- });
794
- }
795
- }
796
- await credentialsFile.delete();
797
- return successMessage("You have logged out.");
798
- }
799
- };
800
-
801
- // src/platform/auth/show.ts
802
- import { green as green5 } from "kleur/colors";
803
- var Show = class _Show {
804
- static new() {
805
- return new _Show();
806
- }
807
- async parse(argv, _config) {
808
- const args = argOrThrow(argv, {
809
- ...platformParameters.global,
810
- "--sensitive": Boolean
811
- });
812
- const token = await getTokenOrThrow(args);
813
- const { me } = await requestOrThrow({
814
- token,
815
- body: {
816
- query: (
817
- /* graphql */
818
- `
819
- query {
820
- me {
821
- __typename
822
- user {
823
- __typename
824
- id
825
- email
826
- displayName
827
- }
828
- }
829
- }
830
- `
831
- )
832
- }
833
- });
834
- const data = {
835
- ...me.user,
836
- token: getOptionalParameter(args, ["--sensitive"]) ? token : null
837
- };
838
- return messages.sections([
839
- messages.info(`Currently authenticated as ${green5(me.user.email)}`),
840
- messages.resource(data, {
841
- email: true,
842
- token: true
843
- })
844
- ]);
845
- }
846
- };
847
-
848
- // src/platform/environment/_.ts
849
- var __exports3 = {};
850
- __export(__exports3, {
851
- $: () => $3,
852
- Create: () => Create,
853
- Delete: () => Delete,
854
- Show: () => Show2,
855
- getEnvironmentOrThrow: () => getEnvironmentOrThrow
856
- });
857
-
858
- // src/platform/environment/$.ts
859
- var $3 = createNamespace();
860
-
861
- // src/platform/environment/create.ts
862
- var Create = class _Create {
863
- static new() {
864
- return new _Create();
865
- }
866
- async parse(argv, _config) {
867
- const args = argOrThrow(argv, {
868
- ...platformParameters.project,
869
- "--name": String,
870
- "-n": "--name"
871
- });
872
- const token = await getTokenOrThrow(args);
873
- const projectId = getRequiredParameterOrThrow(args, ["--project", "-p"]);
874
- const displayName = getOptionalParameter(args, ["--name", "-n"]);
875
- const { environmentCreate } = await requestOrThrow({
876
- token,
877
- body: {
878
- query: (
879
- /* graphql */
880
- `
881
- mutation ($input: MutationEnvironmentCreateInput!) {
882
- environmentCreate(input: $input) {
883
- __typename
884
- ...on Error {
885
- message
886
- }
887
- ...on Environment {
888
- id
889
- createdAt
890
- displayName
891
- }
892
- }
893
- }
894
- `
895
- ),
896
- variables: {
897
- input: {
898
- projectId,
899
- displayName
900
- }
901
- }
902
- }
903
- });
904
- return messages.resourceCreated(environmentCreate);
905
- }
906
- };
907
-
908
- // src/platform/environment/delete.ts
909
- import internals10 from "@prisma/internals";
910
- var Delete = class _Delete {
911
- static new() {
912
- return new _Delete();
913
- }
914
- async parse(argv, _config) {
915
- const args = internals10.arg(argv, {
916
- ...platformParameters.environment
917
- });
918
- if (internals10.isError(args))
919
- return args;
920
- const token = await getTokenOrThrow(args);
921
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
922
- const { environmentDelete } = await requestOrThrow({
923
- token,
924
- body: {
925
- query: (
926
- /* graphql */
927
- `
928
- mutation ($input: MutationEnvironmentDeleteInput!) {
929
- environmentDelete(input: $input) {
930
- __typename
931
- ...on Error {
932
- message
933
- }
934
- ...on Environment {
935
- id
936
- createdAt
937
- displayName
938
- }
939
- }
940
- }
941
- `
942
- ),
943
- variables: {
944
- input: {
945
- id: environmentId
946
- }
947
- }
948
- }
949
- });
950
- return messages.resourceDeleted(environmentDelete);
951
- }
952
- };
953
-
954
- // src/platform/environment/show.ts
955
- import internals11 from "@prisma/internals";
956
- var Show2 = class _Show {
957
- static new() {
958
- return new _Show();
959
- }
960
- async parse(argv, _config) {
961
- const args = internals11.arg(argv, {
962
- ...platformParameters.project
963
- });
964
- if (internals11.isError(args))
965
- return args;
966
- const token = await getTokenOrThrow(args);
967
- const projectId = getRequiredParameterOrThrow(args, ["--project", "-p"]);
968
- const { project } = await requestOrThrow({
969
- token,
970
- body: {
971
- query: (
972
- /* GraphQL */
973
- `
974
- query ($input: QueryProjectInput!) {
975
- project(input: $input) {
976
- __typename
977
- ... on Error {
978
- message
979
- }
980
- ... on Project {
981
- environments {
982
- __typename
983
- id
984
- createdAt
985
- displayName
986
- }
987
- }
988
- }
989
- }
990
- `
991
- ),
992
- variables: {
993
- input: {
994
- id: projectId
995
- }
996
- }
997
- }
998
- });
999
- return messages.resourceList(project.environments);
1000
- }
1001
- };
1002
- var getEnvironmentOrThrow = async (input) => {
1003
- const { token, environmentId } = input;
1004
- const { environment } = await requestOrThrow({
1005
- token,
1006
- body: {
1007
- query: (
1008
- /* GraphQL */
1009
- `
1010
- query ($input: QueryEnvironmentInput!) {
1011
- environment(input: $input) {
1012
- __typename
1013
- ... on Error {
1014
- message
1015
- }
1016
- ... on Environment {
1017
- __typename
1018
- id
1019
- displayName
1020
- ppg {
1021
- status
1022
- }
1023
- accelerate {
1024
- status {
1025
- ... on AccelerateStatusEnabled {
1026
- __typename
1027
- enabled
1028
- }
1029
- ... on AccelerateStatusDisabled {
1030
- __typename
1031
- enabled
1032
- }
1033
- }
1034
- }
1035
- }
1036
- }
1037
- }
1038
- `
1039
- ),
1040
- variables: {
1041
- input: {
1042
- id: environmentId
1043
- }
1044
- }
1045
- }
1046
- });
1047
- return environment;
1048
- };
1049
-
1050
- // src/platform/project/_.ts
1051
- var __exports4 = {};
1052
- __export(__exports4, {
1053
- $: () => $4,
1054
- Create: () => Create2,
1055
- Delete: () => Delete2,
1056
- Show: () => Show3,
1057
- createProjectOrThrow: () => createProjectOrThrow
1058
- });
1059
-
1060
- // src/platform/project/$.ts
1061
- var $4 = createNamespace();
1062
-
1063
- // src/platform/project/create.ts
1064
- var Create2 = class _Create {
1065
- static new() {
1066
- return new _Create();
1067
- }
1068
- async parse(argv, _config) {
1069
- const args = argOrThrow(argv, {
1070
- ...platformParameters.workspace,
1071
- "--name": String,
1072
- "-n": "--name"
1073
- });
1074
- const workspaceId = getRequiredParameterOrThrow(args, ["--workspace", "-w"]);
1075
- const displayName = getOptionalParameter(args, ["--name", "-n"]);
1076
- const project = await createProjectOrThrow({
1077
- token: await getTokenOrThrow(args),
1078
- workspaceId,
1079
- displayName
1080
- });
1081
- return messages.resourceCreated(project);
1082
- }
1083
- };
1084
- var createProjectOrThrow = async (input) => {
1085
- const { token, ...mutationInput } = input;
1086
- const { projectCreate } = await requestOrThrow({
1087
- token,
1088
- body: {
1089
- query: (
1090
- /* graphql */
1091
- `
1092
- mutation ($input: MutationProjectCreateInput!) {
1093
- projectCreate(input: $input) {
1094
- __typename
1095
- ...on Error {
1096
- message
1097
- }
1098
- ...on Project {
1099
- id
1100
- createdAt
1101
- displayName
1102
- defaultEnvironment {
1103
- id
1104
- displayName
1105
- }
1106
- }
1107
- }
1108
- }
1109
- `
1110
- ),
1111
- variables: {
1112
- input: mutationInput
1113
- }
1114
- }
1115
- });
1116
- return projectCreate;
1117
- };
1118
-
1119
- // src/platform/project/delete.ts
1120
- import internals12 from "@prisma/internals";
1121
- var Delete2 = class _Delete {
1122
- static new() {
1123
- return new _Delete();
1124
- }
1125
- async parse(argv, _config) {
1126
- const args = internals12.arg(argv, {
1127
- ...platformParameters.project
1128
- });
1129
- if (internals12.isError(args))
1130
- return args;
1131
- const token = await getTokenOrThrow(args);
1132
- const projectId = getRequiredParameterOrThrow(args, ["--project", "-p"]);
1133
- const { projectDelete } = await requestOrThrow({
1134
- token,
1135
- body: {
1136
- query: (
1137
- /* graphql */
1138
- `
1139
- mutation ($input: MutationProjectDeleteInput!) {
1140
- projectDelete(input: $input) {
1141
- __typename
1142
- ...on Error {
1143
- message
1144
- }
1145
- ...on ProjectNode {
1146
- id
1147
- createdAt
1148
- displayName
1149
- }
1150
- }
1151
- }
1152
- `
1153
- ),
1154
- variables: {
1155
- input: {
1156
- id: projectId
1157
- }
1158
- }
1159
- }
1160
- });
1161
- return messages.resourceDeleted(projectDelete);
1162
- }
1163
- };
1164
-
1165
- // src/platform/project/show.ts
1166
- import internals13 from "@prisma/internals";
1167
- var Show3 = class _Show {
1168
- static new() {
1169
- return new _Show();
1170
- }
1171
- async parse(argv, _config) {
1172
- const args = internals13.arg(argv, {
1173
- ...platformParameters.workspace
1174
- });
1175
- if (internals13.isError(args))
1176
- return args;
1177
- const token = await getTokenOrThrow(args);
1178
- const workspaceId = getRequiredParameterOrThrow(args, ["--workspace", "-w"]);
1179
- const { workspace } = await requestOrThrow({
1180
- token,
1181
- body: {
1182
- query: (
1183
- /* GraphQL */
1184
- `
1185
- query ($input: QueryWorkspaceInput!) {
1186
- workspace(input: $input) {
1187
- __typename
1188
- ... on Error {
1189
- message
1190
- }
1191
- ... on Workspace {
1192
- projects {
1193
- __typename
1194
- id
1195
- createdAt
1196
- displayName
1197
- }
1198
- }
1199
- }
1200
- }
1201
- `
1202
- ),
1203
- variables: {
1204
- input: {
1205
- id: workspaceId
1206
- }
1207
- }
1208
- }
1209
- });
1210
- return messages.resourceList(workspace.projects);
1211
- }
1212
- };
1213
-
1214
- // src/platform/serviceToken/_.ts
1215
- var __exports5 = {};
1216
- __export(__exports5, {
1217
- $: () => $5,
1218
- Create: () => Create3,
1219
- Delete: () => Delete3,
1220
- Show: () => Show4,
1221
- createOrThrow: () => createOrThrow
1222
- });
1223
-
1224
- // src/platform/serviceToken/$.ts
1225
- var $5 = createNamespace();
1226
-
1227
- // src/platform/serviceToken/create.ts
1228
- var Create3 = class _Create {
1229
- constructor(legacy = false) {
1230
- this.legacy = legacy;
1231
- }
1232
- static new(legacy = false) {
1233
- return new _Create(legacy);
1234
- }
1235
- async parse(argv, _config) {
1236
- const args = argOrThrow(argv, {
1237
- ...platformParameters.environment,
1238
- "--name": String,
1239
- "-n": "--name"
1240
- });
1241
- const token = await getTokenOrThrow(args);
1242
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
1243
- const displayName = getOptionalParameter(args, ["--name", "-n"]);
1244
- const serviceTokenCreate = await createOrThrow({ environmentId, displayName, token });
1245
- const resource = this.legacy ? {
1246
- ...serviceTokenCreate.serviceToken,
1247
- __typename: "APIKey"
1248
- } : serviceTokenCreate.serviceToken;
1249
- return messages.sections([messages.resourceCreated(resource), messages.info(serviceTokenCreate.value)]);
1250
- }
1251
- };
1252
- var createOrThrow = async (input) => {
1253
- const { environmentId, displayName, token } = input;
1254
- const { serviceTokenCreate } = await requestOrThrow({
1255
- token,
1256
- body: {
1257
- query: (
1258
- /* GraphQL */
1259
- `
1260
- mutation ($input: MutationServiceTokenCreateInput!) {
1261
- serviceTokenCreate(input: $input) {
1262
- __typename
1263
- ... on Error {
1264
- message
1265
- }
1266
- ... on ServiceTokenWithValue {
1267
- value
1268
- serviceToken {
1269
- __typename
1270
- id
1271
- createdAt
1272
- displayName
1273
- }
1274
- }
1275
- }
1276
- }
1277
- `
1278
- ),
1279
- variables: {
1280
- input: {
1281
- displayName,
1282
- environmentId
1283
- }
1284
- }
1285
- }
1286
- });
1287
- return serviceTokenCreate;
1288
- };
1289
-
1290
- // src/platform/serviceToken/delete.ts
1291
- var Delete3 = class _Delete {
1292
- constructor(legacy = false) {
1293
- this.legacy = legacy;
1294
- }
1295
- static new(legacy = false) {
1296
- return new _Delete(legacy);
1297
- }
1298
- async parse(argv, _config) {
1299
- const args = argOrThrow(argv, {
1300
- ...platformParameters[this.legacy ? "apikey" : "serviceToken"]
1301
- });
1302
- const token = await getTokenOrThrow(args);
1303
- const serviceTokenId = this.legacy ? getRequiredParameterOrThrow(args, ["--apikey"]) : getRequiredParameterOrThrow(args, ["--serviceToken", "-s"]);
1304
- const { serviceTokenDelete } = await requestOrThrow({
1305
- token,
1306
- body: {
1307
- query: (
1308
- /* GraphQL */
1309
- `
1310
- mutation ($input: MutationServiceTokenDeleteInput!) {
1311
- serviceTokenDelete(input: $input) {
1312
- __typename
1313
- ... on Error {
1314
- message
1315
- }
1316
- ... on ServiceTokenNode {
1317
- id
1318
- displayName
1319
- }
1320
- }
1321
- }
1322
- `
1323
- ),
1324
- variables: {
1325
- input: {
1326
- id: serviceTokenId
1327
- }
1328
- }
1329
- }
1330
- });
1331
- return messages.resourceDeleted(this.legacy ? { ...serviceTokenDelete, __typename: "APIKey" } : serviceTokenDelete);
1332
- }
1333
- };
1334
-
1335
- // src/platform/serviceToken/show.ts
1336
- import internals14 from "@prisma/internals";
1337
- var Show4 = class _Show {
1338
- constructor(legacy = false) {
1339
- this.legacy = legacy;
1340
- }
1341
- static new(legacy = false) {
1342
- return new _Show(legacy);
1343
- }
1344
- async parse(argv, _config) {
1345
- const args = internals14.arg(argv, {
1346
- ...platformParameters.environment
1347
- });
1348
- if (internals14.isError(args))
1349
- return args;
1350
- const token = await getTokenOrThrow(args);
1351
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
1352
- const { environment } = await requestOrThrow({
1353
- token,
1354
- body: {
1355
- query: (
1356
- /* GraphQL */
1357
- `
1358
- query ($input: QueryEnvironmentInput!) {
1359
- environment(input: $input) {
1360
- __typename
1361
- ... on Error {
1362
- message
1363
- }
1364
- ... on Environment {
1365
- serviceTokens {
1366
- id
1367
- createdAt
1368
- displayName
1369
- }
1370
- }
1371
- }
1372
- }
1373
- `
1374
- ),
1375
- variables: {
1376
- input: {
1377
- id: environmentId
1378
- }
1379
- }
1380
- }
1381
- });
1382
- const resources = this.legacy ? environment.serviceTokens.map((serviceToken) => ({ ...serviceToken, __typename: "APIKey" })) : environment.serviceTokens;
1383
- return messages.resourceList(resources);
1384
- }
1385
- };
1386
-
1387
- // src/platform/workspace/_.ts
1388
- var __exports6 = {};
1389
- __export(__exports6, {
1390
- $: () => $6,
1391
- Show: () => Show5,
1392
- getDefaultWorkspaceOrThrow: () => getDefaultWorkspaceOrThrow,
1393
- getUserWorkspacesOrThrow: () => getUserWorkspacesOrThrow
1394
- });
1395
-
1396
- // src/platform/workspace/$.ts
1397
- var $6 = createNamespace();
1398
-
1399
- // src/platform/workspace/show.ts
1400
- var Show5 = class _Show {
1401
- static new() {
1402
- return new _Show();
1403
- }
1404
- async parse(argv, _config) {
1405
- const args = argOrThrow(argv, {
1406
- ...platformParameters.global
1407
- });
1408
- const token = await getTokenOrThrow(args);
1409
- const userWorkspaces = await getUserWorkspacesOrThrow({ token });
1410
- return messages.resourceList(userWorkspaces);
1411
- }
1412
- };
1413
- var getUserWorkspacesOrThrow = async (input) => {
1414
- const { token } = input;
1415
- const { me } = await requestOrThrow({
1416
- token,
1417
- body: {
1418
- query: (
1419
- /* GraphQL */
1420
- `
1421
- query {
1422
- me {
1423
- __typename
1424
- workspaces {
1425
- id
1426
- displayName
1427
- createdAt
1428
- isDefault
1429
- }
1430
- }
1431
- }
1432
- `
1433
- )
1434
- }
1435
- });
1436
- return me.workspaces;
1437
- };
1438
- var getDefaultWorkspaceOrThrow = async (input) => {
1439
- const { token } = input;
1440
- const { me } = await requestOrThrow({
1441
- token,
1442
- body: {
1443
- query: (
1444
- /* GraphQL */
1445
- `
1446
- query {
1447
- me {
1448
- __typename
1449
- workspaces {
1450
- id
1451
- displayName
1452
- createdAt
1453
- isDefault
1454
- }
1455
- }
1456
- }
1457
- `
1458
- )
1459
- }
1460
- });
1461
- const defaultWorkspace = me.workspaces.find((_) => _.isDefault);
1462
- if (!defaultWorkspace) {
1463
- throw new Error("No default workspace found");
1464
- }
1465
- return defaultWorkspace;
1466
- };
1467
-
1468
- export {
1469
- credentialsFile,
1470
- platformParameters,
1471
- ErrorPlatformUnauthorized,
1472
- getTokenOrThrow,
1473
- generateConnectionString,
1474
- poll,
1475
- printPpgInitOutput,
1476
- successMessage,
1477
- requestOrThrow,
1478
- __exports,
1479
- Login,
1480
- loginOrSignup,
1481
- Logout,
1482
- __exports2,
1483
- __exports3,
1484
- __exports4,
1485
- __exports5,
1486
- __exports6
1487
- };