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