-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.ts
More file actions
5067 lines (4670 loc) · 142 KB
/
Copy pathapp.ts
File metadata and controls
5067 lines (4670 loc) · 142 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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { access, readFile } from "node:fs/promises";
import path from "node:path";
import type { PortMapping, StreamRecord } from "@prisma/compute-sdk";
import {
COMPUTE_REGIONS,
type ComputeFramework,
type ConfigBackedBuildType,
ENTRYPOINT_BUILD_TYPES,
FRAMEWORKS,
type FrameworkBuildType,
type FrameworkDescriptor,
frameworkByKey,
frameworkFromAlias,
isConfigBackedBuildType,
LOCAL_DEV_BUILD_TYPES,
} from "@prisma/compute-sdk/config";
import type { ManagementApiClient } from "@prisma/management-api-sdk";
import { matchError, Result } from "better-result";
import open from "open";
import { FileTokenStorage } from "../adapters/token-storage";
import { DEFAULT_REGION } from "../lib/app/app-interaction";
import {
type AppRecord,
createAppProvider,
DomainApiError,
type DomainRecord,
} from "../lib/app/app-provider";
import {
type BranchDatabaseDeployBranch,
maybeSetupBranchDatabase,
} from "../lib/app/branch-database-deploy";
import {
APP_BUILD_TYPE_LABELS,
APP_BUILD_TYPES,
type AppBuildSettings,
type AppBuildSettingsResolution,
type AppBuildType,
detectLegacyBuildSettings,
executeAppBuild,
PRISMA_APP_CONFIG_FILENAME,
RESOLVED_APP_BUILD_TYPES,
resolveConfiguredAppBuildSettings,
resolveInferredAppBuildSettings,
} from "../lib/app/build";
import {
type BunPackageJsonLike,
readBunPackageEntrypoint,
readBunPackageJson,
} from "../lib/app/bun-project";
import {
COMPUTE_CONFIG_FILENAME,
type ComputeConfigCommandName,
ComputeConfigTargetRequiredError,
type ComputeDeployTarget,
computeConfigErrorToCliError,
computeFrameworkToBuildType,
computeTargetAppDir,
inferComputeTargetFromCwd,
type LoadedComputeConfig,
loadComputeConfig,
type MergedDeployInput,
mergeComputeDeployInputs,
mergeComputeLocalInputs,
selectComputeDeployTarget,
} from "../lib/app/compute-config";
import {
renderDeployOutputRows,
renderDeploySettingsPreview,
} from "../lib/app/deploy-output";
import {
describeDeployAllFailure,
type PlannedDeployTarget,
perAppInputsForDeployAll,
planAppDeploy,
} from "../lib/app/deploy-plan";
import {
createDeployProgress,
createDeployProgressState,
createPromoteProgress,
type DeployProgressState,
} from "../lib/app/deploy-progress";
import { formatDomainFailureFix } from "../lib/app/domain-guidance";
import { envVarNames, parseEnvInputs } from "../lib/app/env-vars";
import {
DEFAULT_LOCAL_DEV_PORT,
type LocalBuildType,
runLocalApp,
} from "../lib/app/local-dev";
import { enforceProductionDeployGate } from "../lib/app/production-deploy-gate";
import { resolveReadBranch } from "../lib/app/read-branch";
import { readAuthState } from "../lib/auth/auth-ops";
import { getApiBaseUrl, SERVICE_TOKEN_ENV_VAR } from "../lib/auth/client";
import { requireComputeAuth } from "../lib/auth/guard";
import { readLocalGitBranch } from "../lib/git/local-branch";
import { promptForProjectSetupChoice } from "../lib/project/interactive-setup";
import {
LOCAL_RESOLUTION_PIN_RELATIVE_PATH,
type LocalResolutionPinReadError,
type LocalResolutionPinReadResult,
readLocalResolutionPin,
} from "../lib/project/local-pin";
import {
buildProjectSetupNextActions,
type InferredTargetName,
inferTargetName,
localProjectWorkspaceMismatchError,
type ProjectCandidate,
projectNotFoundError,
projectResolutionErrorToCliError,
resolveDurablePlatformMapping,
resolveProjectTarget,
sortProjects,
} from "../lib/project/resolution";
import {
bindProjectToDirectory,
formatCommandArgument,
projectCreateFailedError,
projectDirectoryBindingErrorToCliError,
projectSetupNameRequiredError,
resolveProjectForSetup,
toProjectSummary,
} from "../lib/project/setup";
import {
authRequiredError,
CliError,
featureUnavailableError,
usageError,
workspaceRequiredError,
} from "../shell/errors";
import { type CommandSuccess, writeJsonEvent } from "../shell/output";
import { confirmPrompt, selectPrompt, textPrompt } from "../shell/prompt";
import { type CommandContext, canPrompt } from "../shell/runtime";
import { renderCommandHeader } from "../shell/ui";
import type {
AppBuildResult,
AppDeployAllResult,
AppDeploymentSummary,
AppDeployResult,
AppDomainAddResult,
AppDomainDnsRecord,
AppDomainRemoveResult,
AppDomainRetryResult,
AppDomainShowResult,
AppDomainStatus,
AppDomainSummary,
AppDomainTarget,
AppListDeploysResult,
AppOpenResult,
AppPromoteResult,
AppRemoveResult,
AppResolvedContext,
AppRollbackResult,
AppRunResult,
AppShowDeployResult,
AppShowResult,
} from "../types/app";
import type { AuthWorkspace } from "../types/auth";
import type { BranchKind } from "../types/branch";
import type { ProjectResolution, ProjectSummary } from "../types/project";
import { maybePromptForAgentSetup } from "./agent-setup";
import { requireAuthenticatedAuthState } from "./auth";
import { listRealWorkspaceProjects } from "./project";
import { createSelectPromptPort } from "./select-prompt-port";
type AppDomainCommand = "add" | "show" | "remove" | "retry" | "wait";
const FRAMEWORK_DEFAULT_HTTP_PORT = 3000;
const PRISMA_PROJECT_ID_ENV_VAR = "PRISMA_PROJECT_ID";
const PRISMA_APP_ID_ENV_VAR = "PRISMA_APP_ID";
const COMPUTE_REGION_IDS = new Set<string>(COMPUTE_REGIONS);
function isRealMode(context: CommandContext): boolean {
return (
!context.runtime.fixturePath &&
!context.runtime.env.PRISMA_CLI_MOCK_FIXTURE_PATH
);
}
export async function runAppBuild(
context: CommandContext,
options?: {
entrypoint?: string;
buildType?: string;
configTarget?: string;
},
): Promise<CommandSuccess<AppBuildResult>> {
const compute = await resolveComputeTargetOrThrow(
context,
options?.configTarget,
"build",
);
const merged = mergeComputeLocalInputs({
cli: { entrypoint: options?.entrypoint, buildType: options?.buildType },
target: compute.target,
});
const appDir = await resolveComputeAppDir(context, compute);
let buildType = normalizeBuildType(merged.buildType);
if (compute.target?.build && buildType === "auto") {
// A committed build block must never be silently ignored, so resolve the
// framework the same way deploy does instead of deferring to the
// strategy's auto detection.
const detected = await detectDeployFramework(
appDir,
context.runtime.signal,
);
if (!detected) {
throw frameworkNotDetectedError(appDir);
}
buildType = detected.buildType;
}
assertSupportedEntrypoint(buildType, merged.entrypoint, "build");
if (compute.target?.build && buildType !== "auto") {
assertConfigBackedBuildSettings(buildType);
}
// Config-owned build settings apply when the build type is determinate;
// auto detection resolves inside the strategy and keeps its own fallback.
const buildSettings =
compute.config &&
compute.target?.build &&
isConfigBackedBuildType(buildType)
? (
await resolveConfiguredAppBuildSettings({
appPath: appDir,
buildType,
configured: compute.target.build,
configPath: compute.config.configPath,
signal: context.runtime.signal,
})
).settings
: undefined;
try {
const { artifact, buildType: actualBuildType } = await executeAppBuild({
appPath: appDir,
entrypoint: merged.entrypoint,
buildType,
buildSettings,
signal: context.runtime.signal,
});
return {
command: "app.build",
result: {
directory: artifact.directory,
entrypoint: artifact.entrypoint,
buildType: actualBuildType,
},
warnings: [],
nextSteps: ["prisma-cli app deploy"],
};
} catch (error) {
if (buildType === "auto" && isAutoBuildDetectionError(error)) {
throw usageError(
"App build requires an explicit framework when detection is ambiguous",
`This preview auto-detects clear project shapes for ${RESOLVED_APP_BUILD_TYPES.map(formatBuildTypeName).join(", ")}.`,
"Pass a supported --build-type value, or pass --entry <path> for a Bun app.",
getBuildTypeExamples("build"),
"app",
);
}
throw buildFailedError("Local app build failed", error);
}
}
export async function runAppRun(
context: CommandContext,
options?: {
entrypoint?: string;
buildType?: string;
port?: string;
configTarget?: string;
},
): Promise<CommandSuccess<AppRunResult>> {
if (context.flags.json) {
throw usageError(
"App run does not support --json",
"This command streams the framework dev server directly and cannot return structured JSON.",
"Rerun without --json to pass framework logs through directly.",
["prisma-cli app run"],
"app",
);
}
const compute = await resolveComputeTargetOrThrow(
context,
options?.configTarget,
"run",
);
const merged = mergeComputeLocalInputs({
cli: {
entrypoint: options?.entrypoint,
buildType: options?.buildType,
port: options?.port,
},
target: compute.target,
});
if (
merged.buildTypeFromConfig &&
compute.target?.framework &&
!frameworkByKey(compute.target.framework).hasLocalDevServer
) {
throw usageError(
`App run does not support the ${compute.target?.framework} framework yet`,
`${compute.config?.relativeConfigPath ?? COMPUTE_CONFIG_FILENAME} sets a framework that has no local dev server in the current preview.`,
"Run the framework dev server directly, or pass --build-type nextjs or --build-type bun to override.",
[
"prisma-cli app run --build-type nextjs",
"prisma-cli app run --build-type bun --entry server.ts",
],
"app",
);
}
const appDir = await resolveComputeAppDir(context, compute);
const buildType = normalizeBuildType(merged.buildType);
assertSupportedEntrypoint(buildType, merged.entrypoint, "run");
const port = parseLocalPort(merged.port);
const framework = await resolveLocalRunFramework(context, {
requestedBuildType: buildType,
configFramework: compute.target?.framework ?? null,
appDir,
entrypoint: merged.entrypoint,
});
// Hono apps get the same src/index.ts entrypoint default as deploy.
const entrypoint =
framework.buildType === "bun"
? await resolveDeployEntrypoint(
appDir,
framework,
merged.entrypoint,
context.runtime.signal,
)
: merged.entrypoint;
let runResult: Awaited<ReturnType<typeof runLocalApp>>;
try {
runResult = await runLocalApp({
appPath: appDir,
buildType: framework.buildType as LocalBuildType,
entrypoint,
port,
env: context.runtime.env,
signal: context.runtime.signal,
});
} catch (error) {
throw runFailedError("Local app run failed", error);
}
if (runResult.signal === "SIGINT" || runResult.signal === "SIGTERM") {
throw new DOMException("Command canceled", "AbortError");
} else if (runResult.exitCode !== 0) {
throw runFailedError(
"Local app run failed",
`The ${formatFrameworkName(runResult.framework)} process exited with code ${runResult.exitCode}.`,
runResult.exitCode,
);
}
return {
command: "app.run",
result: {
framework: runResult.framework,
entrypoint: runResult.entrypoint,
port: runResult.port,
command: runResult.command,
},
warnings: [],
nextSteps: [],
};
}
interface AppDeployOptions {
projectRef?: string;
createProjectName?: string;
branchName?: string;
entrypoint?: string;
framework?: string;
httpPort?: string;
region?: string;
envAssignments?: string[];
prod?: boolean;
noPromote?: boolean;
db?: boolean;
configTarget?: string;
}
export async function runAppDeploy(
context: CommandContext,
appName: string | undefined,
options?: AppDeployOptions,
): Promise<CommandSuccess<AppDeployResult | AppDeployAllResult>> {
ensurePreviewAppMode(context);
const loaded = await loadComputeConfig(
context.runtime.cwd,
context.runtime.signal,
);
if (loaded.isErr()) {
throw computeConfigErrorToCliError(loaded.error, "deploy");
}
const config = loaded.value;
const requestedTarget =
options?.configTarget ??
(config
? inferComputeTargetFromCwd(config, context.runtime.cwd)
: undefined);
const plan = planAppDeploy({
config,
requestedTarget,
hasCreateProject: options?.createProjectName !== undefined,
});
if (plan.mode === "all") {
// config is non-null and multi-app whenever the planner schedules a run.
return runAppDeployAll(
context,
config as LoadedComputeConfig,
plan.targets,
appName,
options,
);
}
return runSingleAppDeploy(context, appName, options, config);
}
async function runAppDeployAll(
context: CommandContext,
config: LoadedComputeConfig,
plannedTargets: PlannedDeployTarget[],
appName: string | undefined,
options?: AppDeployOptions,
): Promise<CommandSuccess<AppDeployAllResult>> {
assertNoPerAppInputsForDeployAll(context, plannedTargets, appName, options);
const deployments: AppDeployAllResult["deployments"] = [];
const warnings: string[] = [];
for (const planned of plannedTargets) {
maybeRenderDeployAllTargetHeader(context, planned);
// --create-project binds once: after the first target writes the local
// pin, the rest resolve the Project (and its --db branch database) through
// it, so the branch database is created once for the whole run.
const targetOptions: AppDeployOptions = {
...options,
configTarget: planned.targetKey,
createProjectName: planned.bindsCreateProject
? options?.createProjectName
: undefined,
};
try {
// biome-ignore lint/performance/noAwaitInLoops: deploy-all must run in order so --create-project writes the local project pin before later targets resolve it.
const single = await runSingleAppDeploy(
context,
undefined,
targetOptions,
config,
);
deployments.push({ target: planned.targetKey, result: single.result });
warnings.push(...single.warnings);
} catch (error) {
throw deployAllFailedError(
error,
plannedTargets,
planned.index,
deployments,
);
}
}
return {
command: "app.deploy",
result: { deployments },
warnings,
// Bare list-deploys follows the remembered selection (the last target
// deployed), so the multi-app suggestion must name a target.
nextSteps: ["prisma-cli app list-deploys <app>"],
};
}
function assertNoPerAppInputsForDeployAll(
context: CommandContext,
plannedTargets: PlannedDeployTarget[],
appName: string | undefined,
options?: AppDeployOptions,
): void {
const used = perAppInputsForDeployAll({
appName,
framework: options?.framework,
entrypoint: options?.entrypoint,
httpPort: options?.httpPort,
region: options?.region,
envAssignments: options?.envAssignments,
appIdEnvVar: {
name: PRISMA_APP_ID_ENV_VAR,
value: readDeployEnvOverride(context, PRISMA_APP_ID_ENV_VAR),
},
});
if (used.length === 0) {
return;
}
const targetKeys = plannedTargets.map((target) => target.targetKey);
throw usageError(
`Deploying all apps does not accept ${used.join(", ")}`,
`Without a target, app deploy deploys every configured app (${targetKeys.join(", ")}), so per-app inputs are ambiguous.`,
"Pass the app target to apply per-app inputs to one app, or remove them to deploy all apps.",
targetKeys.map((target) => `prisma-cli app deploy ${target}`),
"app",
);
}
function maybeRenderDeployAllTargetHeader(
context: CommandContext,
planned: PlannedDeployTarget,
): void {
if (context.flags.json || context.flags.quiet) {
return;
}
context.output.stderr.write(
`${planned.index > 0 ? "\n" : ""}── ${planned.targetKey} (${planned.index + 1}/${planned.total}) ──\n\n`,
);
}
function deployAllFailedError(
error: unknown,
plannedTargets: PlannedDeployTarget[],
failedIndex: number,
deployments: AppDeployAllResult["deployments"],
): unknown {
if (!(error instanceof CliError)) {
return error;
}
const failure = describeDeployAllFailure({
targetKeys: plannedTargets.map((target) => target.targetKey),
failedIndex,
completed: deployments.map(({ target, result }) => ({
target,
deploymentId: result.deployment.id,
url: result.deployment.url,
})),
});
const contextSentence = failure.contextLines.join(" ");
return new CliError({
code: error.code,
domain: error.domain,
summary: error.summary,
// The deploy-all context renders through whichever path the original
// error uses: appended to humanLines when they replace the structured
// rendering, folded into `why` otherwise.
why: error.humanLines
? error.why
: [error.why, contextSentence].filter(Boolean).join(" "),
fix: error.fix,
debug: error.debug,
where: error.where,
meta: {
...error.meta,
deployAll: {
failedTarget: failure.failedTarget,
completed: failure.completed,
notAttempted: failure.notAttempted,
},
},
docsUrl: error.docsUrl,
exitCode: error.exitCode,
nextSteps: error.nextSteps,
nextActions: error.nextActions,
humanLines: error.humanLines
? [...error.humanLines, "", ...failure.contextLines]
: undefined,
});
}
async function runSingleAppDeploy(
context: CommandContext,
appName: string | undefined,
options: AppDeployOptions | undefined,
preloadedConfig: LoadedComputeConfig | null,
): Promise<CommandSuccess<AppDeployResult>> {
const envProjectId = readDeployEnvOverride(
context,
PRISMA_PROJECT_ID_ENV_VAR,
);
const envAppId = readDeployEnvOverride(context, PRISMA_APP_ID_ENV_VAR);
assertExclusiveDeployProjectInputs({
projectRef: options?.projectRef,
createProjectName: options?.createProjectName,
envProjectId,
});
const computeConfig = await resolveComputeTargetOrThrow(
context,
options?.configTarget,
"deploy",
{
preloaded: preloadedConfig,
},
);
const merged = mergeComputeDeployInputs({
cli: {
framework: options?.framework,
entrypoint: options?.entrypoint,
httpPort: options?.httpPort,
region: options?.region,
envInputs: options?.envAssignments,
},
target: computeConfig.target,
configFilename:
computeConfig.config?.relativeConfigPath ?? COMPUTE_CONFIG_FILENAME,
});
const appDir = await resolveComputeAppDir(context, computeConfig);
// The compute config marks the project root: the Project binding and other
// repo-level concerns live next to the config, not wherever deploy ran.
const projectDir = computeConfig.config?.configDir ?? context.runtime.cwd;
const agentSetupWarnings = await maybePromptForAgentSetup(
context,
projectDir,
);
const skipLocalPin = Boolean(
envProjectId || options?.projectRef || options?.createProjectName,
);
const localPinReadResult = skipLocalPin
? Result.ok({ kind: "missing" } satisfies LocalResolutionPinReadResult)
: await readLocalResolutionPin(projectDir, context.runtime.signal);
if (localPinReadResult.isErr()) {
throw localPinReadErrorToDeployError(localPinReadResult.error);
}
const localPin = localPinReadResult.value;
const branch = await resolveDeployBranch(context, options?.branchName);
if (merged.httpPort) {
parseDeployHttpPort(merged.httpPort.value);
}
const deployRegion = normalizeDeployRegionInput(merged.region);
assertSupportedEntrypointForRequestedDeployShape({
requestedFramework: merged.framework?.value,
entrypoint: merged.entrypoint?.value,
});
const { provider, target, projectId } =
await requireProviderAndDeployProjectContext(context, options?.projectRef, {
branch,
createProjectName: options?.createProjectName,
envProjectId,
localPin,
});
let localPinResult: { path: string; written: true } | undefined;
if (target.localPinAction) {
const setupResult = await bindProjectToDirectory(
context,
target.workspace,
target.project,
target.localPinAction,
projectDir,
);
if (setupResult.isErr()) {
throw projectDirectoryBindingErrorToCliError(setupResult.error);
}
const projectSetup = setupResult.value;
localPinResult = projectSetup.localPin;
maybeRenderProjectLinked(
context,
projectSetup.directory,
projectSetup.project.name,
projectSetup.localPin.path,
);
}
let framework = await resolveDeployFramework(context, {
requestedFramework: merged.framework?.value,
requestedFrameworkAnnotation: merged.framework?.annotation,
entrypoint: merged.entrypoint?.value,
entrypointAnnotation: merged.entrypoint?.annotation,
appDir,
});
let runtime = resolveDeployRuntime(
merged.httpPort?.value,
merged.httpPort?.annotation,
framework,
);
assertSupportedEntrypoint(
framework.buildType,
merged.entrypoint?.value,
"deploy",
);
const envVars = toOptionalEnvVars(
// Config env file paths resolve from the config directory; --env flag
// paths resolve from where the command ran.
await parseEnvInputs(
merged.envInputsFromConfig ? projectDir : context.runtime.cwd,
merged.envInputs,
{
commandName: "deploy",
},
),
);
const apps = await listApps(context, provider, projectId, target.branch.name);
const selectedApp = await resolveDeployAppSelection(
context,
projectId,
apps,
{
explicitAppName: appName,
explicitAppId: envAppId,
configAppName: merged.configAppName,
configRegion: deployRegion,
firstDeploy: Boolean(target.localPinAction),
inferName: () => inferTargetName(appDir, context.runtime.signal),
},
);
await maybeRenderDeploySetupBlock(context, {
includeDirectory: !target.localPinAction,
appDir,
projectName: target.project.name,
branchName: target.branch.name,
appName: selectedApp.displayName,
});
const customized = await maybeCustomizeDeploySettings(context, {
framework,
runtime,
firstDeploy: selectedApp.firstDeploy,
explicitFramework: Boolean(merged.framework),
explicitEntrypoint: Boolean(merged.entrypoint),
explicitHttpPort: Boolean(merged.httpPort),
});
framework = customized.framework;
runtime = customized.runtime;
const noPromote = options?.noPromote === true;
// A promotionless deploy never replaces the live deployment, so the
// production-confirmation gate does not apply: --no-promote on the production
// branch builds a candidate without --prod.
const productionDeployGate = noPromote
? { firstProductionDeploy: false }
: await enforceProductionDeployGate(context, provider, {
appId: selectedApp.appId,
appName: selectedApp.displayName,
branchKind: target.branch.kind,
prod: options?.prod === true,
});
// Customization can switch from a Bun-compatible framework to one that
// derives its entrypoint from build output, so validate --entry again after it.
const buildType = framework.buildType;
assertSupportedEntrypoint(buildType, merged.entrypoint?.value, "deploy");
const entrypoint = await resolveDeployEntrypoint(
appDir,
framework,
merged.entrypoint?.value,
context.runtime.signal,
);
const buildSettingsResolution = await resolveDeployBuildSettings({
computeConfig,
appDir,
buildType,
signal: context.runtime.signal,
});
const legacyWarnings = await handleLegacyBuildSettings(
context,
appDir,
buildSettingsResolution.settings,
);
maybeRenderDeployBuildSettings(context, buildSettingsResolution);
const portMapping = parseDeployPortMapping(String(runtime.port));
const branchDatabaseSetup = await maybeSetupBranchDatabase(
context,
provider,
projectId,
toBranchDatabaseDeployBranch(target.branch),
{
db: options?.db,
providedEnvVars: envVars,
firstProductionDeploy: productionDeployGate.firstProductionDeploy,
projectDir,
},
);
const progressState = createDeployProgressState();
const deployStartedAt = Date.now();
const deployResult = await provider
.deployApp({
cwd: appDir,
projectId,
branchName: target.branch.name,
appId: selectedApp.appId,
appName: selectedApp.appName,
region: selectedApp.region,
entrypoint,
buildType,
buildSettings: buildSettingsResolution.settings,
portMapping,
envVars,
skipPromote: noPromote,
interaction: undefined,
signal: context.runtime.signal,
progress: createDeployProgress(
context.output.stderr,
context.ui,
!context.flags.json && !context.flags.quiet,
progressState,
),
})
.catch((error) => {
throw appDeployFailedError(error, progressState);
});
const deployDurationMs = Date.now() - deployStartedAt;
await context.stateStore.setSelectedApp(projectId, {
id: deployResult.app.id,
name: deployResult.app.name,
});
// With --no-promote the live deployment is unchanged, so cache the actually-live
// id (never the un-promoted candidate); skip when the app has nothing live yet.
const knownLiveDeploymentId = deployResult.promoted
? deployResult.deployment.id
: deployResult.app.liveDeploymentId;
if (knownLiveDeploymentId) {
await context.stateStore.setKnownLiveDeployment(
projectId,
deployResult.app.id,
knownLiveDeploymentId,
);
}
return {
command: "app.deploy",
result: {
workspace: target.workspace,
project: target.project,
branch: toResultBranch(target.branch),
resolution: target.resolution,
branchDatabase: branchDatabaseSetup.result,
app: {
id: deployResult.app.id,
name: deployResult.app.name,
},
deployment: deployResult.deployment,
promoted: deployResult.promoted,
deploySettings: {
config: {
// The compute config in effect, even when it has no build block, so
// `path: null` means "no config loaded" rather than "no build-settings
// block". `status` still says whether the build block owned the
// build settings ("config") or they were inferred ("inferred").
path: computeConfig.config?.relativeConfigPath ?? null,
status: buildSettingsResolution.status,
},
buildCommand: {
value: buildSettingsResolution.settings.buildCommand,
source: buildSettingsResolution.settings.buildCommandSource,
},
outputDirectory: {
value: buildSettingsResolution.settings.outputDirectory,
source: buildSettingsResolution.settings.outputDirectorySource,
},
framework: {
key: framework.key,
buildType,
name: framework.displayName,
source: framework.annotation,
},
entrypoint:
entrypoint ?? buildSettingsResolution.settings.entrypoint ?? null,
httpPort: runtime.port,
region: deployResult.app.region ?? selectedApp.region ?? null,
envVars: envVarNames(envVars),
},
durationMs: deployDurationMs,
localPin: localPinResult,
},
warnings: [
...agentSetupWarnings,
...legacyWarnings,
...branchDatabaseSetup.warnings,
],
nextSteps: deployResult.promoted
? [
"prisma-cli app list-deploys",
`prisma-cli app show-deploy ${deployResult.deployment.id}`,
]
: [
`prisma-cli app promote ${deployResult.deployment.id}`,
`prisma-cli app show-deploy ${deployResult.deployment.id}`,
],
};
}
async function resolveDeployBuildSettings(options: {
computeConfig: {
config: LoadedComputeConfig | null;
target: ComputeDeployTarget | null;
};
appDir: string;
buildType: FrameworkBuildType;
signal: AbortSignal;
}): Promise<AppBuildSettingsResolution> {
const { computeConfig, appDir, buildType, signal } = options;
if (computeConfig.target?.build) {
assertConfigBackedBuildSettings(buildType);
}
// Build settings come from the compute config's build block over framework
// defaults; nothing is read from or written to disk for them.
if (
computeConfig.config &&
computeConfig.target?.build &&
isConfigBackedBuildType(buildType)
) {
return resolveConfiguredAppBuildSettings({
appPath: appDir,
buildType,
configured: computeConfig.target.build,
configPath: computeConfig.config.configPath,
signal,
});
}
return resolveInferredAppBuildSettings({
appPath: appDir,
buildType,
signal,
});
}
export async function runAppListDeploys(
context: CommandContext,
appName: string | undefined,
projectRef?: string,
configTarget?: string,
): Promise<CommandSuccess<AppListDeploysResult>> {
ensurePreviewAppMode(context);
const compute = await resolveComputeManagementContext(
context,
configTarget,
"list-deploys",
);
const { provider, target, projectId } =
await requireProviderAndProjectContext(context, projectRef, {
commandName: "app list-deploys",
projectDir: compute.projectDir,
});
const apps = await listApps(context, provider, projectId, target.branch.name);
const selectedApp = await resolveExistingAppSelection(
context,
projectId,
apps,
appName ?? compute.configAppName,
);
if (!selectedApp) {
return {
command: "app.list-deploys",
result: {
projectId,
verboseContext: toAppVerboseContext(target),
app: null,
deployments: [],
},
warnings: [],
nextSteps: ["prisma-cli app deploy"],
};
}
const deploymentsResult = await provider
.listDeployments(selectedApp.id, { signal: context.runtime.signal })
.catch((error) => {
throw deployFailedError("Failed to list app deployments", error, [
"prisma-cli app deploy",
]);
});
const currentLiveDeploymentId = await resolveCurrentLiveDeploymentId(
context,
projectId,
deploymentsResult.app,
deploymentsResult.deployments,
);
const deployments = applyLiveDeploymentHint(
deploymentsResult.deployments,
currentLiveDeploymentId,
)
.slice()
.sort(
(left, right) =>
right.createdAt.localeCompare(left.createdAt) ||
right.id.localeCompare(left.id),
);
await context.stateStore.setSelectedApp(projectId, {
id: deploymentsResult.app.id,
name: deploymentsResult.app.name,
});