Open History to see the last commit
1import * as NodeUtil from "node:util";
2import {
3 VcsProcessSpawnError,
4 type SourceControlProviderAuth,
5 type SourceControlProviderDiscoveryItem,
6 type SourceControlProviderInfo,
7 type SourceControlProviderKind,
8} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { SpawnExecutableResolution } from "@t3tools/shared/shell";
11import type * as Cause from "effect/Cause";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as PlatformError from "effect/PlatformError";
15import * as Result from "effect/Result";
16import * as Schema from "effect/Schema";
17
18import type * as SourceControlProvider from "./SourceControlProvider.ts";
19import type * as SourceControlHost from "./SourceControlHost.ts";
20
21export interface SourceControlAuthProbeInput {
22 readonly stdout: string;
23 readonly stderr: string;
24 readonly exitCode: SourceControlHost.SourceControlProcessOutput["exitCode"];
25}
26
27export interface SourceControlUnknownRemoteRefinementInput {
28 readonly cwd: string;
29 readonly context: SourceControlProvider.SourceControlProviderContext;
30 readonly auth: SourceControlAuthProbeInput;
31}
32
33interface SourceControlDiscoverySpecBase {
34 readonly kind: SourceControlProviderKind;
35 readonly label: string;
36 readonly installHint: string;
37}
38
39export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
40 readonly type: "cli";
41 readonly executable: string;
42 readonly versionArgs: ReadonlyArray<string>;
43 readonly authArgs: ReadonlyArray<string>;
44 readonly remoteRefinementArgs?: (
45 context: SourceControlProvider.SourceControlProviderContext,
46 ) => ReadonlyArray<string>;
47 readonly probeTimeoutMs?: number;
48 readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
49 /** `null` when the CLI holds nothing for the remote; `undefined` when its output cannot say. */
50 readonly refineUnknownRemote?: (
51 input: SourceControlUnknownRemoteRefinementInput,
52 ) => SourceControlProviderInfo | null | undefined;
53};
54
55export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
56 readonly type: "api";
57 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
58};
59
60export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & {
61 readonly type: "managed-cli";
62 readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>;
63 /** Null includes missing CLIs. Failure means unknown and must not be cached by the registry. */
64 readonly refineUnknownRemote: (input: {
65 readonly cwd: string;
66 readonly context: SourceControlProvider.SourceControlProviderContext;
67 }) => Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError>;
68};
69
70export type SourceControlProviderDiscoverySpec =
71 | SourceControlCliDiscoverySpec
72 | SourceControlManagedCliDiscoverySpec
73 | SourceControlApiDiscoverySpec;
74
75type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & {
76 readonly refineUnknownRemote: NonNullable<SourceControlCliDiscoverySpec["refineUnknownRemote"]>;
77};
78
79const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
80/** An API host that stalls must not hold the whole discovery answer behind it. */
81const API_PROBE_TIMEOUT = "3 seconds";
82
83function probeTimeoutMs(spec: SourceControlCliDiscoverySpec): number {
84 return spec.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
85}
86
87interface DiscoveryProbeResult {
88 readonly kind: SourceControlProviderKind;
89 readonly label: string;
90 readonly executable: string;
91 readonly status: "available" | "missing";
92 readonly version: Option.Option<string>;
93 readonly installHint: string;
94 readonly detail: Option.Option<string>;
95}
96
97export function firstNonEmptyLine(text: string): Option.Option<string> {
98 const line = NodeUtil.stripVTControlCharacters(text)
99 .split(/\r?\n/)
100 .map((entry) => entry.trim())
101 .find((entry) => entry.length > 0);
102 return line === undefined ? Option.none() : Option.some(line);
103}
104
105export function detailFromCause(cause: unknown): Option.Option<string> {
106 if (cause instanceof Error && cause.message.trim().length > 0) {
107 return Option.some(cause.message.trim());
108 }
109 return Option.none();
110}
111
112function authAccount(account: string | undefined): Option.Option<string> {
113 const trimmed = account?.trim();
114 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
115}
116
117function authHost(host: string | undefined): Option.Option<string> {
118 const trimmed = host?.trim();
119 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
120}
121
122function authDetail(detail: string | undefined): Option.Option<string> {
123 const trimmed = detail?.trim();
124 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
125}
126
127export function providerAuth(input: {
128 readonly status: SourceControlProviderAuth["status"];
129 readonly account?: string | undefined;
130 readonly host?: string | undefined;
131 readonly detail?: string | undefined;
132}): SourceControlProviderAuth {
133 return {
134 status: input.status,
135 account: authAccount(input.account),
136 host: authHost(input.host),
137 detail: authDetail(input.detail),
138 };
139}
140
141function unknownAuth(detail?: string): SourceControlProviderAuth {
142 return providerAuth({ status: "unknown", detail });
143}
144
145export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
146 const parts: string[] = [];
147 for (const entry of [input.stdout, input.stderr]) {
148 if (entry.trim().length > 0) {
149 parts.push(entry);
150 }
151 }
152 return parts.join("\n");
153}
154
155function sanitizedAuthLines(text: string): ReadonlyArray<string> {
156 const lines: string[] = [];
157 for (const entry of text.split(/\r?\n/)) {
158 const line = entry.trim();
159 if (line.length === 0) continue;
160 if (/^[-\s]*token(?:\s+scopes?)?:/iu.test(line)) continue;
161 lines.push(line);
162 }
163 return lines;
164}
165
166export function firstSafeAuthLine(text: string): string | undefined {
167 return sanitizedAuthLines(text)[0];
168}
169
170export function parseCliHost(text: string): string | undefined {
171 return sanitizedAuthLines(text)
172 .map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
173 .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
174}
175
176export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
177 for (const pattern of patterns) {
178 const match = pattern.exec(text);
179 const value = match?.[1]?.trim();
180 if (value && value.length > 0) return value;
181 }
182 return undefined;
183}
184
185function isCliRemoteRefinementSpec(
186 spec: SourceControlProviderDiscoverySpec,
187): spec is SourceControlCliRemoteRefinementSpec {
188 return spec.type === "cli" && spec.refineUnknownRemote !== undefined;
189}
190
191function probeCli(input: {
192 readonly spec: SourceControlCliDiscoverySpec;
193 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
194 readonly cwd: string;
195}): Effect.Effect<DiscoveryProbeResult> {
196 return input.process
197 .run({
198 operation: "source-control.discovery.probe",
199 command: input.spec.executable,
200 args: input.spec.versionArgs,
201 cwd: input.cwd,
202 timeoutMs: probeTimeoutMs(input.spec),
203 maxOutputBytes: 8_000,
204 appendTruncationMarker: true,
205 })
206 .pipe(
207 Effect.map(
208 (result) =>
209 ({
210 kind: input.spec.kind,
211 label: input.spec.label,
212 executable: input.spec.executable,
213 status: "available" as const,
214 version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
215 firstNonEmptyLine(result.stderr),
216 ),
217 installHint: input.spec.installHint,
218 detail: Option.none<string>(),
219 }) satisfies DiscoveryProbeResult,
220 ),
221 Effect.catch((cause) =>
222 Effect.gen(function* () {
223 const installHint = yield* unavailableInstallHint(
224 input.spec.executable,
225 input.spec.installHint,
226 cause,
227 );
228 return {
229 kind: input.spec.kind,
230 label: input.spec.label,
231 executable: input.spec.executable,
232 status: "missing" as const,
233 version: Option.none<string>(),
234 installHint,
235 detail: detailFromCause(cause),
236 } satisfies DiscoveryProbeResult;
237 }),
238 ),
239 );
240}
241
242export function probeSourceControlProvider(input: {
243 readonly spec: SourceControlProviderDiscoverySpec;
244 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
245 readonly cwd: string;
246}): Effect.Effect<SourceControlProviderDiscoveryItem> {
247 if (input.spec.type === "managed-cli") return input.spec.probe(input.cwd);
248 if (input.spec.type === "api") {
249 return input.spec.probeAuth.pipe(
250 Effect.timeoutOption(API_PROBE_TIMEOUT),
251 Effect.map(
252 Option.getOrElse(() =>
253 unknownAuth("The hosting service did not answer in time. Refresh to try again."),
254 ),
255 ),
256 Effect.map(
257 (auth) =>
258 ({
259 kind: input.spec.kind,
260 label: input.spec.label,
261 status: "available" as const,
262 version: Option.none<string>(),
263 installHint: input.spec.installHint,
264 detail: Option.none<string>(),
265 auth,
266 }) satisfies SourceControlProviderDiscoveryItem,
267 ),
268 );
269 }
270
271 const spec = input.spec;
272
273 // The auth check does not depend on the version output, so both spawn at once.
274 return Effect.all(
275 [
276 probeCli({
277 spec,
278 process: input.process,
279 cwd: input.cwd,
280 }),
281 input.process
282 .run({
283 operation: "source-control.discovery.auth",
284 command: spec.executable,
285 args: spec.authArgs,
286 cwd: input.cwd,
287 allowNonZeroExit: true,
288 timeoutMs: probeTimeoutMs(spec),
289 maxOutputBytes: 8_000,
290 appendTruncationMarker: true,
291 })
292 .pipe(
293 Effect.map(spec.parseAuth),
294 Effect.catch((cause) =>
295 Effect.succeed(unknownAuth(Option.getOrUndefined(detailFromCause(cause)))),
296 ),
297 ),
298 ],
299 { concurrency: "unbounded" },
300 ).pipe(
301 Effect.map(
302 ([item, auth]) =>
303 ({
304 ...item,
305 auth:
306 item.status === "available"
307 ? auth
308 : unknownAuth("Hosting integration command was not found on the server PATH."),
309 }) satisfies SourceControlProviderDiscoveryItem,
310 ),
311 );
312}
313
314const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError);
315
316/** The spawner checks cwd first, so ChildProcess NotFound identifies the executable. */
317export function isMissingExecutable(error: unknown): boolean {
318 return (
319 isVcsProcessSpawnError(error) &&
320 PlatformError.isPlatformError(error.cause) &&
321 error.cause.reason._tag === "NotFound" &&
322 error.cause.reason.module === "ChildProcess"
323 );
324}
325
326// macOS's EBADARCH, which Node has no name for: the binary is built for another CPU, such as an
327// Intel-only `gh` on Apple Silicon without Rosetta.
328const BAD_CPU_TYPE_ERRNO = -86;
329
330export const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(function* (
331 executable: string,
332 installHint: string,
333 cause: unknown,
334) {
335 const platform = yield* HostProcess.Platform;
336 if (
337 platform !== "darwin" ||
338 !isVcsProcessSpawnError(cause) ||
339 !(cause.cause instanceof Error) ||
340 !("errno" in cause.cause) ||
341 cause.cause.errno !== BAD_CPU_TYPE_ERRNO
342 ) {
343 return installHint;
344 }
345 const resolveExecutable = yield* SpawnExecutableResolution;
346 const path = resolveExecutable(executable, platform, yield* HostProcess.Environment);
347 const architecture = yield* HostProcess.Architecture;
348 return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`;
349});
350
351class UnknownRemoteUnanswered extends Schema.TaggedError<UnknownRemoteUnanswered>()(
352 "UnknownRemoteUnanswered",
353 {},
354) {}
355
356export interface UnknownRemoteVerdict {
357 readonly provider: SourceControlProviderInfo | null;
358 readonly settled: boolean;
359}
360
361function refineWithSpec(input: {
362 readonly spec: SourceControlProviderDiscoverySpec;
363 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
364 readonly cwd: string;
365 readonly context: SourceControlProvider.SourceControlProviderContext;
366}): Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError> {
367 const { spec, context } = input;
368 if (spec.type === "managed-cli") {
369 return spec.refineUnknownRemote({ cwd: input.cwd, context });
370 }
371 if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);
372 return input.process
373 .run({
374 operation: "source-control.discovery.refine-unknown-remote",
375 command: spec.executable,
376 args: spec.remoteRefinementArgs?.(context) ?? spec.authArgs,
377 cwd: input.cwd,
378 allowNonZeroExit: true,
379 timeoutMs: probeTimeoutMs(spec),
380 maxOutputBytes: 8_000,
381 appendTruncationMarker: true,
382 })
383 .pipe(
384 Effect.catchIf(isMissingExecutable, () => Effect.void),
385 Effect.flatMap((auth) => {
386 const provider =
387 auth === undefined ? null : spec.refineUnknownRemote({ cwd: input.cwd, context, auth });
388 return provider === undefined
389 ? Effect.fail(new UnknownRemoteUnanswered())
390 : Effect.succeed(provider);
391 }),
392 );
393}
394
395export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvider")(
396 function* (input: {
397 readonly specs: ReadonlyArray<SourceControlProviderDiscoverySpec>;
398 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
399 readonly cwd: string;
400 readonly context: SourceControlProvider.SourceControlProviderContext;
401 }): Effect.fn.Return<UnknownRemoteVerdict> {
402 const results = yield* Effect.forEach(input.specs, (spec) =>
403 refineWithSpec({ ...input, spec }).pipe(Effect.result),
404 );
405 // An earlier integration that could not answer might have claimed this host.
406 let settled = true;
407 for (const result of results) {
408 if (Result.isFailure(result)) settled = false;
409 else if (result.success !== null) return { provider: result.success, settled };
410 }
411 return { provider: null, settled };
412 },
413);