@prisma/cli 3.0.0-dev.99.1 → 8.0.0-rc.10-dev.80

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.
Files changed (86) hide show
  1. package/README.md +26 -28
  2. package/dist/cli.js +14551 -16
  3. package/dist/payload-B88Qvzxk-CrtTXSOe.js +34 -0
  4. package/dist/sender.js +192 -0
  5. package/package.json +26 -19
  6. package/dist/adapters/git.js +0 -54
  7. package/dist/adapters/local-state.js +0 -144
  8. package/dist/adapters/mock-api.js +0 -136
  9. package/dist/adapters/token-storage.js +0 -418
  10. package/dist/cli2.js +0 -119
  11. package/dist/commands/app/index.js +0 -345
  12. package/dist/commands/auth/index.js +0 -96
  13. package/dist/commands/branch/index.js +0 -27
  14. package/dist/commands/database/index.js +0 -159
  15. package/dist/commands/env.js +0 -99
  16. package/dist/commands/git/index.js +0 -36
  17. package/dist/commands/project/index.js +0 -69
  18. package/dist/commands/version/index.js +0 -18
  19. package/dist/controllers/app-env-api.js +0 -54
  20. package/dist/controllers/app-env-file.js +0 -181
  21. package/dist/controllers/app-env.js +0 -502
  22. package/dist/controllers/app.js +0 -2443
  23. package/dist/controllers/auth.js +0 -316
  24. package/dist/controllers/branch.js +0 -103
  25. package/dist/controllers/database.js +0 -318
  26. package/dist/controllers/project.js +0 -731
  27. package/dist/controllers/select-prompt-port.js +0 -12
  28. package/dist/controllers/version.js +0 -12
  29. package/dist/lib/app/app-interaction.js +0 -5
  30. package/dist/lib/app/app-provider.js +0 -544
  31. package/dist/lib/app/branch-database-api.js +0 -102
  32. package/dist/lib/app/branch-database-deploy.js +0 -325
  33. package/dist/lib/app/branch-database.js +0 -215
  34. package/dist/lib/app/build-settings.js +0 -93
  35. package/dist/lib/app/build.js +0 -80
  36. package/dist/lib/app/bun-project.js +0 -45
  37. package/dist/lib/app/compute-config.js +0 -147
  38. package/dist/lib/app/deploy-output.js +0 -24
  39. package/dist/lib/app/deploy-plan.js +0 -58
  40. package/dist/lib/app/deploy-progress.js +0 -100
  41. package/dist/lib/app/domain-guidance.js +0 -14
  42. package/dist/lib/app/env-config.js +0 -67
  43. package/dist/lib/app/env-file.js +0 -82
  44. package/dist/lib/app/env-vars.js +0 -50
  45. package/dist/lib/app/local-dev.js +0 -109
  46. package/dist/lib/app/production-deploy-gate.js +0 -161
  47. package/dist/lib/app/read-branch.js +0 -30
  48. package/dist/lib/auth/auth-ops.js +0 -158
  49. package/dist/lib/auth/client.js +0 -22
  50. package/dist/lib/auth/guard.js +0 -38
  51. package/dist/lib/auth/login.js +0 -330
  52. package/dist/lib/database/provider.js +0 -167
  53. package/dist/lib/diagnostics.js +0 -15
  54. package/dist/lib/fs/home-path.js +0 -24
  55. package/dist/lib/git/local-branch.js +0 -53
  56. package/dist/lib/git/local-status.js +0 -57
  57. package/dist/lib/project/interactive-setup.js +0 -56
  58. package/dist/lib/project/local-pin.js +0 -200
  59. package/dist/lib/project/resolution.js +0 -386
  60. package/dist/lib/project/setup.js +0 -135
  61. package/dist/lib/version.js +0 -55
  62. package/dist/output/patterns.js +0 -90
  63. package/dist/presenters/app-env.js +0 -265
  64. package/dist/presenters/app.js +0 -646
  65. package/dist/presenters/auth.js +0 -183
  66. package/dist/presenters/branch.js +0 -46
  67. package/dist/presenters/database.js +0 -274
  68. package/dist/presenters/project.js +0 -174
  69. package/dist/presenters/verbose-context.js +0 -64
  70. package/dist/presenters/version.js +0 -29
  71. package/dist/shell/command-arguments.js +0 -6
  72. package/dist/shell/command-meta.js +0 -622
  73. package/dist/shell/command-runner.js +0 -112
  74. package/dist/shell/diagnostics-output.js +0 -57
  75. package/dist/shell/errors.js +0 -134
  76. package/dist/shell/global-flags.js +0 -37
  77. package/dist/shell/help.js +0 -89
  78. package/dist/shell/output.js +0 -82
  79. package/dist/shell/prompt.js +0 -41
  80. package/dist/shell/runtime.js +0 -55
  81. package/dist/shell/ui.js +0 -116
  82. package/dist/shell/update-check.js +0 -247
  83. package/dist/use-cases/auth.js +0 -145
  84. package/dist/use-cases/branch.js +0 -47
  85. package/dist/use-cases/create-cli-gateways.js +0 -68
  86. package/dist/use-cases/project.js +0 -30
@@ -1,731 +0,0 @@
1
- import { CliError, authRequiredError, featureUnavailableError, usageError, workspaceRequiredError } from "../shell/errors.js";
2
- import { createAppProvider } from "../lib/app/app-provider.js";
3
- import { renderSummaryLine } from "../shell/ui.js";
4
- import { canPrompt } from "../shell/runtime.js";
5
- import { readLocalResolutionPin } from "../lib/project/local-pin.js";
6
- import { formatCommandArgument } from "../shell/command-arguments.js";
7
- import { buildProjectSetupNextActions, inferTargetName, inspectProjectBinding, projectResolutionErrorToCliError, resolveProjectTarget, sortProjects } from "../lib/project/resolution.js";
8
- import { bindProjectToDirectory, isValidProjectSetupName, projectCreateFailedError, projectDirectoryBindingErrorToCliError, projectSetupNameRequiredError, resolveProjectForSetup, toProjectSummary } from "../lib/project/setup.js";
9
- import { requireComputeAuth } from "../lib/auth/guard.js";
10
- import { promptForProjectSetupChoice } from "../lib/project/interactive-setup.js";
11
- import { createCliUseCaseGateways } from "../use-cases/create-cli-gateways.js";
12
- import { requireAuthenticatedAuthState } from "./auth.js";
13
- import { parseGitHubRepositoryUrl, readGitOriginRemote } from "../adapters/git.js";
14
- import { createProjectUseCases } from "../use-cases/project.js";
15
- import { matchError } from "better-result";
16
- import open from "open";
17
- //#region src/controllers/project.ts
18
- const GITHUB_INSTALL_POLL_INTERVAL_MS = 2e3;
19
- const GITHUB_INSTALL_POLL_TIMEOUT_MS = 12e4;
20
- function isRealMode(context) {
21
- return !context.runtime.fixturePath && !context.runtime.env.PRISMA_CLI_MOCK_FIXTURE_PATH;
22
- }
23
- async function readProjectListLocalBinding(cwd, workspace, projects, signal) {
24
- const pinResult = await readLocalResolutionPin(cwd, signal);
25
- if (pinResult.isErr()) return localPinReadErrorToInvalidLocalBinding(pinResult.error);
26
- const pin = pinResult.value;
27
- if (pin.kind === "present") return pin.pin.workspaceId === workspace.id && projects.some((project) => project.id === pin.pin.projectId) ? { status: "linked" } : { status: "invalid" };
28
- return { status: "not-linked" };
29
- }
30
- function localPinReadErrorToInvalidLocalBinding(error) {
31
- return matchError(error, {
32
- LocalResolutionPinInvalidJsonError: () => ({ status: "invalid" }),
33
- LocalResolutionPinInvalidShapeError: () => ({ status: "invalid" }),
34
- LocalResolutionPinReadAbortedError: (error) => {
35
- throw error;
36
- },
37
- UnhandledException: (error) => {
38
- throw error;
39
- }
40
- });
41
- }
42
- async function runProjectList(context) {
43
- const authState = await requireAuthenticatedAuthState(context);
44
- const workspace = authState.workspace;
45
- if (!workspace) throw workspaceRequiredError();
46
- if (isRealMode(context)) {
47
- const client = await requireComputeAuth(context.runtime.env, context.runtime.signal);
48
- if (!client) throw authRequiredError();
49
- const projects = sortProjects(await listRealWorkspaceProjects(client, workspace, context.runtime.signal));
50
- const localBinding = await readProjectListLocalBinding(context.runtime.cwd, workspace, projects, context.runtime.signal);
51
- const nextActions = buildProjectListNextActions(localBinding);
52
- return {
53
- command: "project.list",
54
- result: {
55
- workspace,
56
- projects: projects.map(toProjectSummary),
57
- localBinding
58
- },
59
- warnings: [],
60
- nextSteps: [],
61
- nextActions
62
- };
63
- }
64
- const result = await createProjectUseCases(createCliUseCaseGateways(context)).list(authState);
65
- const localBinding = await readProjectListLocalBinding(context.runtime.cwd, workspace, result.projects, context.runtime.signal);
66
- const nextActions = buildProjectListNextActions(localBinding);
67
- return {
68
- command: "project.list",
69
- result: {
70
- ...result,
71
- localBinding
72
- },
73
- warnings: [],
74
- nextSteps: [],
75
- nextActions
76
- };
77
- }
78
- function buildProjectListNextActions(localBinding) {
79
- return localBinding?.status === "linked" ? [] : buildProjectSetupNextActions({
80
- createCommand: "prisma-cli project create <name>",
81
- reason: localBinding?.status === "invalid" ? "This directory has an invalid local Project binding. Ask the user which Prisma Project to link before running Project-scoped commands." : "This directory is not linked to a Prisma Project. Project list shows available Projects, but none is selected for this directory."
82
- });
83
- }
84
- async function runProjectShow(context, explicitProject) {
85
- const workspace = (await requireAuthenticatedAuthState(context)).workspace;
86
- if (!workspace) throw workspaceRequiredError();
87
- const result = isRealMode(context) ? await resolveProjectShowInRealMode(context, workspace, explicitProject) : await resolveProjectShowInFixtureMode(context, workspace, explicitProject);
88
- return {
89
- command: "project.show",
90
- result,
91
- warnings: [],
92
- nextSteps: [],
93
- nextActions: result.project === null ? buildProjectSetupNextActions({
94
- commandName: "project show",
95
- suggestedProjectName: result.suggestedProjectName,
96
- reason: "This directory is not linked to a Prisma Project. Package and directory names can suggest setup defaults, but they do not select a Project."
97
- }) : []
98
- };
99
- }
100
- async function runProjectCreate(context, projectName) {
101
- const workspace = (await requireAuthenticatedAuthState(context)).workspace;
102
- if (!workspace) throw workspaceRequiredError();
103
- if (!isValidProjectSetupName(projectName)) throw projectSetupNameRequiredError("project create");
104
- if (!isRealMode(context)) throw featureUnavailableError("Project create is not available in fixture mode", "Creating Projects requires live platform integration.", "Rerun without fixture mode enabled to create a Project.", ["prisma-cli auth login"], "project");
105
- const client = await requireComputeAuth(context.runtime.env, context.runtime.signal);
106
- if (!client) throw authRequiredError();
107
- const provider = createAppProvider(client);
108
- const name = projectName.trim();
109
- const created = await provider.createProject({
110
- name,
111
- signal: context.runtime.signal
112
- }).catch((error) => {
113
- throw projectCreateFailedError(error, name, workspace, {
114
- nextSteps: ["prisma-cli project list", "prisma-cli project link <id-or-name>"],
115
- permissionFix: "Grant the token permission to create Projects in this workspace, or link an existing Project.",
116
- fallbackFix: "Retry the command, or choose an existing Project with prisma-cli project link <id-or-name>."
117
- });
118
- });
119
- const bindResult = await bindProjectToDirectory(context, workspace, {
120
- id: created.id,
121
- name: created.name
122
- }, "created");
123
- if (bindResult.isErr()) throw projectDirectoryBindingErrorToCliError(bindResult.error);
124
- return {
125
- command: "project.create",
126
- result: bindResult.value,
127
- warnings: [],
128
- nextSteps: ["prisma-cli app deploy"]
129
- };
130
- }
131
- async function runProjectLink(context, projectRef) {
132
- const workspace = (await requireAuthenticatedAuthState(context)).workspace;
133
- if (!workspace) throw workspaceRequiredError();
134
- let provider = null;
135
- let projects;
136
- if (isRealMode(context)) {
137
- const client = await requireComputeAuth(context.runtime.env, context.runtime.signal);
138
- if (!client) throw authRequiredError();
139
- provider = createAppProvider(client);
140
- projects = await listRealWorkspaceProjects(client, workspace, context.runtime.signal);
141
- } else projects = listFixtureWorkspaceProjects(context, workspace);
142
- let result;
143
- if (projectRef?.trim()) result = await requireProjectDirectoryBinding(context, workspace, toProjectSummary(resolveProjectForSetup(projectRef.trim(), projects, workspace)), "linked");
144
- else if (canPrompt(context) && !context.flags.yes) result = await resolveInteractiveProjectLinkSetup(context, workspace, projects, provider);
145
- else throw await projectLinkTargetRequiredError(context, projects);
146
- return {
147
- command: "project.link",
148
- result,
149
- warnings: [],
150
- nextSteps: ["prisma-cli app deploy"]
151
- };
152
- }
153
- async function resolveInteractiveProjectLinkSetup(context, workspace, projects, provider) {
154
- const setup = await promptForProjectSetupChoice({
155
- context,
156
- projects,
157
- createProject: (projectName) => {
158
- if (!provider) throw featureUnavailableError("Project create is not available in fixture mode", "Creating Projects requires live platform integration.", "Rerun without fixture mode enabled to create a Project.", ["prisma-cli auth login"], "project");
159
- return createProjectForLinkSetup(provider, projectName, workspace, context.runtime.signal);
160
- },
161
- cancel: {
162
- why: "Project link needs a Project before it can continue.",
163
- fix: "Choose an existing Project or create a new one, then rerun project link.",
164
- nextSteps: ["prisma-cli project link <id-or-name>", "prisma-cli project create <name>"]
165
- }
166
- });
167
- return requireProjectDirectoryBinding(context, workspace, setup.project, setup.action);
168
- }
169
- async function requireProjectDirectoryBinding(context, workspace, project, action) {
170
- const bindResult = await bindProjectToDirectory(context, workspace, project, action);
171
- if (bindResult.isErr()) throw projectDirectoryBindingErrorToCliError(bindResult.error);
172
- return bindResult.value;
173
- }
174
- async function createProjectForLinkSetup(provider, projectName, workspace, signal) {
175
- const created = await provider.createProject({
176
- name: projectName,
177
- signal
178
- }).catch((error) => {
179
- throw projectCreateFailedError(error, projectName, workspace, {
180
- nextSteps: [
181
- "prisma-cli project list",
182
- "prisma-cli project link <id-or-name>",
183
- `prisma-cli project create ${formatCommandArgument(projectName)}`
184
- ],
185
- permissionFix: "Grant the token permission to create Projects in this workspace, or link an existing Project.",
186
- fallbackFix: "Retry the command, or choose an existing Project with prisma-cli project link <id-or-name>."
187
- });
188
- });
189
- return {
190
- id: created.id,
191
- name: created.name,
192
- workspace
193
- };
194
- }
195
- async function projectLinkTargetRequiredError(context, projects) {
196
- const suggestedName = await inferTargetName(context.runtime.cwd, context.runtime.signal);
197
- const createCommand = `prisma-cli project create ${formatCommandArgument(suggestedName.name)}`;
198
- const recoveryCommands = ["prisma-cli project link <id-or-name>", createCommand];
199
- return new CliError({
200
- code: "PROJECT_LINK_TARGET_REQUIRED",
201
- domain: "project",
202
- summary: "Choose a Project to link this directory",
203
- why: "This directory is not linked to a Prisma Project. Existing Projects are candidates until the user chooses one, and package or directory names are suggestions only.",
204
- fix: "Run prisma-cli project link in a TTY to choose from the setup list, pass a Project id or name, or create a new Project.",
205
- meta: {
206
- suggestedProjectName: suggestedName.name,
207
- suggestedProjectNameSource: suggestedName.source,
208
- candidates: sortProjects(projects).map(toProjectSummary),
209
- recoveryCommands
210
- },
211
- exitCode: 2,
212
- nextSteps: ["prisma-cli project list", ...recoveryCommands],
213
- nextActions: buildProjectSetupNextActions({
214
- suggestedProjectName: suggestedName.name,
215
- createCommand,
216
- reason: "Project link needs the user to choose an existing Project or create a new one. Existing Projects, package names, and directory names are candidates only, not selections."
217
- })
218
- });
219
- }
220
- async function runGitConnect(context, gitUrl, options = {}) {
221
- const workspace = (await requireAuthenticatedAuthState(context)).workspace;
222
- if (!workspace) throw workspaceRequiredError();
223
- if (isRealMode(context)) {
224
- const client = await requireComputeAuth(context.runtime.env, context.runtime.signal);
225
- if (!client) throw authRequiredError();
226
- const target = await resolveRequiredProjectInRealMode(context, workspace, options.project, "git connect");
227
- const repository = await resolveRepositoryForConnect(context, gitUrl);
228
- const api = client;
229
- const existing = await readFirstSourceRepository(api, target.project.id, context.runtime.signal);
230
- if (existing) {
231
- const existingConnection = toRepositoryConnection(existing);
232
- if (repositoryFullNamesMatch(existingConnection.repository.fullName, repository.fullName)) return {
233
- command: "git.connect",
234
- result: {
235
- ...target,
236
- repositoryConnection: existingConnection
237
- },
238
- warnings: [],
239
- nextSteps: []
240
- };
241
- throw repoAlreadyConnectedError(existingConnection.repository.fullName);
242
- }
243
- const resolvedRepository = await resolveInstalledRepository(context, api, workspace.id, repository);
244
- const { data, error, response } = await api.POST("/v1/source-repositories", {
245
- body: {
246
- projectId: target.project.id,
247
- provider: "github",
248
- providerRepositoryId: resolvedRepository.repository.id,
249
- installationId: resolvedRepository.installation.id
250
- },
251
- signal: context.runtime.signal
252
- });
253
- if (error || !data) throw repoConnectionApiError("Failed to connect GitHub repository", response, error);
254
- return {
255
- command: "git.connect",
256
- result: {
257
- ...target,
258
- repositoryConnection: toRepositoryConnection(data.data)
259
- },
260
- warnings: [],
261
- nextSteps: []
262
- };
263
- }
264
- const target = await resolveRequiredProjectInFixtureMode(context, workspace, options.project, "git connect");
265
- const repository = await resolveRepositoryForConnect(context, gitUrl);
266
- const existingConnection = await context.stateStore.readRepositoryConnection(target.project.id);
267
- if (existingConnection) {
268
- if (repositoryFullNamesMatch(existingConnection.repository.fullName, repository.fullName)) return {
269
- command: "git.connect",
270
- result: {
271
- ...target,
272
- repositoryConnection: existingConnection
273
- },
274
- warnings: [],
275
- nextSteps: []
276
- };
277
- throw repoAlreadyConnectedError(existingConnection.repository.fullName);
278
- }
279
- const connection = createPendingRepositoryConnection(repository);
280
- await context.stateStore.setRepositoryConnection(target.project.id, connection);
281
- return {
282
- command: "git.connect",
283
- result: {
284
- ...target,
285
- repositoryConnection: connection
286
- },
287
- warnings: [],
288
- nextSteps: []
289
- };
290
- }
291
- async function runGitDisconnect(context, options = {}) {
292
- const workspace = (await requireAuthenticatedAuthState(context)).workspace;
293
- if (!workspace) throw workspaceRequiredError();
294
- if (isRealMode(context)) {
295
- const client = await requireComputeAuth(context.runtime.env, context.runtime.signal);
296
- if (!client) throw authRequiredError();
297
- const target = await resolveRequiredProjectInRealMode(context, workspace, options.project, "git disconnect");
298
- const api = client;
299
- const existing = await readFirstSourceRepository(api, target.project.id, context.runtime.signal);
300
- if (!existing) throw repoNotConnectedError();
301
- const { error, response } = await api.DELETE("/v1/source-repositories/{id}", {
302
- params: { path: { id: existing.id } },
303
- signal: context.runtime.signal
304
- });
305
- if (error) throw repoConnectionApiError("Failed to disconnect GitHub repository", response, error);
306
- return {
307
- command: "git.disconnect",
308
- result: {
309
- ...target,
310
- repositoryConnection: toRepositoryConnection(existing)
311
- },
312
- warnings: [],
313
- nextSteps: []
314
- };
315
- }
316
- const target = await resolveRequiredProjectInFixtureMode(context, workspace, options.project, "git disconnect");
317
- const existingConnection = await context.stateStore.readRepositoryConnection(target.project.id);
318
- if (!existingConnection) throw repoNotConnectedError();
319
- await context.stateStore.clearRepositoryConnection(target.project.id);
320
- return {
321
- command: "git.disconnect",
322
- result: {
323
- ...target,
324
- repositoryConnection: existingConnection
325
- },
326
- warnings: [],
327
- nextSteps: []
328
- };
329
- }
330
- async function resolveProjectShowInRealMode(context, workspace, explicitProject) {
331
- const client = await requireComputeAuth(context.runtime.env, context.runtime.signal);
332
- if (!client) throw authRequiredError();
333
- const result = await inspectProjectBinding({
334
- context,
335
- workspace,
336
- explicitProject,
337
- listProjects: () => listRealWorkspaceProjects(client, workspace, context.runtime.signal),
338
- commandName: "project show"
339
- });
340
- if (result.isErr()) throw projectResolutionErrorToCliError(result.error);
341
- return result.value;
342
- }
343
- async function resolveRequiredProjectInRealMode(context, workspace, explicitProject, commandName) {
344
- const client = await requireComputeAuth(context.runtime.env, context.runtime.signal);
345
- if (!client) throw authRequiredError();
346
- const result = await resolveProjectTarget({
347
- context,
348
- workspace,
349
- explicitProject,
350
- listProjects: () => listRealWorkspaceProjects(client, workspace, context.runtime.signal),
351
- commandName
352
- });
353
- if (result.isErr()) throw projectResolutionErrorToCliError(result.error);
354
- return result.value;
355
- }
356
- async function resolveProjectShowInFixtureMode(context, workspace, explicitProject) {
357
- const result = await inspectProjectBinding({
358
- context,
359
- workspace,
360
- explicitProject,
361
- listProjects: async () => listFixtureWorkspaceProjects(context, workspace),
362
- commandName: "project show"
363
- });
364
- if (result.isErr()) throw projectResolutionErrorToCliError(result.error);
365
- return result.value;
366
- }
367
- async function resolveRequiredProjectInFixtureMode(context, workspace, explicitProject, commandName) {
368
- const result = await resolveProjectTarget({
369
- context,
370
- workspace,
371
- explicitProject,
372
- listProjects: async () => listFixtureWorkspaceProjects(context, workspace),
373
- commandName
374
- });
375
- if (result.isErr()) throw projectResolutionErrorToCliError(result.error);
376
- return result.value;
377
- }
378
- async function listRealWorkspaceProjects(client, workspace, signal) {
379
- const { data } = await client.GET("/v1/projects", { signal });
380
- return sortProjects((data?.data ?? []).filter((project) => project.workspace.id === workspace.id).map((project) => ({
381
- id: project.id,
382
- name: project.name,
383
- ..."url" in project && typeof project.url === "string" ? { url: project.url } : {},
384
- slug: "slug" in project && typeof project.slug === "string" ? project.slug : null,
385
- workspace: {
386
- id: project.workspace.id,
387
- name: project.workspace.name
388
- }
389
- })));
390
- }
391
- function listFixtureWorkspaceProjects(context, workspace) {
392
- return sortProjects(context.api.listProjectsForWorkspace(workspace.id).map((project) => ({
393
- id: project.id,
394
- name: project.name,
395
- ...project.url ? { url: project.url } : {},
396
- slug: project.slug,
397
- workspace
398
- })));
399
- }
400
- async function resolveRepositoryForConnect(context, gitUrl) {
401
- const remoteUrl = gitUrl ?? await readGitOriginRemote(context.runtime.cwd, context.runtime.signal);
402
- if (!remoteUrl) throw usageError("Repository connection requires a GitHub repository URL", "No git-url was provided and the local repo does not have an origin remote.", "Pass a GitHub repository URL, or add a GitHub origin remote and rerun prisma-cli git connect.", ["prisma-cli git connect git@github.com:prisma/prisma-cli.git"], "project");
403
- const repository = parseGitHubRepositoryUrl(remoteUrl);
404
- if (!repository) throw unsupportedRepositoryProviderError();
405
- return repository;
406
- }
407
- async function resolveInstalledRepository(context, api, workspaceId, repository) {
408
- const lookup = await findRepositoryInInstallations(api, await listScmInstallations(api, workspaceId, context.runtime.signal), repository, context.runtime.signal);
409
- if (lookup.match) return lookup.match;
410
- const installUrl = await createGitHubInstallIntent(api, workspaceId, context.runtime.signal);
411
- const canWait = canPrompt(context);
412
- const opened = await openInstallUrlIfInteractive(context, installUrl);
413
- if (!canWait) {
414
- if (lookup.inspectableInstallationCount > 0) throw repoNotAccessibleError(repository, installUrl, opened);
415
- throw repoInstallationRequiredError(repository, installUrl, opened);
416
- }
417
- writeInstallWaitStatus(context, opened, installUrl);
418
- const result = await waitForInstalledRepository(context, api, workspaceId, repository);
419
- if (result.match) return result.match;
420
- if (result.inspectableInstallationCount > 0) throw repoNotAccessibleError(repository, installUrl, opened);
421
- throw repoInstallationRequiredError(repository, installUrl, opened);
422
- }
423
- async function findRepositoryInInstallations(api, installations, repository, signal) {
424
- let inspectableInstallationCount = 0;
425
- for (const installation of installations) {
426
- if (installation.provider !== "github" || installation.suspended) continue;
427
- const matchedRepository = await findRepositoryInInstallationIfAvailable(api, installation.id, repository, signal);
428
- if (matchedRepository === "unavailable") continue;
429
- inspectableInstallationCount += 1;
430
- if (matchedRepository) return {
431
- match: {
432
- installation,
433
- repository: matchedRepository
434
- },
435
- inspectableInstallationCount
436
- };
437
- }
438
- return {
439
- match: null,
440
- inspectableInstallationCount
441
- };
442
- }
443
- async function waitForInstalledRepository(context, api, workspaceId, repository) {
444
- const timeoutMs = readPositiveIntegerEnv(context.runtime.env.PRISMA_CLI_GITHUB_INSTALL_TIMEOUT_MS, GITHUB_INSTALL_POLL_TIMEOUT_MS);
445
- const intervalMs = readPositiveIntegerEnv(context.runtime.env.PRISMA_CLI_GITHUB_INSTALL_POLL_INTERVAL_MS, GITHUB_INSTALL_POLL_INTERVAL_MS);
446
- const deadline = Date.now() + timeoutMs;
447
- let inspectableInstallationCount = 0;
448
- while (Date.now() <= deadline) {
449
- context.runtime.signal.throwIfAborted();
450
- const lookup = await findRepositoryInInstallations(api, await listScmInstallations(api, workspaceId, context.runtime.signal), repository, context.runtime.signal);
451
- inspectableInstallationCount = lookup.inspectableInstallationCount;
452
- if (lookup.match) return {
453
- match: lookup.match,
454
- inspectableInstallationCount
455
- };
456
- const remainingMs = deadline - Date.now();
457
- if (remainingMs <= 0) break;
458
- await sleep(Math.min(intervalMs, remainingMs), context.runtime.signal);
459
- }
460
- return {
461
- match: null,
462
- inspectableInstallationCount
463
- };
464
- }
465
- function readPositiveIntegerEnv(value, fallback) {
466
- if (value === void 0) return fallback;
467
- const parsed = Number(value);
468
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
469
- }
470
- function writeInstallWaitStatus(context, opened, installUrl) {
471
- if (context.flags.quiet) return;
472
- const lines = [renderSummaryLine(context.ui, "info", opened ? "Waiting for GitHub App installation or repository access approval..." : "Waiting for GitHub App installation or repository access approval. Open the install URL in your browser.")];
473
- if (!opened) lines.push(installUrl);
474
- context.output.stderr.write(`${lines.join("\n")}\n`);
475
- }
476
- function sleep(ms, signal) {
477
- signal.throwIfAborted();
478
- return new Promise((resolve, reject) => {
479
- const onAbort = () => {
480
- clearTimeout(timeout);
481
- reject(signal.reason);
482
- };
483
- const timeout = setTimeout(() => {
484
- signal.removeEventListener("abort", onAbort);
485
- resolve();
486
- }, ms);
487
- signal.addEventListener("abort", onAbort, { once: true });
488
- });
489
- }
490
- async function listScmInstallations(api, workspaceId, signal) {
491
- const installations = [];
492
- let cursor;
493
- const seenCursors = /* @__PURE__ */ new Set();
494
- do {
495
- const { data, error, response } = await api.GET("/v1/scm-installations", {
496
- params: { query: {
497
- workspaceId,
498
- limit: 100,
499
- ...cursor ? { cursor } : {}
500
- } },
501
- signal
502
- });
503
- if (error || !data) throw repoConnectionApiError("Failed to inspect GitHub App installations", response, error);
504
- installations.push(...data.data);
505
- cursor = readNextPaginationCursor(data.pagination, seenCursors, "Failed to inspect GitHub App installations", response);
506
- } while (cursor);
507
- return installations;
508
- }
509
- async function findRepositoryInInstallation(api, installationId, repository, signal) {
510
- const expectedFullName = repository.fullName.toLowerCase();
511
- let cursor;
512
- const seenCursors = /* @__PURE__ */ new Set();
513
- do {
514
- const { data, error, response } = await api.GET("/v1/scm-installations/{installationId}/repositories", {
515
- params: {
516
- path: { installationId },
517
- query: {
518
- limit: 100,
519
- ...cursor ? { cursor } : {}
520
- }
521
- },
522
- signal
523
- });
524
- if (error || !data) throw repoConnectionApiError("Failed to inspect GitHub repositories", response, error);
525
- const matchedRepository = data.data.find((candidate) => candidate.fullName.toLowerCase() === expectedFullName);
526
- if (matchedRepository) return matchedRepository;
527
- cursor = readNextPaginationCursor(data.pagination, seenCursors, "Failed to inspect GitHub repositories", response);
528
- } while (cursor);
529
- return null;
530
- }
531
- function readNextPaginationCursor(pagination, seenCursors, summary, response) {
532
- const nextCursor = pagination.hasMore && pagination.nextCursor ? pagination.nextCursor : void 0;
533
- if (!nextCursor) return;
534
- if (seenCursors.has(nextCursor)) throw repoConnectionApiError(summary, response, { error: { message: "Pagination cursor did not advance." } });
535
- seenCursors.add(nextCursor);
536
- return nextCursor;
537
- }
538
- async function findRepositoryInInstallationIfAvailable(api, installationId, repository, signal) {
539
- try {
540
- return await findRepositoryInInstallation(api, installationId, repository, signal);
541
- } catch (error) {
542
- if (signal.aborted) throw error;
543
- if (isUnavailableScmInstallationError(error)) return "unavailable";
544
- throw error;
545
- }
546
- }
547
- function isUnavailableScmInstallationError(error) {
548
- if (!(error instanceof CliError) || error.code !== "REPO_CONNECTION_FAILED") return false;
549
- return error.meta.status === 404 || error.meta.status === 422;
550
- }
551
- async function createGitHubInstallIntent(api, workspaceId, signal) {
552
- const { data, error, response } = await api.POST("/v1/scm-installations/install-intents", {
553
- body: {
554
- provider: "github",
555
- workspaceId
556
- },
557
- signal
558
- });
559
- if (error || !data) throw repoConnectionApiError("Failed to create GitHub App installation link", response, error);
560
- return data.data.installUrl;
561
- }
562
- async function openInstallUrlIfInteractive(context, installUrl) {
563
- if (!canPrompt(context)) return false;
564
- try {
565
- context.runtime.signal.throwIfAborted();
566
- await open(installUrl);
567
- context.runtime.signal.throwIfAborted();
568
- return true;
569
- } catch (error) {
570
- if (context.runtime.signal.aborted) throw error;
571
- return false;
572
- }
573
- }
574
- async function readFirstSourceRepository(api, projectId, signal) {
575
- const { data, error, response } = await api.GET("/v1/source-repositories", {
576
- params: { query: {
577
- projectId,
578
- limit: 1
579
- } },
580
- signal
581
- });
582
- if (error || !data) throw repoConnectionApiError("Failed to inspect GitHub repository connection", response, error);
583
- return data.data[0] ?? null;
584
- }
585
- function createPendingRepositoryConnection(repository) {
586
- return {
587
- id: null,
588
- provider: "github",
589
- repoId: null,
590
- repository,
591
- defaultBranch: null,
592
- isPrivate: null,
593
- status: "pending",
594
- installation: {
595
- id: null,
596
- status: "pending"
597
- },
598
- automation: {
599
- branches: false,
600
- pullRequests: false,
601
- comments: false
602
- },
603
- connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
604
- updatedAt: null
605
- };
606
- }
607
- function toRepositoryConnection(record) {
608
- const [owner = "", name = ""] = record.repoFullName.split("/");
609
- return {
610
- id: record.id,
611
- provider: "github",
612
- repoId: record.repoId,
613
- repository: {
614
- owner,
615
- name,
616
- fullName: record.repoFullName,
617
- url: `https://github.com/${record.repoFullName}`
618
- },
619
- defaultBranch: record.defaultBranch,
620
- isPrivate: record.isPrivate,
621
- status: record.status,
622
- installation: {
623
- id: record.installationId,
624
- status: "connected"
625
- },
626
- automation: {
627
- branches: record.status === "active",
628
- pullRequests: false,
629
- comments: false
630
- },
631
- connectedAt: record.createdAt,
632
- updatedAt: record.updatedAt
633
- };
634
- }
635
- function unsupportedRepositoryProviderError() {
636
- return new CliError({
637
- code: "REPO_PROVIDER_UNSUPPORTED",
638
- domain: "project",
639
- summary: "Repository provider is not supported",
640
- why: "Repository connection supports GitHub repository URLs only.",
641
- fix: "Pass a GitHub repository URL such as git@github.com:prisma/prisma-cli.git.",
642
- exitCode: 2,
643
- nextSteps: ["prisma-cli git connect git@github.com:owner/repo.git"]
644
- });
645
- }
646
- function repoNotConnectedError() {
647
- return new CliError({
648
- code: "REPO_NOT_CONNECTED",
649
- domain: "project",
650
- summary: "No GitHub repository connected",
651
- why: "The resolved project does not have an active GitHub repository connection.",
652
- fix: "Run prisma-cli git connect before disconnecting.",
653
- exitCode: 1,
654
- nextSteps: ["prisma-cli git connect"]
655
- });
656
- }
657
- function repoInstallationRequiredError(repository, installUrl, opened) {
658
- return new CliError({
659
- code: "REPO_INSTALLATION_REQUIRED",
660
- domain: "project",
661
- summary: "GitHub App installation required",
662
- why: `The selected workspace does not have a GitHub App installation that can be used to link ${repository.fullName}.`,
663
- fix: opened ? "Finish installing the GitHub App in the browser, then rerun prisma-cli git connect." : "Open the GitHub App installation URL, approve access, then rerun prisma-cli git connect.",
664
- meta: {
665
- repository: repository.fullName,
666
- installUrl,
667
- opened
668
- },
669
- exitCode: 1,
670
- nextSteps: [installUrl, `prisma-cli git connect ${repository.url}`]
671
- });
672
- }
673
- function repoNotAccessibleError(repository, installUrl, opened) {
674
- return new CliError({
675
- code: "REPO_NOT_ACCESSIBLE",
676
- domain: "project",
677
- summary: "GitHub repository is not accessible",
678
- why: `The GitHub App installations connected to this workspace do not expose ${repository.fullName}.`,
679
- fix: "Open the GitHub App installation URL, grant access to this repository, then rerun prisma-cli git connect.",
680
- meta: {
681
- repository: repository.fullName,
682
- installUrl,
683
- opened
684
- },
685
- exitCode: 1,
686
- nextSteps: [installUrl, `prisma-cli git connect ${repository.url}`]
687
- });
688
- }
689
- function repoAlreadyConnectedError(repositoryFullName) {
690
- return new CliError({
691
- code: "REPO_ALREADY_CONNECTED",
692
- domain: "project",
693
- summary: "Project already has a GitHub repository connected",
694
- why: `The resolved project is already connected to ${repositoryFullName}.`,
695
- fix: "Disconnect the existing repository before connecting a different one.",
696
- meta: { repository: repositoryFullName },
697
- exitCode: 1,
698
- nextSteps: ["prisma-cli git disconnect"]
699
- });
700
- }
701
- function repositoryFullNamesMatch(left, right) {
702
- return left.toLowerCase() === right.toLowerCase();
703
- }
704
- function repoConnectionApiError(summary, response, error) {
705
- const status = response?.status ?? 0;
706
- const apiCode = error?.error?.code;
707
- const apiMessage = error?.error?.message;
708
- const apiHint = error?.error?.hint;
709
- if (status === 401 || status === 403) return authRequiredError(["prisma-cli auth login"]);
710
- return new CliError({
711
- code: "REPO_CONNECTION_FAILED",
712
- domain: "project",
713
- summary,
714
- why: apiMessage ?? `The Management API returned status ${status || "unknown"}.`,
715
- fix: apiHint ?? repoConnectionFixForStatus(status),
716
- meta: {
717
- status,
718
- ...apiCode ? { apiCode } : {}
719
- },
720
- exitCode: 1,
721
- nextSteps: ["prisma-cli project show"]
722
- });
723
- }
724
- function repoConnectionFixForStatus(status) {
725
- if (status === 404) return "Install the GitHub App for this workspace, then rerun prisma-cli git connect.";
726
- if (status === 409) return "This project or repository is already linked. Disconnect the old link first, then try again.";
727
- if (status === 422) return "Make sure the GitHub App installation has access to this repository.";
728
- return "Re-run with --trace for the underlying API response details.";
729
- }
730
- //#endregion
731
- export { listFixtureWorkspaceProjects, listRealWorkspaceProjects, runGitConnect, runGitDisconnect, runProjectCreate, runProjectLink, runProjectList, runProjectShow };