@prisma/cli 3.0.0-beta.4 → 3.0.0-beta.5

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.
package/README.md CHANGED
@@ -57,6 +57,7 @@ Useful next commands:
57
57
  npx prisma-cli app logs
58
58
  npx prisma-cli app open
59
59
  npx prisma-cli project env add DATABASE_URL=postgresql://example --role preview
60
+ npx prisma-cli project env add --file .env --role preview
60
61
  npx prisma-cli project env list
61
62
  npx prisma-cli project env list --role preview
62
63
  ```
@@ -1,3 +1,4 @@
1
+ import { usageError } from "../../shell/errors.js";
1
2
  import { attachCommandDescriptor } from "../../shell/command-meta.js";
2
3
  import { addCompactGlobalFlags, addGlobalFlags } from "../../shell/global-flags.js";
3
4
  import { configureRuntimeCommand } from "../../shell/runtime.js";
@@ -64,7 +65,7 @@ function createDeployCommand(runtime) {
64
65
  "hono",
65
66
  "tanstack-start",
66
67
  "bun"
67
- ])).addOption(new Option("--entry <path>", "Entrypoint path for Bun deploys")).addOption(new Option("--http-port <port>", "HTTP port override for the deployed app")).addOption(new Option("--env <name=value>", "Environment variable").argParser(collectRepeatableValues)).addOption(new Option("--prod", "Confirm intent to deploy to production"));
68
+ ])).addOption(new Option("--entry <path>", "Entrypoint path for Bun deploys")).addOption(new Option("--http-port <port>", "HTTP port override for the deployed app")).addOption(new Option("--env <name=value>", "Environment variable").argParser(collectRepeatableValues)).addOption(new Option("--db", "Create and wire an isolated database for the preview Branch")).addOption(new Option("--no-db", "Skip branch database setup")).addOption(new Option("--prod", "Confirm intent to deploy to production"));
68
69
  addGlobalFlags(command);
69
70
  command.action(async (options) => {
70
71
  const appName = options.app;
@@ -76,22 +77,31 @@ function createDeployCommand(runtime) {
76
77
  const projectRef = options.project;
77
78
  const createProjectName = options.createProject;
78
79
  const prod = options.prod;
79
- await runCommand(runtime, "app.deploy", options, (context) => runAppDeploy(context, appName, {
80
- projectRef,
81
- createProjectName,
82
- branchName,
83
- entrypoint: entry,
84
- framework,
85
- httpPort,
86
- envAssignments,
87
- prod: prod === true
88
- }), {
80
+ const db = options.db;
81
+ const hasDbConflict = hasFlag(runtime.argv, "--db") && hasFlag(runtime.argv, "--no-db");
82
+ await runCommand(runtime, "app.deploy", options, (context) => {
83
+ if (hasDbConflict) throw usageError("app deploy accepts either --db or --no-db", "--db requests branch database setup, while --no-db disables it.", "Pass exactly one database setup flag.", ["prisma-cli app deploy --db", "prisma-cli app deploy --no-db"], "app");
84
+ return runAppDeploy(context, appName, {
85
+ projectRef,
86
+ createProjectName,
87
+ branchName,
88
+ entrypoint: entry,
89
+ framework,
90
+ httpPort,
91
+ envAssignments,
92
+ prod: prod === true,
93
+ db
94
+ });
95
+ }, {
89
96
  renderHuman: (context, descriptor, result) => renderAppDeploy(context, descriptor, result),
90
97
  renderJson: (result) => serializeAppDeploy(result)
91
98
  });
92
99
  });
93
100
  return command;
94
101
  }
102
+ function hasFlag(argv, flag) {
103
+ return argv.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
104
+ }
95
105
  function createShowCommand(runtime) {
96
106
  const command = attachCommandDescriptor(configureRuntimeCommand(new Command("show"), runtime), "app.show");
97
107
  command.addOption(new Option("--app <name>", "App name")).addOption(new Option("--project <id-or-name>", "Project id or name"));
@@ -17,16 +17,18 @@ function createEnvCommand(runtime) {
17
17
  }
18
18
  function createEnvAddCommand(runtime) {
19
19
  const command = attachCommandDescriptor(configureRuntimeCommand(new Command("add"), runtime), "project.env.add");
20
- command.argument("<assignment>", "Variable assignment as KEY=VALUE or KEY from the current environment").addOption(new Option("--role <role>", "Project template scope (production or preview)").choices(["production", "preview"])).addOption(new Option("--branch <git-name>", "Preview branch override scope")).addOption(new Option("--project <id-or-name>", "Project id or name"));
20
+ command.argument("[assignment]", "Variable assignment as KEY=VALUE or KEY from the current environment").addOption(new Option("--file <path>", "Read KEY=VALUE assignments from a dotenv file")).addOption(new Option("--role <role>", "Project template scope (production or preview)").choices(["production", "preview"])).addOption(new Option("--branch <git-name>", "Preview branch override scope")).addOption(new Option("--project <id-or-name>", "Project id or name"));
21
21
  addGlobalFlags(command);
22
22
  command.action(async (assignment, options) => {
23
23
  const roleName = options.role;
24
24
  const branchName = options.branch;
25
25
  const projectRef = options.project;
26
+ const filePath = options.file;
26
27
  await runCommand(runtime, "project.env.add", options, (context) => runEnvAdd(context, assignment, {
27
28
  roleName,
28
29
  branchName,
29
- projectRef
30
+ projectRef,
31
+ filePath
30
32
  }), {
31
33
  renderHuman: (context, descriptor, result) => renderEnvAdd(context, descriptor, result),
32
34
  renderJson: (result) => serializeEnvAdd(result)
@@ -36,16 +38,18 @@ function createEnvAddCommand(runtime) {
36
38
  }
37
39
  function createEnvUpdateCommand(runtime) {
38
40
  const command = attachCommandDescriptor(configureRuntimeCommand(new Command("update"), runtime), "project.env.update");
39
- command.argument("<assignment>", "Variable assignment as KEY=VALUE or KEY from the current environment").addOption(new Option("--role <role>", "Project template scope (production or preview)").choices(["production", "preview"])).addOption(new Option("--branch <git-name>", "Preview branch override scope")).addOption(new Option("--project <id-or-name>", "Project id or name"));
41
+ command.argument("[assignment]", "Variable assignment as KEY=VALUE or KEY from the current environment").addOption(new Option("--file <path>", "Read KEY=VALUE assignments from a dotenv file")).addOption(new Option("--role <role>", "Project template scope (production or preview)").choices(["production", "preview"])).addOption(new Option("--branch <git-name>", "Preview branch override scope")).addOption(new Option("--project <id-or-name>", "Project id or name"));
40
42
  addGlobalFlags(command);
41
43
  command.action(async (assignment, options) => {
42
44
  const roleName = options.role;
43
45
  const branchName = options.branch;
44
46
  const projectRef = options.project;
47
+ const filePath = options.file;
45
48
  await runCommand(runtime, "project.env.update", options, (context) => runEnvUpdate(context, assignment, {
46
49
  roleName,
47
50
  branchName,
48
- projectRef
51
+ projectRef,
52
+ filePath
49
53
  }), {
50
54
  renderHuman: (context, descriptor, result) => renderEnvUpdate(context, descriptor, result),
51
55
  renderJson: (result) => serializeEnvUpdate(result)
@@ -0,0 +1,54 @@
1
+ import { CliError, authRequiredError } from "../shell/errors.js";
2
+ //#region src/controllers/app-env-api.ts
3
+ async function findVariableByNaturalKey(client, projectId, key, resolved, signal) {
4
+ const { data, error, response } = await client.GET("/v1/environment-variables", {
5
+ params: { query: {
6
+ projectId,
7
+ class: resolved.apiTarget.class,
8
+ key
9
+ } },
10
+ signal
11
+ });
12
+ if (error || !data) throw apiCallError(`Failed to look up ${key}`, response, error);
13
+ return data.data.filter((row) => rowMatchesExactScope(row, resolved))[0] ?? null;
14
+ }
15
+ function toMetadata(row, requestedScope) {
16
+ const rowScope = row.branchId === null ? {
17
+ kind: "role",
18
+ role: row.class
19
+ } : requestedScope;
20
+ return {
21
+ id: row.id,
22
+ key: row.key,
23
+ scope: rowScope,
24
+ source: formatDescriptorLabel(rowScope),
25
+ isManagedBySystem: row.isManagedBySystem,
26
+ updatedAt: row.updatedAt
27
+ };
28
+ }
29
+ function rowMatchesExactScope(row, resolved) {
30
+ return row.class === resolved.apiTarget.class && row.branchId === resolved.apiTarget.branchId;
31
+ }
32
+ function apiCallError(summary, response, error) {
33
+ const status = response?.status ?? 0;
34
+ const apiCode = error?.error?.code;
35
+ const apiMessage = error?.error?.message;
36
+ const apiHint = error?.error?.hint;
37
+ if (status === 401 || status === 403) return authRequiredError(["prisma auth login"]);
38
+ return new CliError({
39
+ code: apiCode ?? "ENV_API_ERROR",
40
+ domain: "app",
41
+ summary,
42
+ why: apiMessage ?? `The Management API returned status ${status || "unknown"}.`,
43
+ fix: apiHint ?? "Re-run with --trace for the underlying API response details.",
44
+ exitCode: 1,
45
+ nextSteps: []
46
+ });
47
+ }
48
+ function formatDescriptorLabel(scope) {
49
+ if (scope.kind === "role") return scope.role ?? "unknown";
50
+ if (scope.kind === "overview") return "overview";
51
+ return `branch:${scope.branchName ?? scope.branchId ?? "unknown"}`;
52
+ }
53
+ //#endregion
54
+ export { apiCallError, findVariableByNaturalKey, toMetadata };
@@ -0,0 +1,179 @@
1
+ import { CliError } from "../shell/errors.js";
2
+ import { formatScopeLabel } from "../lib/app/env-config.js";
3
+ import { apiCallError, findVariableByNaturalKey, toMetadata } from "./app-env-api.js";
4
+ //#region src/controllers/app-env-file.ts
5
+ async function runEnvAddFile(context, client, projectId, resolved, filePath, assignments) {
6
+ const existing = await findVariablesByNaturalKey(client, projectId, assignments.map((assignment) => assignment.key), resolved, context.runtime.signal);
7
+ const existingKeys = assignments.map((assignment) => assignment.key).filter((key) => existing.has(key));
8
+ if (existingKeys.length > 0) throw new CliError({
9
+ code: "ENV_VARIABLE_ALREADY_EXISTS",
10
+ domain: "app",
11
+ summary: `${existingKeys.length} environment variable(s) already exist in ${formatScopeLabel(resolved.scope)}`,
12
+ why: `Existing keys: ${formatKeyList(existingKeys)}.`,
13
+ fix: "Split the input file by key state: update existing keys and add new keys separately.",
14
+ exitCode: 1,
15
+ nextSteps: splitFileNextSteps(filePath, resolved.scope, {
16
+ existingKeys,
17
+ first: "update-existing"
18
+ }),
19
+ meta: { keys: existingKeys }
20
+ });
21
+ const warnings = await missingPreviewDefaultWarnings(client, projectId, resolved.scope, assignments.map((assignment) => assignment.key), context.runtime.signal);
22
+ const variables = [];
23
+ for (const assignment of assignments) try {
24
+ const { data, error, response } = await client.POST("/v1/environment-variables", {
25
+ body: {
26
+ projectId,
27
+ class: resolved.apiTarget.class,
28
+ ...resolved.apiTarget.branchId !== null ? { branchId: resolved.apiTarget.branchId } : {},
29
+ key: assignment.key,
30
+ value: assignment.value
31
+ },
32
+ signal: context.runtime.signal
33
+ });
34
+ if (error || !data) throw apiCallError(`Failed to add ${assignment.key}`, response, error);
35
+ variables.push(toMetadata(data.data, resolved.descriptor));
36
+ } catch (error) {
37
+ throw envFileApplyFailedError("add", filePath, resolved.scope, assignment.key, variables, error);
38
+ }
39
+ return {
40
+ command: "project.env.add",
41
+ result: {
42
+ projectId,
43
+ scope: resolved.descriptor,
44
+ variables,
45
+ file: {
46
+ path: filePath,
47
+ count: variables.length
48
+ }
49
+ },
50
+ warnings,
51
+ nextSteps: []
52
+ };
53
+ }
54
+ async function runEnvUpdateFile(context, client, projectId, resolved, filePath, assignments) {
55
+ const existing = await findVariablesByNaturalKey(client, projectId, assignments.map((assignment) => assignment.key), resolved, context.runtime.signal);
56
+ const missingKeys = assignments.map((assignment) => assignment.key).filter((key) => !existing.has(key));
57
+ if (missingKeys.length > 0) throw new CliError({
58
+ code: "ENV_VARIABLE_NOT_FOUND",
59
+ domain: "app",
60
+ summary: `${missingKeys.length} environment variable(s) not found in ${formatScopeLabel(resolved.scope)}`,
61
+ why: `Missing keys: ${formatKeyList(missingKeys)}.`,
62
+ fix: "Split the input file by key state: add missing keys and update existing keys separately.",
63
+ exitCode: 1,
64
+ nextSteps: splitFileNextSteps(filePath, resolved.scope, {
65
+ missingKeys,
66
+ first: "add-missing"
67
+ }),
68
+ meta: { keys: missingKeys }
69
+ });
70
+ const variables = [];
71
+ for (const assignment of assignments) {
72
+ const existingVariable = existing.get(assignment.key);
73
+ if (!existingVariable) continue;
74
+ try {
75
+ const { data, error, response } = await client.PATCH("/v1/environment-variables/{envVarId}", {
76
+ params: { path: { envVarId: existingVariable.id } },
77
+ body: { value: assignment.value },
78
+ signal: context.runtime.signal
79
+ });
80
+ if (error || !data) throw apiCallError(`Failed to update value for ${assignment.key}`, response, error);
81
+ variables.push(toMetadata(data.data, resolved.descriptor));
82
+ } catch (error) {
83
+ throw envFileApplyFailedError("update", filePath, resolved.scope, assignment.key, variables, error);
84
+ }
85
+ }
86
+ return {
87
+ command: "project.env.update",
88
+ result: {
89
+ projectId,
90
+ scope: resolved.descriptor,
91
+ variables,
92
+ file: {
93
+ path: filePath,
94
+ count: variables.length
95
+ }
96
+ },
97
+ warnings: [],
98
+ nextSteps: []
99
+ };
100
+ }
101
+ async function findVariablesByNaturalKey(client, projectId, keys, resolved, signal) {
102
+ const found = /* @__PURE__ */ new Map();
103
+ for (const key of keys) {
104
+ const row = await findVariableByNaturalKey(client, projectId, key, resolved, signal);
105
+ if (row) found.set(key, row);
106
+ }
107
+ return found;
108
+ }
109
+ async function missingPreviewDefaultWarnings(client, projectId, scope, keys, signal) {
110
+ if (scope.kind !== "branch") return [];
111
+ const previewScope = {
112
+ scope: {
113
+ kind: "role",
114
+ role: "preview"
115
+ },
116
+ descriptor: {
117
+ kind: "role",
118
+ role: "preview"
119
+ },
120
+ apiTarget: {
121
+ class: "preview",
122
+ branchId: null
123
+ }
124
+ };
125
+ const missing = [];
126
+ for (const key of keys) if (!await findVariableByNaturalKey(client, projectId, key, previewScope, signal)) missing.push(key);
127
+ if (missing.length === 0) return [];
128
+ if (missing.length === 1) return [`Variable "${missing[0]}" does not exist in preview. It will only exist on ${formatScopeLabel(scope)}.`];
129
+ return [`Variables ${formatKeyList(missing)} do not exist in preview. They will only exist on ${formatScopeLabel(scope)}.`];
130
+ }
131
+ function envFileApplyFailedError(command, filePath, scope, failedKey, writtenVariables, error) {
132
+ const writtenKeys = writtenVariables.map((variable) => variable.key);
133
+ const cause = error instanceof CliError ? error.summary : error instanceof Error ? error.message : "Unknown error.";
134
+ return new CliError({
135
+ code: "ENV_FILE_APPLY_FAILED",
136
+ domain: "app",
137
+ summary: `Failed to ${command} "${failedKey}" from "${filePath}"`,
138
+ why: writtenKeys.length === 0 ? `No variables were written before ${failedKey} failed. Cause: ${cause}` : `Written keys before failure: ${formatKeyList(writtenKeys)}. Cause: ${cause}`,
139
+ fix: "Inspect the target scope, then retry the remaining keys once the API issue is resolved.",
140
+ exitCode: 1,
141
+ nextSteps: [`prisma-cli project env list ${formatScopeFlag(scope)}`, retryStepForApplyFailure(command, filePath, scope, writtenKeys)],
142
+ meta: {
143
+ file: filePath,
144
+ failedKey,
145
+ writtenKeys
146
+ }
147
+ });
148
+ }
149
+ function retryStepForApplyFailure(command, filePath, scope, writtenKeys) {
150
+ if (command === "update") return `prisma-cli project env update --file ${filePath} ${formatScopeFlag(scope)}`;
151
+ if (writtenKeys.length === 0) return `prisma-cli project env add --file ${filePath} ${formatScopeFlag(scope)}`;
152
+ return `prisma-cli project env add --file <remaining.env> ${formatScopeFlag(scope)}`;
153
+ }
154
+ function splitFileNextSteps(filePath, scope, options) {
155
+ const scopeFlag = formatScopeFlag(scope);
156
+ const existingFile = `${filePath}.existing`;
157
+ const newFile = `${filePath}.new`;
158
+ if (options.first === "update-existing") return [
159
+ `# existing keys: ${formatKeyList(options.existingKeys)}`,
160
+ `prisma-cli project env update --file ${existingFile} ${scopeFlag}`,
161
+ "# new keys only",
162
+ `prisma-cli project env add --file ${newFile} ${scopeFlag}`
163
+ ];
164
+ return [
165
+ `# missing keys: ${formatKeyList(options.missingKeys)}`,
166
+ `prisma-cli project env add --file ${newFile} ${scopeFlag}`,
167
+ "# existing keys only",
168
+ `prisma-cli project env update --file ${existingFile} ${scopeFlag}`
169
+ ];
170
+ }
171
+ function formatKeyList(keys) {
172
+ return keys.map((key) => `"${key}"`).join(", ");
173
+ }
174
+ function formatScopeFlag(scope) {
175
+ if (scope.kind === "role") return `--role ${scope.role}`;
176
+ return `--branch ${scope.branchName}`;
177
+ }
178
+ //#endregion
179
+ export { runEnvAddFile, runEnvUpdateFile };
@@ -5,29 +5,34 @@ import { readLocalGitBranch } from "../lib/git/local-branch.js";
5
5
  import { requireAuthenticatedAuthState } from "./auth.js";
6
6
  import { listRealWorkspaceProjects } from "./project.js";
7
7
  import { formatScopeLabel, parseKeyValuePositional, resolveEnvScope } from "../lib/app/env-config.js";
8
+ import { readEnvFileAssignments } from "../lib/app/env-file.js";
9
+ import { apiCallError, findVariableByNaturalKey, toMetadata } from "./app-env-api.js";
10
+ import { runEnvAddFile, runEnvUpdateFile } from "./app-env-file.js";
8
11
  //#region src/controllers/app-env.ts
9
12
  async function runEnvAdd(context, rawAssignment, flags) {
10
- const { key, value } = parseKeyValuePositional(rawAssignment, "add", context.runtime.env);
13
+ const source = resolveEnvWriteSource(rawAssignment, flags.filePath, "add");
11
14
  const scope = resolveEnvScope(flags, {
12
15
  requireExplicit: true,
13
16
  command: "add"
14
17
  });
15
- if (!scope) throw usageError(`prisma-cli project env add requires --role or --branch`, "Writing without an explicit scope is rejected.", "Pass --role production, --role preview, or --branch <git-name>.", [`prisma-cli project env add ${key}=${value} --role production`], "app");
18
+ if (!scope) throw usageError(`prisma-cli project env add requires --role or --branch`, "Writing without an explicit scope is rejected.", "Pass --role production, --role preview, or --branch <git-name>.", ["prisma-cli project env add KEY=value --role production"], "app");
19
+ const input = await resolveEnvWriteInput(context, source, "add");
16
20
  const { client, projectId } = await requireClientAndProject(context, flags.projectRef, "project env add");
17
21
  const resolved = await resolveScopeToApi(client, projectId, scope, {
18
22
  createBranchIfMissing: true,
19
23
  signal: context.runtime.signal
20
24
  });
21
- if (await findVariableByNaturalKey(client, projectId, key, resolved, context.runtime.signal)) throw new CliError({
25
+ if (input.kind === "file") return runEnvAddFile(context, client, projectId, resolved, input.filePath, input.assignments);
26
+ if (await findVariableByNaturalKey(client, projectId, input.key, resolved, context.runtime.signal)) throw new CliError({
22
27
  code: "ENV_VARIABLE_ALREADY_EXISTS",
23
28
  domain: "app",
24
- summary: `Variable "${key}" already exists in ${formatScopeLabel(scope)}`,
29
+ summary: `Variable "${input.key}" already exists in ${formatScopeLabel(scope)}`,
25
30
  why: "A variable with this key already exists in the targeted scope.",
26
31
  fix: "Use `prisma-cli project env update` to change an existing variable's value.",
27
32
  exitCode: 1,
28
- nextSteps: [`prisma-cli project env update ${key}=<new-value> ${formatScopeFlag(scope)}`]
33
+ nextSteps: [`prisma-cli project env update ${input.key}=<new-value> ${formatScopeFlag(scope)}`]
29
34
  });
30
- const warnings = scope.kind === "branch" && !await findVariableByNaturalKey(client, projectId, key, {
35
+ const warnings = scope.kind === "branch" && !await findVariableByNaturalKey(client, projectId, input.key, {
31
36
  scope: {
32
37
  kind: "role",
33
38
  role: "preview"
@@ -40,18 +45,18 @@ async function runEnvAdd(context, rawAssignment, flags) {
40
45
  class: "preview",
41
46
  branchId: null
42
47
  }
43
- }, context.runtime.signal) ? [`Variable "${key}" does not exist in preview. It will only exist on ${formatScopeLabel(scope)}.`] : [];
48
+ }, context.runtime.signal) ? [`Variable "${input.key}" does not exist in preview. It will only exist on ${formatScopeLabel(scope)}.`] : [];
44
49
  const { data, error, response } = await client.POST("/v1/environment-variables", {
45
50
  body: {
46
51
  projectId,
47
52
  class: resolved.apiTarget.class,
48
53
  ...resolved.apiTarget.branchId !== null ? { branchId: resolved.apiTarget.branchId } : {},
49
- key,
50
- value
54
+ key: input.key,
55
+ value: input.value
51
56
  },
52
57
  signal: context.runtime.signal
53
58
  });
54
- if (error || !data) throw apiCallError(`Failed to add ${key}`, response, error);
59
+ if (error || !data) throw apiCallError(`Failed to add ${input.key}`, response, error);
55
60
  return {
56
61
  command: "project.env.add",
57
62
  result: {
@@ -64,33 +69,35 @@ async function runEnvAdd(context, rawAssignment, flags) {
64
69
  };
65
70
  }
66
71
  async function runEnvUpdate(context, rawAssignment, flags) {
67
- const { key, value } = parseKeyValuePositional(rawAssignment, "update", context.runtime.env);
72
+ const source = resolveEnvWriteSource(rawAssignment, flags.filePath, "update");
68
73
  const scope = resolveEnvScope(flags, {
69
74
  requireExplicit: true,
70
75
  command: "update"
71
76
  });
72
- if (!scope) throw usageError(`prisma-cli project env update requires --role or --branch`, "Writing without an explicit scope is rejected.", "Pass --role production, --role preview, or --branch <git-name>.", [`prisma-cli project env update ${key}=${value} --role production`], "app");
77
+ if (!scope) throw usageError(`prisma-cli project env update requires --role or --branch`, "Writing without an explicit scope is rejected.", "Pass --role production, --role preview, or --branch <git-name>.", ["prisma-cli project env update KEY=value --role production"], "app");
78
+ const input = await resolveEnvWriteInput(context, source, "update");
73
79
  const { client, projectId } = await requireClientAndProject(context, flags.projectRef, "project env update");
74
80
  const resolved = await resolveScopeToApi(client, projectId, scope, {
75
81
  createBranchIfMissing: false,
76
82
  signal: context.runtime.signal
77
83
  });
78
- const existing = await findVariableByNaturalKey(client, projectId, key, resolved, context.runtime.signal);
84
+ if (input.kind === "file") return runEnvUpdateFile(context, client, projectId, resolved, input.filePath, input.assignments);
85
+ const existing = await findVariableByNaturalKey(client, projectId, input.key, resolved, context.runtime.signal);
79
86
  if (!existing) throw new CliError({
80
87
  code: "ENV_VARIABLE_NOT_FOUND",
81
88
  domain: "app",
82
- summary: `Variable "${key}" not found in ${formatScopeLabel(scope)}`,
89
+ summary: `Variable "${input.key}" not found in ${formatScopeLabel(scope)}`,
83
90
  why: "No variable with this key exists in the targeted scope.",
84
91
  fix: "Use `prisma-cli project env add` to create a new variable.",
85
92
  exitCode: 1,
86
- nextSteps: [`prisma-cli project env add ${key}=<value> ${formatScopeFlag(scope)}`]
93
+ nextSteps: [`prisma-cli project env add ${input.key}=<value> ${formatScopeFlag(scope)}`]
87
94
  });
88
95
  const { data, error, response } = await client.PATCH("/v1/environment-variables/{envVarId}", {
89
96
  params: { path: { envVarId: existing.id } },
90
- body: { value },
97
+ body: { value: input.value },
91
98
  signal: context.runtime.signal
92
99
  });
93
- if (error || !data) throw apiCallError(`Failed to update value for ${key}`, response, error);
100
+ if (error || !data) throw apiCallError(`Failed to update value for ${input.key}`, response, error);
94
101
  return {
95
102
  command: "project.env.update",
96
103
  result: {
@@ -102,6 +109,32 @@ async function runEnvUpdate(context, rawAssignment, flags) {
102
109
  nextSteps: []
103
110
  };
104
111
  }
112
+ function resolveEnvWriteSource(rawAssignment, filePath, command) {
113
+ if (filePath !== void 0 && rawAssignment !== void 0) throw usageError(`prisma-cli project env ${command} accepts either KEY=VALUE or --file`, "The command received both a positional assignment and a dotenv file path.", "Pass one input source.", [`prisma-cli project env ${command} KEY=value --role preview`, `prisma-cli project env ${command} --file .env --role preview`], "app");
114
+ if (filePath !== void 0) {
115
+ if (filePath.length === 0) throw usageError(`prisma-cli project env ${command} --file requires a path`, "The --file flag was passed without a file path.", "Pass a readable dotenv file path.", [`prisma-cli project env ${command} --file .env --role preview`], "app");
116
+ return {
117
+ kind: "file",
118
+ filePath
119
+ };
120
+ }
121
+ if (rawAssignment === void 0) throw usageError(`prisma-cli project env ${command} requires KEY=VALUE or --file`, "No environment variable input was supplied.", "Pass a single KEY=VALUE assignment or a dotenv file path.", [`prisma-cli project env ${command} KEY=value --role preview`, `prisma-cli project env ${command} --file .env --role preview`], "app");
122
+ return {
123
+ kind: "single",
124
+ rawAssignment
125
+ };
126
+ }
127
+ async function resolveEnvWriteInput(context, source, command) {
128
+ if (source.kind === "file") return {
129
+ kind: "file",
130
+ filePath: source.filePath,
131
+ assignments: await readEnvFileAssignments(context.runtime.cwd, source.filePath, command)
132
+ };
133
+ return {
134
+ kind: "single",
135
+ ...parseKeyValuePositional(source.rawAssignment, command, context.runtime.env)
136
+ };
137
+ }
105
138
  async function runEnvList(context, flags) {
106
139
  const explicit = resolveEnvScope(flags, {
107
140
  requireExplicit: false,
@@ -410,18 +443,6 @@ async function projectHasDefaultBranch(client, projectId, signal) {
410
443
  cursor = result.data.pagination.nextCursor;
411
444
  }
412
445
  }
413
- async function findVariableByNaturalKey(client, projectId, key, resolved, signal) {
414
- const { data, error, response } = await client.GET("/v1/environment-variables", {
415
- params: { query: {
416
- projectId,
417
- class: resolved.apiTarget.class,
418
- key
419
- } },
420
- signal
421
- });
422
- if (error || !data) throw apiCallError(`Failed to look up ${key}`, response, error);
423
- return data.data.filter((row) => rowMatchesExactScope(row, resolved))[0] ?? null;
424
- }
425
446
  async function listVariables(client, projectId, resolved, signal) {
426
447
  return materializeEffectiveRows(await collectEnvironmentVariables(client, projectId, signal, {
427
448
  className: resolved.apiTarget.class,
@@ -461,9 +482,6 @@ function rowMatchesScope(row, resolved) {
461
482
  if (resolved.apiTarget.branchId === null) return row.branchId === null;
462
483
  return row.branchId === null || row.branchId === resolved.apiTarget.branchId;
463
484
  }
464
- function rowMatchesExactScope(row, resolved) {
465
- return row.class === resolved.apiTarget.class && row.branchId === resolved.apiTarget.branchId;
466
- }
467
485
  function materializeEffectiveRows(rows, resolved) {
468
486
  if (resolved.apiTarget.branchId === null) return rows;
469
487
  const byKey = /* @__PURE__ */ new Map();
@@ -471,40 +489,5 @@ function materializeEffectiveRows(rows, resolved) {
471
489
  for (const row of rows) if (row.branchId === resolved.apiTarget.branchId) byKey.set(row.key, row);
472
490
  return [...byKey.values()].sort((left, right) => left.key.localeCompare(right.key));
473
491
  }
474
- function toMetadata(row, requestedScope) {
475
- const rowScope = row.branchId === null ? {
476
- kind: "role",
477
- role: row.class
478
- } : requestedScope;
479
- return {
480
- id: row.id,
481
- key: row.key,
482
- scope: rowScope,
483
- source: formatDescriptorLabel(rowScope),
484
- isManagedBySystem: row.isManagedBySystem,
485
- updatedAt: row.updatedAt
486
- };
487
- }
488
- function formatDescriptorLabel(scope) {
489
- if (scope.kind === "role") return scope.role ?? "unknown";
490
- if (scope.kind === "overview") return "overview";
491
- return `branch:${scope.branchName ?? scope.branchId ?? "unknown"}`;
492
- }
493
- function apiCallError(summary, response, error) {
494
- const status = response?.status ?? 0;
495
- const apiCode = error?.error?.code;
496
- const apiMessage = error?.error?.message;
497
- const apiHint = error?.error?.hint;
498
- if (status === 401 || status === 403) return authRequiredError(["prisma auth login"]);
499
- return new CliError({
500
- code: apiCode ?? "ENV_API_ERROR",
501
- domain: "app",
502
- summary,
503
- why: apiMessage ?? `The Management API returned status ${status || "unknown"}.`,
504
- fix: apiHint ?? "Re-run with --trace for the underlying API response details.",
505
- exitCode: 1,
506
- nextSteps: []
507
- });
508
- }
509
492
  //#endregion
510
493
  export { runEnvAdd, runEnvList, runEnvRemove, runEnvUpdate };
@@ -19,6 +19,7 @@ import { promptForProjectSetupChoice } from "../lib/project/interactive-setup.js
19
19
  import { readLocalGitBranch } from "../lib/git/local-branch.js";
20
20
  import { PREVIEW_BUILD_TYPES, RESOLVED_PREVIEW_BUILD_TYPES, executePreviewBuild } from "../lib/app/preview-build.js";
21
21
  import { PREVIEW_DEFAULT_REGION } from "../lib/app/preview-interaction.js";
22
+ import { maybeSetupBranchDatabase } from "../lib/app/branch-database-deploy.js";
22
23
  import { createPreviewDeployProgress, createPreviewDeployProgressState, createPreviewPromoteProgress } from "../lib/app/preview-progress.js";
23
24
  import { PreviewDomainApiError, createPreviewAppProvider } from "../lib/app/preview-provider.js";
24
25
  import { enforceProductionDeployGate } from "../lib/app/production-deploy-gate.js";
@@ -170,6 +171,10 @@ async function runAppDeploy(context, appName, options) {
170
171
  assertSupportedEntrypoint(buildType, options?.entrypoint, "deploy");
171
172
  const entrypoint = await resolveDeployEntrypoint(context.runtime.cwd, framework, options?.entrypoint, context.runtime.signal);
172
173
  const portMapping = parseDeployPortMapping(String(runtime.port));
174
+ const branchDatabaseSetup = await maybeSetupBranchDatabase(context, provider, projectId, toBranchDatabaseDeployBranch(target.branch), {
175
+ db: options?.db,
176
+ inlineEnvVars: envVars
177
+ });
173
178
  const progressState = createPreviewDeployProgressState();
174
179
  const deployStartedAt = Date.now();
175
180
  const deployResult = await provider.deployApp({
@@ -200,8 +205,9 @@ async function runAppDeploy(context, appName, options) {
200
205
  result: {
201
206
  workspace: target.workspace,
202
207
  project: target.project,
203
- branch: target.branch,
208
+ branch: toResultBranch(target.branch),
204
209
  resolution: target.resolution,
210
+ branchDatabase: branchDatabaseSetup.result,
205
211
  app: {
206
212
  id: deployResult.app.id,
207
213
  name: deployResult.app.name
@@ -210,7 +216,7 @@ async function runAppDeploy(context, appName, options) {
210
216
  durationMs: deployDurationMs,
211
217
  localPin: localPinResult
212
218
  },
213
- warnings: [],
219
+ warnings: branchDatabaseSetup.warnings,
214
220
  nextSteps: ["prisma-cli app list-deploys", `prisma-cli app show-deploy ${deployResult.deployment.id}`]
215
221
  };
216
222
  }
@@ -757,7 +763,7 @@ async function resolveAppDomainTarget(context, options, commandName = "app domai
757
763
  resultTarget: {
758
764
  workspace: target.workspace,
759
765
  project: target.project,
760
- branch: target.branch,
766
+ branch: toResultBranch(target.branch),
761
767
  app: {
762
768
  id: selectedApp.id,
763
769
  name: selectedApp.name
@@ -1320,6 +1326,7 @@ async function resolveProjectContext(context, client, explicitProject, options)
1320
1326
  return {
1321
1327
  ...resolved,
1322
1328
  branch: {
1329
+ id: null,
1323
1330
  name: branch.name,
1324
1331
  kind: toBranchKind(branch.name)
1325
1332
  }
@@ -1446,6 +1453,7 @@ async function withRemoteDeployBranch(provider, target, branch, signal) {
1446
1453
  return {
1447
1454
  ...target,
1448
1455
  branch: {
1456
+ id: remoteBranch.id,
1449
1457
  name: remoteBranch.name,
1450
1458
  kind: remoteBranch.role
1451
1459
  }
@@ -1454,6 +1462,20 @@ async function withRemoteDeployBranch(provider, target, branch, signal) {
1454
1462
  function toBranchKind(name) {
1455
1463
  return name === "production" || name === "main" ? "production" : "preview";
1456
1464
  }
1465
+ function toResultBranch(branch) {
1466
+ return {
1467
+ name: branch.name,
1468
+ kind: branch.kind
1469
+ };
1470
+ }
1471
+ function toBranchDatabaseDeployBranch(branch) {
1472
+ if (!branch.id) throw new Error(`Deploy branch "${branch.name}" was not resolved remotely.`);
1473
+ return {
1474
+ id: branch.id,
1475
+ name: branch.name,
1476
+ kind: branch.kind
1477
+ };
1478
+ }
1457
1479
  function assertExclusiveDeployProjectInputs(options) {
1458
1480
  const provided = [
1459
1481
  options.projectRef ? "--project" : null,