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