@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 135 lines 5.45 KB
Raw
1 import { Credentials, DEFAULT_API_BASE_URL } from "@distilled.cloud/github/Credentials";
2 import type { ConfigError } from "@distilled.cloud/github/Errors";
3 import { AuthError } from "alchemy/Auth/AuthProvider";
4 import { getEnv } from "alchemy/Auth/Env";
5 import * as Effect from "effect/Effect";
6
7 /**
8 * Normalize a user-supplied GitHub host or URL into the REST API base URL
9 * the GitHub SDK expects, following the same conventions as the `gh` CLI and the
10 * Terraform GitHub provider:
11 *
12 * - `github.com` / `api.github.com` → `undefined` (the github.com default)
13 * - GitHub Enterprise Cloud with data residency (`acme.ghe.com` or
14 * `api.acme.ghe.com`) → `https://api.acme.ghe.com`
15 * - GitHub Enterprise Server (`github.example.com`) → `https://github.example.com/api/v3`;
16 * an explicit path (e.g. an already-complete `/api/v3` URL) is honored as-is.
17 *
18 * Accepts a bare hostname or a full URL.
19 */
20 export const normalizeGitHubBaseUrl = (
21 input: string,
22 ): Effect.Effect<string | undefined, AuthError> =>
23 Effect.try({
24 try: () => {
25 const trimmed = input.trim();
26 const url = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
27 const host = url.hostname.toLowerCase();
28 if (host === "github.com" || host === "www.github.com" || host === "api.github.com") {
29 return undefined;
30 }
31 if (host.endsWith(".ghe.com")) {
32 return `https://${host.startsWith("api.") ? host : `api.${host}`}`;
33 }
34 const path = url.pathname.replace(/\/+$/, "");
35 return `${url.protocol}//${url.host}${path === "" ? "/api/v3" : path}`;
36 },
37 catch: () =>
38 AuthError.make({
39 message: `Invalid GitHub base URL: '${input}'. Provide a hostname (github.example.com) or URL (https://github.example.com/api/v3).`,
40 }),
41 });
42
43 /**
44 * The hostname `gh auth token --hostname` expects for a normalized API base
45 * URL — the plain host for GitHub Enterprise Server, and the `api.`-less
46 * host for GitHub Enterprise Cloud with data residency.
47 */
48 export const githubHostname = (baseUrl: string): string => {
49 const host = new URL(baseUrl).hostname;
50 return host.startsWith("api.") && host.endsWith(".ghe.com") ? host.slice("api.".length) : host;
51 };
52
53 /**
54 * Resolve the GitHub API base URL from the environment:
55 * `GITHUB_BASE_URL` (Terraform convention), then `GITHUB_API_URL` (set by
56 * GitHub Actions runners), then `GH_HOST` (gh CLI convention, a bare
57 * hostname). Returns `undefined` when unset or when the value points at
58 * github.com.
59 */
60 export const resolveGitHubBaseUrlFromEnv: Effect.Effect<string | undefined, AuthError> = Effect.gen(
61 function* () {
62 for (const key of ["GITHUB_BASE_URL", "GITHUB_API_URL", "GH_HOST"]) {
63 const value = yield* getEnv(key);
64 if (value !== undefined && value.trim() !== "") {
65 return yield* normalizeGitHubBaseUrl(value);
66 }
67 }
68 return undefined;
69 },
70 );
71
72 /**
73 * Run a resource's GitHub calls against its own `baseUrl` prop. When set, it
74 * is normalized and replaces the provider's host (an explicit `"github.com"`
75 * overrides an enterprise-wide provider host back to the default); when
76 * unset, the calls use the provider's credentials unchanged.
77 *
78 * ```ts
79 * reconcile: Effect.fn(function* ({ news }) { ... }, (effect, { news }) =>
80 * effect.pipe(withBaseUrl(news.baseUrl)),
81 * ),
82 * ```
83 */
84 export const withBaseUrl =
85 (baseUrl: string | undefined) =>
86 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | AuthError, R | Credentials> =>
87 baseUrl === undefined
88 ? effect
89 : Effect.flatMap(normalizeGitHubBaseUrl(baseUrl), (apiBaseUrl) =>
90 Effect.updateService(effect, Credentials, (resolve) =>
91 Effect.map(resolve, (config) => ({
92 ...config,
93 apiBaseUrl: apiBaseUrl ?? DEFAULT_API_BASE_URL,
94 })),
95 ),
96 );
97
98 /**
99 * The REST API base URL a resource's `baseUrl` prop actually resolves to: the
100 * normalized prop when set, otherwise the provider's host — which already
101 * reflects `GitHub.providers({ baseUrl })` or the auth provider's resolved
102 * host.
103 */
104 export const effectiveGitHubBaseUrl = (
105 baseUrl: string | undefined,
106 ): Effect.Effect<string, AuthError | ConfigError, Credentials> =>
107 baseUrl !== undefined
108 ? Effect.map(normalizeGitHubBaseUrl(baseUrl), (url) => url ?? DEFAULT_API_BASE_URL)
109 : Effect.gen(function* () {
110 return (yield* yield* Credentials).apiBaseUrl;
111 });
112
113 /**
114 * Whether a resource's EFFECTIVE GitHub host changed between deploys — used
115 * by resource `diff` implementations to decide replacement (a resource with
116 * the same name on a different GitHub instance is a different physical
117 * resource).
118 *
119 * Each side is resolved through the full fallback chain (explicit prop →
120 * `providers({ baseUrl })` → auth provider host) and normalized before
121 * comparing, so neither a cosmetic rewrite (`github.example.com` →
122 * `https://github.example.com/api/v3`) nor making the ambient default
123 * explicit (prop `undefined` → prop equal to the provider's host) triggers
124 * a replacement — and dropping back to github.com from an enterprise-wide
125 * provider host is correctly detected as a change.
126 */
127 export const gitHubBaseUrlChanged = (
128 olds: { baseUrl?: string },
129 news: { baseUrl?: string },
130 ): Effect.Effect<boolean, AuthError | ConfigError, Credentials> =>
131 Effect.gen(function* () {
132 const oldUrl = yield* effectiveGitHubBaseUrl(olds.baseUrl);
133 const newUrl = yield* effectiveGitHubBaseUrl(news.baseUrl);
134 return oldUrl !== newUrl;
135 });