Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ForgejoCli.ts

790 lines29.0 KB

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