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

ForgejoCli.ts

724 lines26.1 KB

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