-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathVercelSettingsPresenter.server.ts
More file actions
599 lines (556 loc) · 20.5 KB
/
VercelSettingsPresenter.server.ts
File metadata and controls
599 lines (556 loc) · 20.5 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
import { type PrismaClient } from "@trigger.dev/database";
import { type Result, fromPromise, ok, okAsync, ResultAsync } from "neverthrow";
import { env } from "~/env.server";
import { logger } from "~/services/logger.server";
import { OrgIntegrationRepository } from "~/models/orgIntegration.server";
import {
VercelIntegrationRepository,
VercelCustomEnvironment,
VercelEnvironmentVariable,
} from "~/models/vercelIntegration.server";
import { type GitHubAppInstallation } from "~/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.github";
import { EnvironmentVariablesRepository } from "~/v3/environmentVariables/environmentVariablesRepository.server";
import {
VercelProjectIntegrationDataSchema,
VercelProjectIntegrationData,
} from "~/v3/vercel/vercelProjectIntegrationSchema";
import { BasePresenter } from "./basePresenter.server";
type VercelSettingsOptions = {
projectId: string;
organizationId: string;
};
export type VercelSettingsResult = {
enabled: boolean;
hasOrgIntegration: boolean;
authInvalid?: boolean;
authError?: string;
connectedProject?: {
id: string;
vercelProjectId: string;
vercelProjectName: string;
vercelTeamId: string | null;
integrationData: VercelProjectIntegrationData;
createdAt: Date;
};
isGitHubConnected: boolean;
hasStagingEnvironment: boolean;
hasPreviewEnvironment: boolean;
customEnvironments: VercelCustomEnvironment[];
/** Whether autoAssignCustomDomains is enabled on the Vercel project. null if unknown. */
autoAssignCustomDomains?: boolean | null;
};
export type VercelAvailableProject = {
id: string;
name: string;
};
export type VercelOnboardingData = {
customEnvironments: VercelCustomEnvironment[];
environmentVariables: VercelEnvironmentVariable[];
availableProjects: VercelAvailableProject[];
hasProjectSelected: boolean;
authInvalid?: boolean;
authError?: string;
existingVariables: Record<string, { environments: string[] }>; // Environment slugs (non-archived only)
gitHubAppInstallations: GitHubAppInstallation[];
isGitHubConnected: boolean;
isOnboardingComplete: boolean;
};
export class VercelSettingsPresenter extends BasePresenter {
/**
* Get Vercel integration settings for the settings page
*/
public async call({ projectId, organizationId }: VercelSettingsOptions): Promise<Result<VercelSettingsResult, unknown>> {
const vercelIntegrationEnabled = OrgIntegrationRepository.isVercelSupported;
if (!vercelIntegrationEnabled) {
return ok({
enabled: false,
hasOrgIntegration: false,
authInvalid: false,
connectedProject: undefined,
isGitHubConnected: false,
hasStagingEnvironment: false,
hasPreviewEnvironment: false,
customEnvironments: [],
} as VercelSettingsResult);
}
const orgIntegrationResult = await fromPromise(
(this._replica as PrismaClient).organizationIntegration.findFirst({
where: {
organizationId,
service: "VERCEL",
deletedAt: null,
},
include: {
tokenReference: true,
},
}),
(error) => error
);
if (orgIntegrationResult.isErr()) {
logger.error("Unexpected error in VercelSettingsPresenter.call", { error: orgIntegrationResult.error });
return ok({
enabled: true,
hasOrgIntegration: false,
authInvalid: true,
authError: orgIntegrationResult.error instanceof Error ? orgIntegrationResult.error.message : "Failed to fetch organization integration",
connectedProject: undefined,
isGitHubConnected: false,
hasStagingEnvironment: false,
hasPreviewEnvironment: false,
customEnvironments: [],
} as VercelSettingsResult);
}
const orgIntegration = orgIntegrationResult.value;
const hasOrgIntegration = orgIntegration !== null;
if (hasOrgIntegration) {
const tokenResult = await VercelIntegrationRepository.validateVercelToken(orgIntegration);
if (tokenResult.isErr() || !tokenResult.value.isValid) {
return ok({
enabled: true,
hasOrgIntegration: true,
authInvalid: true,
authError: tokenResult.isErr() ? tokenResult.error.message : "Vercel token is invalid",
connectedProject: undefined,
isGitHubConnected: false,
hasStagingEnvironment: false,
hasPreviewEnvironment: false,
customEnvironments: [],
} as VercelSettingsResult);
}
}
const checkOrgIntegration = () => fromPromise(
Promise.resolve(hasOrgIntegration),
(error) => ({
type: "other" as const,
cause: error,
})
);
const checkGitHubConnection = () =>
fromPromise(
(this._replica as PrismaClient).connectedGithubRepository.findFirst({
where: {
projectId,
repository: {
installation: {
deletedAt: null,
suspendedAt: null,
},
},
},
select: {
id: true,
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).map((repo) => repo !== null);
const checkStagingEnvironment = () =>
fromPromise(
(this._replica as PrismaClient).runtimeEnvironment.findFirst({
select: {
id: true,
},
where: {
projectId,
type: "STAGING",
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).map((env) => env !== null);
const checkPreviewEnvironment = () =>
fromPromise(
(this._replica as PrismaClient).runtimeEnvironment.findFirst({
select: {
id: true,
},
where: {
projectId,
type: "PREVIEW",
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).map((env) => env !== null);
const getVercelProjectIntegration = () =>
fromPromise(
(this._replica as PrismaClient).organizationProjectIntegration.findFirst({
where: {
projectId,
deletedAt: null,
organizationIntegration: {
service: "VERCEL",
deletedAt: null,
},
},
include: {
organizationIntegration: true,
},
}),
(error) => ({
type: "other" as const,
cause: error,
})
).map((integration) => {
if (!integration) {
return undefined;
}
const parsedData = VercelProjectIntegrationDataSchema.safeParse(
integration.integrationData
);
if (!parsedData.success) {
return undefined;
}
return {
id: integration.id,
vercelProjectId: integration.externalEntityId,
vercelProjectName: parsedData.data.vercelProjectName,
vercelTeamId: parsedData.data.vercelTeamId,
integrationData: parsedData.data,
createdAt: integration.createdAt,
};
});
return ResultAsync.combine([
checkOrgIntegration(),
checkGitHubConnection(),
checkStagingEnvironment(),
checkPreviewEnvironment(),
getVercelProjectIntegration(),
]).andThen(([hasOrgIntegration, isGitHubConnected, hasStagingEnvironment, hasPreviewEnvironment, connectedProject]) => {
const fetchCustomEnvsAndProjectSettings = async (): Promise<{
customEnvironments: VercelCustomEnvironment[];
autoAssignCustomDomains: boolean | null;
}> => {
if (!connectedProject || !orgIntegration) {
return { customEnvironments: [], autoAssignCustomDomains: null };
}
const clientResult = await VercelIntegrationRepository.getVercelClient(orgIntegration);
if (clientResult.isErr()) {
return { customEnvironments: [], autoAssignCustomDomains: null };
}
const client = clientResult.value;
const teamId = await VercelIntegrationRepository.getTeamIdFromIntegration(orgIntegration);
const [customEnvsResult, autoAssignResult] = await Promise.all([
VercelIntegrationRepository.getVercelCustomEnvironments(
client,
connectedProject.vercelProjectId,
teamId
),
VercelIntegrationRepository.getAutoAssignCustomDomains(
client,
connectedProject.vercelProjectId,
teamId
),
]);
return {
customEnvironments: customEnvsResult.isOk() ? customEnvsResult.value : [],
autoAssignCustomDomains: autoAssignResult.isOk() ? autoAssignResult.value : null,
};
};
return fromPromise(
fetchCustomEnvsAndProjectSettings(),
(error) => ({ type: "other" as const, cause: error })
).map(({ customEnvironments, autoAssignCustomDomains }) => ({
enabled: true,
hasOrgIntegration,
authInvalid: false,
connectedProject,
isGitHubConnected,
hasStagingEnvironment,
hasPreviewEnvironment,
customEnvironments,
autoAssignCustomDomains,
} as VercelSettingsResult));
}).mapErr((error) => {
// Log the error and return a safe fallback
logger.error("Error in VercelSettingsPresenter.call", { error });
return error;
});
}
/**
* Get data needed for the onboarding modal (custom environments and env vars)
*/
public async getOnboardingData(
projectId: string,
organizationId: string,
vercelEnvironmentId?: string
): Promise<VercelOnboardingData | null> {
const result = await ResultAsync.fromPromise(
(async (): Promise<VercelOnboardingData | null> => {
const [gitHubInstallations, connectedGitHubRepo] = await Promise.all([
(this._replica as PrismaClient).githubAppInstallation.findMany({
where: {
organizationId,
deletedAt: null,
suspendedAt: null,
},
select: {
id: true,
accountHandle: true,
targetType: true,
appInstallationId: true,
repositories: {
select: {
id: true,
name: true,
fullName: true,
htmlUrl: true,
private: true,
},
take: 200,
},
},
take: 20,
orderBy: {
createdAt: "desc",
},
}),
(this._replica as PrismaClient).connectedGithubRepository.findFirst({
where: {
projectId,
repository: {
installation: {
deletedAt: null,
suspendedAt: null,
},
},
},
select: {
id: true,
},
}),
]);
const isGitHubConnected = connectedGitHubRepo !== null;
const gitHubAppInstallations: GitHubAppInstallation[] = gitHubInstallations.map((installation) => ({
id: installation.id,
appInstallationId: installation.appInstallationId,
targetType: installation.targetType,
accountHandle: installation.accountHandle,
repositories: installation.repositories.map((repo) => ({
id: repo.id,
name: repo.name,
fullName: repo.fullName,
private: repo.private,
htmlUrl: repo.htmlUrl,
})),
}));
const orgIntegration = await (this._replica as PrismaClient).organizationIntegration.findFirst({
where: {
organizationId,
service: "VERCEL",
deletedAt: null,
},
include: {
tokenReference: true,
},
});
if (!orgIntegration) {
return null;
}
const tokenResult = await VercelIntegrationRepository.validateVercelToken(orgIntegration);
if (tokenResult.isErr() || !tokenResult.value.isValid) {
return {
customEnvironments: [],
environmentVariables: [],
availableProjects: [],
hasProjectSelected: false,
authInvalid: true,
authError: tokenResult.isErr() ? tokenResult.error.message : "Vercel token is invalid",
existingVariables: {},
gitHubAppInstallations,
isGitHubConnected,
isOnboardingComplete: false,
};
}
const clientResult = await VercelIntegrationRepository.getVercelClient(orgIntegration);
if (clientResult.isErr()) {
return {
customEnvironments: [],
environmentVariables: [],
availableProjects: [],
hasProjectSelected: false,
authInvalid: clientResult.error.authInvalid,
authError: clientResult.error.authInvalid ? clientResult.error.message : undefined,
existingVariables: {},
gitHubAppInstallations,
isGitHubConnected,
isOnboardingComplete: false,
};
}
const client = clientResult.value;
const teamId = await VercelIntegrationRepository.getTeamIdFromIntegration(orgIntegration);
const projectIntegration = await (this._replica as PrismaClient).organizationProjectIntegration.findFirst({
where: {
projectId,
deletedAt: null,
organizationIntegration: {
service: "VERCEL",
deletedAt: null,
},
},
});
const availableProjectsResult = await VercelIntegrationRepository.getVercelProjects(client, teamId);
if (availableProjectsResult.isErr()) {
return {
customEnvironments: [],
environmentVariables: [],
availableProjects: [],
hasProjectSelected: false,
authInvalid: availableProjectsResult.error.authInvalid,
authError: availableProjectsResult.error.authInvalid ? availableProjectsResult.error.message : undefined,
existingVariables: {},
gitHubAppInstallations,
isGitHubConnected,
isOnboardingComplete: false,
};
}
if (!projectIntegration) {
return {
customEnvironments: [],
environmentVariables: [],
availableProjects: availableProjectsResult.value,
hasProjectSelected: false,
existingVariables: {},
gitHubAppInstallations,
isGitHubConnected,
isOnboardingComplete: false,
};
}
const [customEnvironmentsResult, projectEnvVarsResult, sharedEnvVarsResult] = await Promise.all([
VercelIntegrationRepository.getVercelCustomEnvironments(
client,
projectIntegration.externalEntityId,
teamId
),
VercelIntegrationRepository.getVercelEnvironmentVariables(
client,
projectIntegration.externalEntityId,
teamId
),
// Only fetch shared env vars if teamId is available
teamId
? VercelIntegrationRepository.getVercelSharedEnvironmentVariables(
client,
teamId,
projectIntegration.externalEntityId
)
: okAsync([] as Array<{ id: string; key: string; type: string; isSecret: boolean; target: string[] }>),
]);
const authInvalid =
(customEnvironmentsResult.isErr() && customEnvironmentsResult.error.authInvalid) ||
(projectEnvVarsResult.isErr() && projectEnvVarsResult.error.authInvalid) ||
(sharedEnvVarsResult.isErr() && sharedEnvVarsResult.error.authInvalid);
if (authInvalid) {
const authError =
(customEnvironmentsResult.isErr() && customEnvironmentsResult.error.authInvalid && customEnvironmentsResult.error.message) ||
(projectEnvVarsResult.isErr() && projectEnvVarsResult.error.authInvalid && projectEnvVarsResult.error.message) ||
(sharedEnvVarsResult.isErr() && sharedEnvVarsResult.error.authInvalid && sharedEnvVarsResult.error.message) ||
undefined;
return {
customEnvironments: [],
environmentVariables: [],
availableProjects: availableProjectsResult.value,
hasProjectSelected: true,
authInvalid: true,
authError: authError || undefined,
existingVariables: {},
gitHubAppInstallations,
isGitHubConnected,
isOnboardingComplete: false,
};
}
const customEnvironments = customEnvironmentsResult.isOk() ? customEnvironmentsResult.value : [];
const projectEnvVars = projectEnvVarsResult.isOk() ? projectEnvVarsResult.value : [];
const sharedEnvVars = sharedEnvVarsResult.isOk() ? sharedEnvVarsResult.value : [];
// Filter out TRIGGER_SECRET_KEY and TRIGGER_VERSION (managed by Trigger.dev) and merge project + shared env vars
const excludedKeys = new Set(["TRIGGER_SECRET_KEY", "TRIGGER_VERSION"]);
const projectEnvVarKeys = new Set(projectEnvVars.map((v) => v.key));
const mergedEnvVars: VercelEnvironmentVariable[] = [
...projectEnvVars
.filter((v) => !excludedKeys.has(v.key))
.map((v) => {
const envVar = { ...v };
if (vercelEnvironmentId && (v as any).customEnvironmentIds?.includes(vercelEnvironmentId)) {
envVar.target = [...v.target, 'staging'];
}
return envVar;
}),
...sharedEnvVars
.filter((v) => !projectEnvVarKeys.has(v.key) && !excludedKeys.has(v.key))
.map((v) => {
const envVar = {
id: v.id,
key: v.key,
type: v.type as VercelEnvironmentVariable["type"],
isSecret: v.isSecret,
target: v.target,
isShared: true,
customEnvironmentIds: [] as string[],
};
if (vercelEnvironmentId && (v as any).customEnvironmentIds?.includes(vercelEnvironmentId)) {
envVar.target = [...v.target, 'staging'];
}
return envVar;
}),
];
const sortedEnvVars = [...mergedEnvVars].sort((a, b) =>
a.key.localeCompare(b.key)
);
const projectEnvs = await (this._replica as PrismaClient).runtimeEnvironment.findMany({
where: {
projectId,
archivedAt: null, // Filter out archived environments
},
select: {
id: true,
slug: true,
type: true,
},
});
const envIdToSlug = new Map(projectEnvs.map((e) => [e.id, e.slug]));
const activeEnvIds = new Set(projectEnvs.map((e) => e.id));
const envVarRepository = new EnvironmentVariablesRepository(this._replica as PrismaClient);
const existingVariables = await envVarRepository.getProject(projectId);
const existingVariablesRecord: Record<string, { environments: string[] }> = {};
for (const v of existingVariables) {
// Filter out archived environments and map to slugs
const activeEnvSlugs = v.values
.filter((val) => activeEnvIds.has(val.environment.id))
.map((val) => envIdToSlug.get(val.environment.id) || val.environment.type.toLowerCase());
if (activeEnvSlugs.length > 0) {
existingVariablesRecord[v.key] = {
environments: activeEnvSlugs,
};
}
}
const parsedIntegrationData = VercelProjectIntegrationDataSchema.safeParse(
projectIntegration.integrationData
);
return {
customEnvironments,
environmentVariables: sortedEnvVars,
availableProjects: availableProjectsResult.value,
hasProjectSelected: true,
existingVariables: existingVariablesRecord,
gitHubAppInstallations,
isGitHubConnected,
isOnboardingComplete: parsedIntegrationData.success
? (parsedIntegrationData.data.onboardingCompleted ?? false)
: false,
};
})(),
(error) => error
);
if (result.isErr()) {
logger.error("Error in getOnboardingData", { error: result.error });
return null;
}
return result.value;
}
}