Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Schedule from "effect/Schedule";
4import * as Schema from "effect/Schema";
5import { SourceControlProviderError, SourceControlProviderKind } from "@t3tools/contracts";
6import { CURSOR_ORIGIN_WEB_BASE_URL } from "../shared/definition.ts";
7import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
8import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
9import {
10 probeSourceControlProvider,
11 providerAuth,
12 type SourceControlCliDiscoverySpec,
13 type SourceControlManagedCliDiscoverySpec,
14} from "@t3tools/source-control-core/server/discovery";
15
16import * as OriginCli from "./OriginCli.ts";
17import {
18 OriginPullRequestListSchema,
19 OriginPullRequestSchema,
20 OriginRepositorySchema,
21 pullReference,
22 toOriginChangeRequest,
23 type OriginRepository,
24} from "./originPullRequests.ts";
25
26const isOriginCliError = Schema.is(OriginCli.OriginCliError);
27
28const discovery = {
29 type: "cli",
30 kind: SourceControlProviderKind.make("cursor-origin"),
31 label: "Cursor Origin",
32 executable: OriginCli.ORIGIN_COMMAND,
33 versionArgs: ["--version"],
34 authArgs: ["auth", "status", "--json"],
35 parseAuth: (input) => {
36 const status = OriginCli.parseOriginAuthStatus(input.stdout);
37 const account = OriginCli.originAccount(status);
38 if (status === null) return providerAuth({ status: "unknown" });
39 return status.authenticated && status.tokenValid !== false
40 ? providerAuth({
41 status: "authenticated",
42 account: account ?? undefined,
43 host: "origin.cursor.com",
44 })
45 : providerAuth({
46 status: "unauthenticated",
47 detail: "Run `origin auth login` to sign in to Cursor Origin.",
48 });
49 },
50 installHint:
51 "Install the Origin CLI with `curl -fsSL https://downloads.cursor.com/origin/install.sh | sh`, then run `origin auth login`.",
52} satisfies SourceControlCliDiscoverySpec;
53
54/**
55 * Discovery names the account by its namespace slug, which is what owns its repositories (and so
56 * what Publish fills in), rather than the email `origin auth status` reports.
57 */
58export const makeDiscovery = Effect.gen(function* () {
59 const cli = yield* OriginCli.OriginCli;
60 const { process } = yield* SourceControlHost.SourceControlHost;
61 return {
62 type: "managed-cli",
63 kind: discovery.kind,
64 label: discovery.label,
65 installHint: discovery.installHint,
66 probe: Effect.fn("OriginSourceControlProvider.discovery")(function* (cwd: string) {
67 const item = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
68 if (item.status !== "available" || item.auth.status !== "authenticated") return item;
69 const namespace = yield* cli.personalNamespace(cwd).pipe(Effect.option);
70 return { ...item, auth: { ...item.auth, account: namespace } };
71 }),
72 // `origin.cursor.com` is recognised from the remote alone, so there is nothing to refine.
73 refineUnknownRemote: () => Effect.succeed(null),
74 } satisfies SourceControlManagedCliDiscoverySpec;
75});
76
77const cloneUrls = (repository: OriginRepository, fallbackName: string) => {
78 const nameWithOwner =
79 repository.fullName ??
80 (repository.owner ? `${repository.owner.slug}/${repository.name}` : fallbackName);
81 const url = repository.cloneUrl ?? `https://origin.cursor.com/${nameWithOwner}.git`;
82 // Origin documents no SSH clone URL, and `origin auth login` already configures git's HTTPS
83 // credential helper, so HTTPS stands in for both.
84 return { nameWithOwner, url, sshUrl: url };
85};
86
87export const make = Effect.gen(function* () {
88 const cli = yield* OriginCli.OriginCli;
89 const fs = yield* FileSystem.FileSystem;
90 const { git } = yield* SourceControlHost.SourceControlHost;
91
92 const mapError = (
93 operation: string,
94 cwd: string,
95 extra?: { readonly repository?: string; readonly reference?: string },
96 ) =>
97 Effect.mapError(
98 (cause: unknown) =>
99 new SourceControlProviderError({
100 provider: SourceControlProviderKind.make("cursor-origin"),
101 operation,
102 cwd,
103 command: OriginCli.ORIGIN_COMMAND,
104 ...(extra?.repository
105 ? {
106 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
107 extra.repository,
108 ),
109 }
110 : {}),
111 ...(extra?.reference
112 ? {
113 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
114 extra.reference,
115 ),
116 }
117 : {}),
118 detail: isOriginCliError(cause) ? cause.detail : "Cursor Origin operation failed.",
119 cause,
120 }),
121 );
122
123 const getRepository = (cwd: string, repository: string, operation: string) =>
124 cli.api(
125 { cwd, operation, path: OriginCli.originRepositoryPath(repository) },
126 OriginRepositorySchema,
127 );
128
129 return SourceControlProvider.SourceControlProvider.of({
130 kind: SourceControlProviderKind.make("cursor-origin"),
131
132 /** Origin's browser pages live on cursor.com, not on the git host the remote names. */
133 refineRepositoryIdentity: Effect.fn("OriginSourceControlProvider.refineRepositoryIdentity")(
134 ({ identity }) => {
135 const path = SourceControlProvider.repositoryPathFromRemoteUrl(identity.locator.remoteUrl);
136 return Effect.succeed(
137 identity.provider === "cursor-origin" && path
138 ? { ...identity, webUrl: `${CURSOR_ORIGIN_WEB_BASE_URL}/${path}` }
139 : identity,
140 );
141 },
142 ),
143
144 listChangeRequests: Effect.fn("OriginSourceControlProvider.listChangeRequests")(
145 function* (input) {
146 const repository = yield* cli.resolveRepository(input);
147 const head = SourceControlProvider.sourceBranch(input);
148 const limit = Math.min(Math.max(input.limit ?? 20, 1), 100);
149 const query = new URLSearchParams({
150 head,
151 state: input.state,
152 pageSize: String(limit),
153 sortBy: "updated",
154 });
155 const page = yield* cli.api(
156 {
157 cwd: input.cwd,
158 operation: "listChangeRequests",
159 path: `${OriginCli.originRepositoryPath(repository)}/pulls?${query}`,
160 },
161 OriginPullRequestListSchema,
162 );
163 return (page.pullRequests ?? []).map(toOriginChangeRequest);
164 },
165 (effect, input) =>
166 effect.pipe(mapError("listChangeRequests", input.cwd, { reference: input.headSelector })),
167 ),
168
169 getChangeRequest: Effect.fn("OriginSourceControlProvider.getChangeRequest")(
170 function* (input) {
171 const reference = pullReference(input.reference);
172 const repository = reference.repository ?? (yield* cli.resolveRepository(input));
173 const number = reference.number;
174 if (number === null)
175 return yield* new OriginCli.OriginCliError({
176 operation: "getChangeRequest",
177 cwd: input.cwd,
178 reason: "not-found",
179 detail: "Specify a pull request number or Cursor Origin pull request URL.",
180 });
181 return toOriginChangeRequest(
182 yield* cli.api(
183 {
184 cwd: input.cwd,
185 operation: "getChangeRequest",
186 path: `${OriginCli.originRepositoryPath(repository)}/pulls/${number}`,
187 },
188 OriginPullRequestSchema,
189 ),
190 );
191 },
192 (effect, input) =>
193 effect.pipe(mapError("getChangeRequest", input.cwd, { reference: input.reference })),
194 ),
195
196 createsDraftChangeRequests: true,
197 createChangeRequest: Effect.fn("OriginSourceControlProvider.createChangeRequest")(
198 function* (input) {
199 const repository = input.target?.repository ?? (yield* cli.resolveRepository(input));
200 // Origin creates drafts unless told otherwise, so `draft` is always sent.
201 yield* cli.api(
202 {
203 cwd: input.cwd,
204 operation: "createChangeRequest",
205 method: "POST",
206 path: `${OriginCli.originRepositoryPath(repository)}/pulls`,
207 body: {
208 title: input.title,
209 body: yield* fs.readFileString(input.bodyFile),
210 head: SourceControlProvider.sourceBranch(input),
211 base: input.target?.refName ?? input.baseRefName,
212 draft: input.draft === true,
213 },
214 },
215 Schema.Unknown,
216 );
217 },
218 (effect, input) =>
219 effect.pipe(mapError("createChangeRequest", input.cwd, { reference: input.headSelector })),
220 ),
221
222 getRepositoryCloneUrls: Effect.fn("OriginSourceControlProvider.getRepositoryCloneUrls")(
223 function* (input) {
224 const repositoryName = OriginCli.parseOriginRepository(input.repository);
225 if (repositoryName === null) {
226 const detail = "Specify an Origin repository as owner/name or a Cursor Origin URL.";
227 return yield* new OriginCli.OriginCliError({
228 operation: "getRepositoryCloneUrls",
229 cwd: input.cwd,
230 reason: "failed",
231 detail,
232 userFacingDetail: detail,
233 });
234 }
235 const repository = yield* getRepository(
236 input.cwd,
237 repositoryName,
238 "getRepositoryCloneUrls",
239 ).pipe(
240 Effect.mapError((error) =>
241 error.reason === "not-found"
242 ? new OriginCli.OriginCliError({
243 ...error,
244 userFacingDetail: SourceControlProvider.repositoryNotFoundDetail(repositoryName),
245 })
246 : error.httpStatus === 403
247 ? new OriginCli.OriginCliError({
248 ...error,
249 userFacingDetail: `Your Cursor account does not have access to ${SourceControlProvider.transportSafeSourceControlErrorValue(repositoryName)} on Origin. Ask the repository owner for access and try again.`,
250 })
251 : error,
252 ),
253 );
254 return cloneUrls(repository, repositoryName);
255 },
256 (effect, input) =>
257 effect.pipe(
258 mapError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
259 ),
260 ),
261
262 createRepository: Effect.fn("OriginSourceControlProvider.createRepository")(
263 function* (input) {
264 if (input.visibility === "public")
265 return yield* new OriginCli.OriginCliError({
266 operation: "createRepository",
267 cwd: input.cwd,
268 reason: "failed",
269 detail: "Cursor Origin repositories are private. Choose private visibility.",
270 });
271 const parts = input.repository.split("/");
272 if (parts.length > 2 || parts.some((part) => part.trim().length === 0))
273 return yield* new OriginCli.OriginCliError({
274 operation: "createRepository",
275 cwd: input.cwd,
276 reason: "failed",
277 detail: "Specify an Origin repository as owner/name or name.",
278 });
279 const [owner, name] =
280 parts.length === 2 ? parts : [yield* cli.personalNamespace(input.cwd), input.repository];
281 yield* cli.api(
282 {
283 cwd: input.cwd,
284 operation: "createRepository",
285 method: "POST",
286 path: `/v1/origin/repos/${encodeURIComponent(owner ?? "")}`,
287 body: { name },
288 },
289 OriginRepositorySchema,
290 );
291 // Origin creates repositories internal (visible to the whole team) and only takes a
292 // visibility on update, so the repository is made private straight after.
293 const madePrivate = yield* cli
294 .api(
295 {
296 cwd: input.cwd,
297 operation: "createRepository",
298 method: "PATCH",
299 path: OriginCli.originRepositoryPath(`${owner}/${name}`),
300 body: { visibility: "private" },
301 },
302 OriginRepositorySchema,
303 )
304 .pipe(
305 Effect.retry({
306 times: 2,
307 schedule: Schedule.spaced("1 second"),
308 while: (error) =>
309 error.reason !== "rate-limited" && error.reason !== "unauthenticated",
310 }),
311 Effect.mapError(
312 (cause) =>
313 new OriginCli.OriginCliError({
314 operation: "createRepository",
315 cwd: input.cwd,
316 reason: cause.reason,
317 ...(cause.retryAt === undefined ? {} : { retryAt: cause.retryAt }),
318 detail: `Created ${owner}/${name}, but could not make it private, so your Cursor team can still see it. Set it to private on cursor.com.`,
319 cause,
320 }),
321 ),
322 );
323 return cloneUrls(madePrivate, `${owner}/${name}`);
324 },
325 (effect, input) =>
326 effect.pipe(mapError("createRepository", input.cwd, { repository: input.repository })),
327 ),
328
329 getDefaultBranch: Effect.fn("OriginSourceControlProvider.getDefaultBranch")(
330 function* (input) {
331 const repository = yield* cli.resolveRepository(input);
332 return (
333 (yield* getRepository(input.cwd, repository, "getDefaultBranch")).defaultBranch ?? null
334 );
335 },
336 (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
337 ),
338
339 checkoutChangeRequest: Effect.fn("OriginSourceControlProvider.checkoutChangeRequest")(
340 function* (input) {
341 const repository = yield* cli.resolveRepository(input);
342 const { repository: linked, number } = pullReference(input.reference);
343 const reference = input.reference.trim();
344 // The CLI reads a leading dash as a flag and ignores a target after `--`; no branch starts
345 // with one.
346 if (number === null && reference.startsWith("-"))
347 return yield* new OriginCli.OriginCliError({
348 operation: "checkoutChangeRequest",
349 cwd: input.cwd,
350 reason: "not-found",
351 detail: "Specify a pull request number, branch, or Cursor Origin pull request URL.",
352 });
353 if (linked !== null && linked !== repository.toLowerCase())
354 return yield* new OriginCli.OriginCliError({
355 operation: "checkoutChangeRequest",
356 cwd: input.cwd,
357 reason: "not-found",
358 detail: `That pull request is in ${linked}, not this checkout's ${repository}.`,
359 });
360 yield* cli.execute({
361 cwd: input.cwd,
362 operation: "checkoutChangeRequest",
363 args: [
364 "pr",
365 "checkout",
366 "-R",
367 repository,
368 "--remote",
369 input.context?.remoteName ?? (yield* git.resolvePrimaryRemoteName(input.cwd)),
370 ...(input.force ? ["--force"] : []),
371 number === null ? reference : String(number),
372 ],
373 });
374 },
375 (effect, input) =>
376 effect.pipe(mapError("checkoutChangeRequest", input.cwd, { reference: input.reference })),
377 ),
378 });
379});