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 yield* execute({ command: "fj", cwd, args: ["--host", login.url, "whoami"] });
437 // fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.
438 const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;
439 if (!refreshed)
440 return yield* new ForgejoCliError({
441 command: "fj",
442 cwd,
443 reason: "authentication",
444 detail: "fj has no credentials for this server. Authenticate again with fj.",
445 });
446 authenticated.set(login.url, { token: refreshed, time: now });
447 return refreshed;
448 }, authLock.withPermits(1));
449
450 const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(
451 "ForgejoCli.getAccount",
452 )(function* (input) {
453 const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });
454 const login = logins.find(
455 (item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),
456 );
457 if (!login)
458 return yield* new ForgejoCliError({
459 command: "fj",
460 cwd: input.cwd,
461 reason: "authentication",
462 detail: "fj has no credentials for this server.",
463 });
464 const token = yield* authenticateFj(input.cwd, login);
465 const currentUser = yield* requestFj({
466 cwd: input.cwd,
467 baseUrl: login.url.replace(/\/+$/, ""),
468 token,
469 path: "user",
470 });
471 const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);
472 if (Result.isFailure(user) || !user.success.login.trim())
473 return yield* new ForgejoCliError({
474 command: "fj",
475 cwd: input.cwd,
476 reason: "invalid-response",
477 detail: "Forgejo returned an invalid account response.",
478 });
479 return user.success.login;
480 });
481
482 const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (
483 input: ForgejoRepositoryInput,
484 hostOnly = false,
485 ) {
486 const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;
487 let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(
488 (value) => value && parseForgejoRemote(value),
489 );
490 let remote =
491 referenceRemote ??
492 (input.repository ? parseForgejoRemote(input.repository) : null) ??
493 (input.context ? parseForgejoRemote(input.context.remoteUrl) : null);
494 if (!remote && (!input.repository || input.host)) {
495 const result = yield* process
496 .run({
497 operation: "ForgejoCli.remote",
498 command: "git",
499 args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],
500 cwd: input.cwd,
501 allowNonZeroExit: true,
502 })
503 .pipe(
504 Effect.mapError(
505 (cause) =>
506 new ForgejoCliError({
507 command: "tea",
508 cwd: input.cwd,
509 detail: "Could not resolve the Forgejo repository remote.",
510 cause,
511 }),
512 ),
513 );
514 if (input.host) {
515 const matchingUrls = [
516 ...new Set(
517 result.stdout.split("\n").flatMap((line) => {
518 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
519 const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)(?:\s+\[[^\]]+\])?$/.exec(
520 line.trim(),
521 )?.[1];
522 return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()
523 ? [url]
524 : [];
525 }),
526 ),
527 ];
528 const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];
529 remoteUrl =
530 matchingUrls.length === 1
531 ? matchingUrls[0]
532 : origins.length === 1
533 ? origins[0]
534 : undefined;
535 } else {
536 remoteUrl = result.stdout.trim();
537 }
538 remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
539 }
540 if (
541 input.host &&
542 !remote?.ssh &&
543 remote?.host !== input.host.toLowerCase() &&
544 remote?.hostname !== input.host.toLowerCase()
545 )
546 remote = {
547 host: input.host.toLowerCase(),
548 hostname: input.host.split(":")[0] ?? input.host,
549 ssh: false,
550 path: remote?.path ?? "",
551 };
552 const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;
553 const fjLogins = yield* listLogins({
554 cwd: input.cwd,
555 command: "fj",
556 ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),
557 });
558 const requestedHost = input.host ?? input.context?.requestedHost;
559 const matchHostOnly = hostOnly || (!!input.host && !remote?.path);
560 const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>
561 remote
562 ? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)
563 : (logins.find((item) => item.default === "true") ??
564 (new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));
565 let login = selectLogin(fjLogins);
566 let command: "fj" | "tea" = "fj";
567 if (
568 !login &&
569 fjLogins.some(
570 (item) =>
571 !remote ||
572 matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),
573 )
574 ) {
575 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
576 Effect.result,
577 );
578 if (Result.isSuccess(available))
579 return yield* new ForgejoCliError({
580 command: "fj",
581 cwd: input.cwd,
582 reason: "authentication",
583 detail: "Multiple fj logins match this repository. Specify its full server URL.",
584 });
585 if (available.failure.reason !== "missing-cli") return yield* available.failure;
586 }
587 if (login) {
588 const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);
589 if (Result.isFailure(auth)) {
590 if (auth.failure.reason === "missing-cli") login = undefined;
591 else return yield* auth.failure;
592 }
593 }
594 if (!login) {
595 command = "tea";
596 login = selectLogin(yield* listLogins({ cwd: input.cwd, command: "tea" }));
597 }
598 if (!login)
599 return yield* new ForgejoCliError({
600 command: "tea",
601 cwd: input.cwd,
602 reason: "authentication",
603 detail:
604 "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.",
605 });
606 if (hostOnly)
607 return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };
608 const path =
609 referenceRemote?.path ??
610 (input.repository && !parseForgejoRemote(input.repository)
611 ? input.repository
612 : remote?.path) ??
613 "";
614 const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");
615 const relativePath =
616 basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)
617 ? path.slice(basePath.length + 1)
618 : path;
619 const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");
620 if (command === "fj" && !repositoryPath.includes("/")) {
621 login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };
622 }
623 const repository = repositoryPath.includes("/")
624 ? repositoryPath
625 : `${login.user}/${repositoryPath}`;
626 if (!/^[^/\s]+\/[^/\s]+$/.test(repository))
627 return yield* new ForgejoCliError({
628 command,
629 cwd: input.cwd,
630 detail: "Specify a Forgejo repository as owner/repository or its full server URL.",
631 });
632 return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };
633 });
634 const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);
635 const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {
636 const repository = yield* resolveTarget(
637 input,
638 input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),
639 );
640 const stdin =
641 input.body === undefined
642 ? undefined
643 : yield* encodeApiBody(input.body).pipe(
644 Effect.mapError(
645 (cause) =>
646 new ForgejoCliError({
647 command: "tea",
648 cwd: input.cwd,
649 detail: "Could not encode the Forgejo request body.",
650 cause,
651 }),
652 ),
653 );
654 let path = input.path.replace(/^\/+/, "");
655 if (input.repository && input.repository !== repository.repository) {
656 // Repository identities retain the server mount path; API routes do not.
657 const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
658 if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {
659 path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;
660 }
661 }
662 if (repository.command === "fj") {
663 const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;
664 if (!token)
665 return yield* new ForgejoCliError({
666 command: "fj",
667 cwd: input.cwd,
668 reason: "authentication",
669 detail: "fj has no credentials for this server.",
670 });
671 return yield* requestFj({
672 cwd: input.cwd,
673 baseUrl: repository.baseUrl,
674 token,
675 path,
676 ...(input.method === undefined ? {} : { method: input.method }),
677 ...(stdin === undefined ? {} : { body: stdin }),
678 });
679 }
680 const result = yield* execute({
681 cwd: input.cwd,
682 args: [
683 "api",
684 "--include",
685 "--login",
686 repository.login,
687 ...(repository.repository ? ["--repo", repository.repository] : []),
688 "--method",
689 input.method ?? "GET",
690 ...(input.body === undefined ? [] : ["--data", "@-"]),
691 `${repository.baseUrl}/api/v1/${path}`,
692 ],
693 ...(stdin === undefined ? {} : { stdin }),
694 });
695 // tea reports HTTP failures with exit code zero; use its response status.
696 const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);
697 if (!status || status >= 400)
698 return yield* new ForgejoCliError({
699 command: "tea",
700 cwd: input.cwd,
701 ...(status ? { httpStatus: status } : {}),
702 ...(status === 401
703 ? { reason: "authentication" as const }
704 : status === 403
705 ? { reason: "forbidden" as const }
706 : status === 404
707 ? { reason: "not-found" as const }
708 : status === 429
709 ? { reason: "rate-limit" as const }
710 : {}),
711 detail:
712 status === 401 || status === 403
713 ? "Forgejo denied access. Check this server's `tea login` credentials and permissions."
714 : status === 404
715 ? "Forgejo repository or pull request was not found."
716 : status === 429
717 ? "Forgejo API rate limit exceeded."
718 : `Forgejo API request failed${status ? ` (HTTP ${status})` : " without an HTTP status"}.`,
719 });
720 return result;
721 });
722 return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });
723});
724
725export const layer = Layer.effect(ForgejoCli, make);