Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Result from "effect/Result";
6import * as Clock from "effect/Clock";
7import * as FileSystem from "effect/FileSystem";
8import * as Semaphore from "effect/Semaphore";
9// @effect-diagnostics-next-line nodeBuiltinImport:off - fj storage paths use explicit Windows and POSIX layouts, independently of this process's platform.
10import * as NodePath from "node:path";
11import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
12import { ChildProcessSpawner } from "effect/process";
13import { decodeJsonResult } from "@t3tools/shared/schemaJson";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
16import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
17import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
18
19const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
20
21export class ForgejoCliError extends Schema.TaggedError<ForgejoCliError>()("ForgejoCliError", {
22 command: Schema.Literals(["fj", "tea"]),
23 cwd: Schema.String,
24 detail: Schema.String,
25 reason: Schema.optional(
26 Schema.Literals([
27 "missing-cli",
28 "authentication",
29 "forbidden",
30 "not-found",
31 "rate-limit",
32 "invalid-response",
33 ]),
34 ),
35 httpStatus: Schema.optional(Schema.Int),
36 cause: Schema.optional(Schema.Defect()),
37}) {}
38
39export const ForgejoLoginSchema = Schema.Struct({
40 name: Schema.String,
41 url: Schema.String,
42 ssh_host: Schema.optional(Schema.String),
43 valid: Schema.optional(Schema.String),
44 user: Schema.String,
45 default: Schema.String,
46});
47
48export function parseForgejoLogins(raw: string) {
49 const decoded = decodeJsonResult(Schema.Array(ForgejoLoginSchema))(raw);
50 return Result.isSuccess(decoded) ? decoded.success : [];
51}
52
53export const ForgejoKeysSchema = Schema.Struct({
54 hosts: Schema.Record(
55 Schema.String,
56 Schema.Struct({
57 type: Schema.Literals(["Application", "OAuth"]),
58 token: Schema.String,
59 }),
60 ),
61 aliases: Schema.optional(Schema.Record(Schema.String, Schema.String)),
62});
63
64const parseForgejoKeys = decodeJsonResult(ForgejoKeysSchema);
65
66function forgejoKeysPaths(input: {
67 readonly platform: string;
68 readonly home: string;
69 readonly dataHome?: string;
70 readonly appData?: string;
71}) {
72 if (input.platform === "darwin")
73 return ["forgejo-cli", "Cyborus"].map((organization) =>
74 NodePath.join(
75 input.home,
76 "Library",
77 "Application Support",
78 `${organization}.forgejo-cli`,
79 "keys.json",
80 ),
81 );
82 if (input.platform === "win32")
83 return ["forgejo-cli", "Cyborus"].map((organization) =>
84 NodePath.win32.join(
85 input.appData || NodePath.win32.join(input.home, "AppData", "Roaming"),
86 organization,
87 "forgejo-cli",
88 "data",
89 "keys.json",
90 ),
91 );
92 return [
93 NodePath.join(
94 input.dataHome && NodePath.isAbsolute(input.dataHome)
95 ? input.dataHome
96 : NodePath.join(input.home, ".local", "share"),
97 "forgejo-cli",
98 "keys.json",
99 ),
100 ];
101}
102
103export interface ForgejoRepositoryInput {
104 readonly cwd: string;
105 readonly context?: SourceControlProviderContext;
106 readonly repository?: string;
107 readonly reference?: string;
108 readonly host?: string;
109}
110
111export interface ForgejoRepository {
112 readonly command?: "fj" | "tea";
113 readonly login: string;
114 readonly repository: string;
115 readonly baseUrl: string;
116}
117
118export interface ForgejoApiInput extends ForgejoRepositoryInput {
119 readonly path: string;
120 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
121 readonly body?: unknown;
122}
123
124export class ForgejoCli extends Context.Service<
125 ForgejoCli,
126 {
127 readonly execute: (input: {
128 readonly command?: "fj" | "tea";
129 readonly cwd: string;
130 readonly args: ReadonlyArray<string>;
131 readonly stdin?: string;
132 readonly timeoutMs?: number;
133 readonly maxOutputBytes?: number;
134 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
135 readonly listLogins?: (input: {
136 readonly cwd: string;
137 readonly command: "fj" | "tea";
138 readonly remoteUrl?: string;
139 }) => Effect.Effect<ReturnType<typeof parseForgejoLogins>, ForgejoCliError>;
140 readonly getAccount?: (input: {
141 readonly cwd: string;
142 readonly baseUrl: string;
143 }) => Effect.Effect<string, ForgejoCliError>;
144 readonly resolveRepository: (
145 input: ForgejoRepositoryInput,
146 ) => Effect.Effect<ForgejoRepository, ForgejoCliError>;
147 readonly api: (
148 input: ForgejoApiInput,
149 ) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
150 }
151>()("@t3tools/source-control-forgejo/server/ForgejoCli") {}
152
153export function parseForgejoRemote(value: string) {
154 if (/^(?:https?|ssh):\/\//i.test(value)) {
155 try {
156 const url = new URL(value);
157 return {
158 host: url.host.toLowerCase(),
159 hostname: url.hostname.toLowerCase(),
160 ssh: url.protocol === "ssh:",
161 path: url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, ""),
162 };
163 } catch {
164 return null;
165 }
166 }
167 // SCP remotes may omit the username; URL treats these as a custom scheme.
168 const ssh = /^(?:[^@/]+@)?([^:/]+):([^/].*)$/.exec(value);
169 return ssh?.[1] && ssh[2]
170 ? {
171 host: ssh[1].toLowerCase(),
172 hostname: ssh[1].toLowerCase(),
173 ssh: true,
174 path: ssh[2].replace(/\.git$/, ""),
175 }
176 : null;
177}
178
179export function matchForgejoLogin(
180 logins: ReturnType<typeof parseForgejoLogins>,
181 remote: NonNullable<ReturnType<typeof parseForgejoRemote>>,
182 requestedHost?: string,
183 hostOnly = false,
184) {
185 const matches = [
186 ...new Map(
187 logins
188 .filter((login) => {
189 const url = parseForgejoRemote(login.url);
190 if (!url) return false;
191 if (requestedHost !== undefined && url.host !== requestedHost.toLowerCase()) return false;
192 return remote.ssh
193 ? login.ssh_host?.toLowerCase() === remote.host ||
194 login.ssh_host?.toLowerCase() === remote.hostname ||
195 url.hostname === remote.hostname
196 : url.host === remote.host &&
197 ((hostOnly && !remote.path) ||
198 !url.path ||
199 remote.path === url.path ||
200 remote.path.startsWith(`${url.path}/`));
201 })
202 .map((login) => [login.name, login]),
203 ).values(),
204 ];
205 return matches.length === 1
206 ? matches[0]
207 : new Set(matches.map((login) => login.url)).size === 1
208 ? matches.find((login) => login.default === "true")
209 : undefined;
210}
211
212export const make = Effect.gen(function* () {
213 const { process } = yield* SourceControlHost.SourceControlHost;
214 const fileSystem = yield* FileSystem.FileSystem;
215 const httpClient = yield* HttpClient.HttpClient;
216 const authLock = yield* Semaphore.make(1);
217 const authenticated = new Map<string, { token: string; time: number }>();
218 const execute: ForgejoCli["Service"]["execute"] = (input) =>
219 process
220 .run({
221 ...input,
222 operation: "ForgejoCli.execute",
223 command: input.command ?? "tea",
224 timeoutMs: input.timeoutMs ?? 30_000,
225 })
226 .pipe(
227 Effect.mapError(
228 (cause) =>
229 new ForgejoCliError({
230 command: input.command ?? "tea",
231 cwd: input.cwd,
232 ...(input.command === "fj" ? {} : { cause }),
233 ...(cause._tag === "VcsProcessSpawnError"
234 ? { reason: "missing-cli" as const }
235 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
236 ? { reason: "authentication" as const }
237 : {}),
238 detail:
239 cause._tag === "VcsProcessSpawnError"
240 ? "Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`tea` 0.16 or later) and retry."
241 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
242 ? "Authenticate this server with `fj auth login`, `fj auth add-token`, or `tea login add`."
243 : "Forgejo CLI command failed.",
244 }),
245 ),
246 );
247
248 const readKeys = Effect.fn("ForgejoCli.readKeys")(function* (cwd: string) {
249 for (const path of forgejoKeysPaths({
250 platform: yield* HostProcess.Platform,
251 home: yield* HostProcess.HomeDirectory,
252 ...(globalThis.process.env.XDG_DATA_HOME
253 ? { dataHome: globalThis.process.env.XDG_DATA_HOME }
254 : {}),
255 ...(globalThis.process.env.APPDATA ? { appData: globalThis.process.env.APPDATA } : {}),
256 })) {
257 const exists = yield* fileSystem.exists(path).pipe(
258 Effect.mapError(
259 () =>
260 new ForgejoCliError({
261 command: "fj",
262 cwd,
263 reason: "authentication",
264 detail: "Could not read fj authentication storage.",
265 }),
266 ),
267 );
268 if (!exists) continue;
269 const raw = yield* fileSystem.readFileString(path).pipe(
270 Effect.mapError(
271 () =>
272 new ForgejoCliError({
273 command: "fj",
274 cwd,
275 reason: "authentication",
276 detail: "Could not read fj authentication storage.",
277 }),
278 ),
279 );
280 const decoded = parseForgejoKeys(raw);
281 if (Result.isFailure(decoded))
282 return yield* new ForgejoCliError({
283 command: "fj",
284 cwd,
285 reason: "authentication",
286 detail: "fj authentication storage is invalid. Authenticate again with fj.",
287 });
288 return decoded.success;
289 }
290 const empty: typeof ForgejoKeysSchema.Type = { hosts: {}, aliases: {} };
291 return empty;
292 });
293
294 const publicLogins = (
295 keys: typeof ForgejoKeysSchema.Type,
296 remoteUrl?: string,
297 ): ReturnType<typeof parseForgejoLogins> => {
298 const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
299 return Object.keys(keys.hosts).flatMap((host) => {
300 const url = parseForgejoRemote(`https://${host}`);
301 // fj 0.6 drops URL mounts during whoami and OAuth renewal; tea supports them.
302 if (!url || url.path) return [];
303 // fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP.
304 const scheme =
305 remote && !remote.ssh && remote.host === url.host && /^http:\/\//i.test(remoteUrl ?? "")
306 ? "http"
307 : "https";
308 const login = { name: host, url: `${scheme}://${host}`, user: "", default: "false" };
309 const aliases = Object.entries(keys.aliases ?? {})
310 .filter(([, target]) => target === host)
311 .map(([alias]) => ({ ...login, ssh_host: alias }));
312 return aliases.length ? aliases : [login];
313 });
314 };
315
316 const listLogins: NonNullable<ForgejoCli["Service"]["listLogins"]> = Effect.fn(
317 "ForgejoCli.listLogins",
318 )(function* (input) {
319 if (input.command === "fj") {
320 const keys = yield* readKeys(input.cwd).pipe(Effect.result);
321 if (Result.isFailure(keys)) {
322 // Stale credentials from an uninstalled fj must not disable an available tea login.
323 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
324 Effect.result,
325 );
326 if (Result.isFailure(available) && available.failure.reason === "missing-cli") return [];
327 return yield* keys.failure;
328 }
329 return publicLogins(keys.success, input.remoteUrl);
330 }
331 return parseForgejoLogins(
332 (yield* execute({ cwd: input.cwd, args: ["login", "list", "--output", "json"] })).stdout,
333 );
334 });
335
336 const requestFj = Effect.fn("ForgejoCli.requestFj")(
337 function* (input: {
338 readonly cwd: string;
339 readonly baseUrl: string;
340 readonly token: string;
341 readonly path: string;
342 readonly method?: ForgejoApiInput["method"];
343 readonly body?: string;
344 }) {
345 const base = new URL(`${input.baseUrl}/api/v1/`);
346 const url = new URL(input.path, base);
347 if (
348 url.origin !== base.origin ||
349 !url.pathname.startsWith(base.pathname) ||
350 url.username ||
351 url.password
352 )
353 return yield* new ForgejoCliError({
354 command: "fj",
355 cwd: input.cwd,
356 detail: "Invalid Forgejo API path.",
357 });
358 let request = HttpClientRequest.make(input.method ?? "GET")(url.toString()).pipe(
359 HttpClientRequest.setHeader("Authorization", `token ${input.token}`),
360 );
361 if (input.body !== undefined)
362 request = request.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
363 const response = yield* httpClient
364 .execute(request)
365 .pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
366 const status = response.status;
367 const body =
368 status === 204 || status === 205
369 ? { text: "", truncated: false, invalidUtf8: false }
370 : yield* collectUint8StreamText({
371 stream: response.stream,
372 maxBytes: 8 * 1024 * 1024,
373 });
374 if (body.truncated || body.invalidUtf8)
375 return yield* new ForgejoCliError({
376 command: "fj",
377 cwd: input.cwd,
378 reason: "invalid-response",
379 detail: "Forgejo returned an oversized or invalid response.",
380 });
381 if (status < 200 || status >= 300) {
382 const detail =
383 status === 404
384 ? "Forgejo repository or pull request was not found."
385 : body.text
386 ? `Forgejo API request failed (HTTP ${status}): ${body.text}`
387 : `Forgejo API request failed (HTTP ${status}). Check this server's fj credentials and permissions.`;
388 return yield* new ForgejoCliError({
389 command: "fj",
390 cwd: input.cwd,
391 httpStatus: status,
392 ...(status === 401
393 ? { reason: "authentication" as const }
394 : status === 403
395 ? { reason: "forbidden" as const }
396 : status === 404
397 ? { reason: "not-found" as const }
398 : status === 429
399 ? { reason: "rate-limit" as const }
400 : {}),
401 detail,
402 });
403 }
404 return {
405 exitCode: ChildProcessSpawner.ExitCode(0),
406 stdout: body.text,
407 stderr: `HTTP/1.1 ${status}\n${response.headers.link ? `link: ${response.headers.link}\n` : ""}`,
408 stdoutTruncated: false,
409 stderrTruncated: false,
410 };
411 },
412 (effect, input) =>
413 effect.pipe(
414 Effect.timeout(30_000),
415 Effect.mapError((error) =>
416 error._tag === "ForgejoCliError"
417 ? error
418 : new ForgejoCliError({
419 command: "fj",
420 cwd: input.cwd,
421 detail: "Forgejo API request failed or timed out.",
422 }),
423 ),
424 ),
425 );
426
427 const authenticateFj = Effect.fn("ForgejoCli.authenticateFj")(function* (
428 cwd: string,
429 login: typeof ForgejoLoginSchema.Type,
430 ) {
431 const keys = yield* readKeys(cwd);
432 const token = keys.hosts[login.name]?.token;
433 const now = yield* Clock.currentTimeMillis;
434 const cached = authenticated.get(login.url);
435 if (token && cached?.token === token && now - cached.time < 30_000) return token;
436 // fj reads the cwd repository even with --host and fails on an unborn branch.
437 yield* execute({
438 command: "fj",
439 cwd: yield* HostProcess.HomeDirectory,
440 args: ["--host", login.url, "whoami"],
441 });
442 // fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.
443 const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;
444 if (!refreshed)
445 return yield* new ForgejoCliError({
446 command: "fj",
447 cwd,
448 reason: "authentication",
449 detail: "fj has no credentials for this server. Authenticate again with fj.",
450 });
451 authenticated.set(login.url, { token: refreshed, time: now });
452 return refreshed;
453 }, authLock.withPermits(1));
454
455 const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(
456 "ForgejoCli.getAccount",
457 )(function* (input) {
458 const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });
459 const login = logins.find(
460 (item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),
461 );
462 if (!login)
463 return yield* new ForgejoCliError({
464 command: "fj",
465 cwd: input.cwd,
466 reason: "authentication",
467 detail: "fj has no credentials for this server.",
468 });
469 const token = yield* authenticateFj(input.cwd, login);
470 const currentUser = yield* requestFj({
471 cwd: input.cwd,
472 baseUrl: login.url.replace(/\/+$/, ""),
473 token,
474 path: "user",
475 });
476 const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);
477 if (Result.isFailure(user) || !user.success.login.trim())
478 return yield* new ForgejoCliError({
479 command: "fj",
480 cwd: input.cwd,
481 reason: "invalid-response",
482 detail: "Forgejo returned an invalid account response.",
483 });
484 return user.success.login;
485 });
486
487 const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (
488 input: ForgejoRepositoryInput,
489 hostOnly = false,
490 ) {
491 const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;
492 let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(
493 (value) => value && parseForgejoRemote(value),
494 );
495 let remote =
496 referenceRemote ??
497 (input.repository ? parseForgejoRemote(input.repository) : null) ??
498 (input.context ? parseForgejoRemote(input.context.remoteUrl) : null);
499 if (!remote && (!input.repository || input.host)) {
500 const result = yield* process
501 .run({
502 operation: "ForgejoCli.remote",
503 command: "git",
504 args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],
505 cwd: input.cwd,
506 allowNonZeroExit: true,
507 })
508 .pipe(
509 Effect.mapError(
510 (cause) =>
511 new ForgejoCliError({
512 command: "tea",
513 cwd: input.cwd,
514 detail: "Could not resolve the Forgejo repository remote.",
515 cause,
516 }),
517 ),
518 );
519 if (input.host) {
520 const matchingUrls = [
521 ...new Set(
522 result.stdout.split("\n").flatMap((line) => {
523 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
524 const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)(?:\s+\[[^\]]+\])?$/.exec(
525 line.trim(),
526 )?.[1];
527 return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()
528 ? [url]
529 : [];
530 }),
531 ),
532 ];
533 const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];
534 remoteUrl =
535 matchingUrls.length === 1
536 ? matchingUrls[0]
537 : origins.length === 1
538 ? origins[0]
539 : undefined;
540 } else {
541 remoteUrl = result.stdout.trim();
542 }
543 remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
544 }
545 if (
546 input.host &&
547 !remote?.ssh &&
548 remote?.host !== input.host.toLowerCase() &&
549 remote?.hostname !== input.host.toLowerCase()
550 )
551 remote = {
552 host: input.host.toLowerCase(),
553 hostname: input.host.split(":")[0] ?? input.host,
554 ssh: false,
555 path: remote?.path ?? "",
556 };
557 const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;
558 const fjLogins = yield* listLogins({
559 cwd: input.cwd,
560 command: "fj",
561 ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),
562 });
563 const requestedHost = input.host ?? input.context?.requestedHost;
564 const matchHostOnly = hostOnly || (!!input.host && !remote?.path);
565 const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>
566 remote
567 ? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)
568 : (logins.find((item) => item.default === "true") ??
569 (new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));
570 let login = selectLogin(fjLogins);
571 let command: "fj" | "tea" = "fj";
572 if (
573 !login &&
574 fjLogins.some(
575 (item) =>
576 !remote ||
577 matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),
578 )
579 ) {
580 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
581 Effect.result,
582 );
583 if (Result.isSuccess(available))
584 return yield* new ForgejoCliError({
585 command: "fj",
586 cwd: input.cwd,
587 reason: "authentication",
588 detail: "Multiple fj logins match this repository. Specify its full server URL.",
589 });
590 if (available.failure.reason !== "missing-cli") return yield* available.failure;
591 }
592 if (login) {
593 const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);
594 if (Result.isFailure(auth)) {
595 if (auth.failure.reason === "missing-cli") login = undefined;
596 else return yield* auth.failure;
597 }
598 }
599 if (!login) {
600 command = "tea";
601 login = selectLogin(yield* listLogins({ cwd: input.cwd, command: "tea" }));
602 }
603 if (!login)
604 return yield* new ForgejoCliError({
605 command: "tea",
606 cwd: input.cwd,
607 reason: "authentication",
608 detail:
609 "No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server; choose a default when multiple tea accounts match.",
610 });
611 if (hostOnly)
612 return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };
613 const path =
614 referenceRemote?.path ??
615 (input.repository && !parseForgejoRemote(input.repository)
616 ? input.repository
617 : remote?.path) ??
618 "";
619 const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");
620 const relativePath =
621 basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)
622 ? path.slice(basePath.length + 1)
623 : path;
624 const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");
625 if (command === "fj" && !repositoryPath.includes("/")) {
626 login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };
627 }
628 const repository = repositoryPath.includes("/")
629 ? repositoryPath
630 : `${login.user}/${repositoryPath}`;
631 if (!/^[^/\s]+\/[^/\s]+$/.test(repository))
632 return yield* new ForgejoCliError({
633 command,
634 cwd: input.cwd,
635 detail: "Specify a Forgejo repository as owner/repository or its full server URL.",
636 });
637 return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };
638 });
639 const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);
640 const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {
641 const repository = yield* resolveTarget(
642 input,
643 input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),
644 );
645 const stdin =
646 input.body === undefined
647 ? undefined
648 : yield* encodeApiBody(input.body).pipe(
649 Effect.mapError(
650 (cause) =>
651 new ForgejoCliError({
652 command: "tea",
653 cwd: input.cwd,
654 detail: "Could not encode the Forgejo request body.",
655 cause,
656 }),
657 ),
658 );
659 let path = input.path.replace(/^\/+/, "");
660 if (input.repository && input.repository !== repository.repository) {
661 // Repository identities retain the server mount path; API routes do not.
662 const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
663 if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {
664 path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;
665 }
666 }
667 if (repository.command === "fj") {
668 const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;
669 if (!token)
670 return yield* new ForgejoCliError({
671 command: "fj",
672 cwd: input.cwd,
673 reason: "authentication",
674 detail: "fj has no credentials for this server.",
675 });
676 return yield* requestFj({
677 cwd: input.cwd,
678 baseUrl: repository.baseUrl,
679 token,
680 path,
681 ...(input.method === undefined ? {} : { method: input.method }),
682 ...(stdin === undefined ? {} : { body: stdin }),
683 });
684 }
685 const result = yield* execute({
686 cwd: input.cwd,
687 args: [
688 "api",
689 "--include",
690 "--login",
691 repository.login,
692 ...(repository.repository ? ["--repo", repository.repository] : []),
693 "--method",
694 input.method ?? "GET",
695 ...(input.body === undefined ? [] : ["--data", "@-"]),
696 `${repository.baseUrl}/api/v1/${path}`,
697 ],
698 ...(stdin === undefined ? {} : { stdin }),
699 });
700 // tea reports HTTP failures with exit code zero; use its response status.
701 const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);
702 if (!status || status >= 400)
703 return yield* new ForgejoCliError({
704 command: "tea",
705 cwd: input.cwd,
706 ...(status ? { httpStatus: status } : {}),
707 ...(status === 401
708 ? { reason: "authentication" as const }
709 : status === 403
710 ? { reason: "forbidden" as const }
711 : status === 404
712 ? { reason: "not-found" as const }
713 : status === 429
714 ? { reason: "rate-limit" as const }
715 : {}),
716 detail:
717 status === 401 || status === 403
718 ? "Forgejo denied access. Check this server's `tea login` credentials and permissions."
719 : status === 404
720 ? "Forgejo repository or pull request was not found."
721 : status === 429
722 ? "Forgejo API rate limit exceeded."
723 : `Forgejo API request failed${status ? ` (HTTP ${status})` : " without an HTTP status"}.`,
724 });
725 return result;
726 });
727 return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });
728});
729
730export const layer = Layer.effect(ForgejoCli, make);