TypeScript
refactor(source-control): forges recognise their own remotes and repository keys (#23993)
Julius Marminge3d4c75370cd7
diff --git a/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts b/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.tsindex 4d1a4ab5add..faed80ecc13 100644--- a/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts+++ b/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts@@ -1,4 +1,4 @@-import { EnvironmentId, ProjectId } from "@t3tools/contracts";+import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import { nativePullRequestDestination } from "../../lib/pullRequestNavigation";@@ -10,7 +10,7 @@ const project = (id: string, canonicalKey: string, provider: string, remoteUrl:canonicalKey,locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },displayName: canonicalKey.split("/").slice(1).join("/"),- provider,+ provider: SourceControlProviderKind.make(provider),},});const projects = [diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.tsindex 4691f81fda8..0e517a53ae9 100644--- a/apps/server/src/git/GitManager.ts+++ b/apps/server/src/git/GitManager.ts@@ -49,15 +49,12 @@ import {resolveProjectSettings,} from "@t3tools/shared/projectSettings";import {- detectSourceControlProviderFromGitRemoteUrl,mergeGitStatusParts,- normalizeGitRemoteUrl,resolveAutoFeatureBranchName,sanitizeBranchFragment,sanitizeFeatureBranchName,} from "@t3tools/shared/git";import {- canonicalRepositoryKey,getChangeRequestTerminologyForKind,isSshRemoteUrl,type ChangeRequestTerminology,@@ -268,7 +265,7 @@ export function pullRequestRepositoryKey(value: string): string | null {url.pathname = match[1];url.search = "";url.hash = "";- return normalizeGitRemoteUrl(url.toString());+ return sourceControlClients.repositoryKeyFromRemote(url.toString());} catch {return null;}@@ -1027,8 +1024,10 @@ export const make = Effect.gen(function* () {if (remoteUrl === null ||pullRequestKey === null ||- canonicalRepositoryKey(pullRequestKey) !==- canonicalRepositoryKey(normalizeGitRemoteUrl(remoteUrl))+ sourceControlClients.canonicalRepositoryKey(pullRequestKey) !==+ sourceControlClients.canonicalRepositoryKey(+ sourceControlClients.repositoryKeyFromRemote(remoteUrl),+ )) {return yield* cause;}@@ -1451,7 +1450,7 @@ export const make = Effect.gen(function* () {const baseUrl =remote.remoteUrl === null? undefined- : detectSourceControlProviderFromGitRemoteUrl(remote.remoteUrl)?.baseUrl;+ : sourceControlClients.recognizeRemote(remote.remoteUrl)?.baseUrl;const host = baseUrl === undefined ? null : urlHost(baseUrl);const repository = remote.repositoryNameWithOwner?.toLowerCase();const fromEnvironment = parseGitHubRepositorySelector(environment.GH_REPO ?? "", host ?? "");@@ -1485,7 +1484,7 @@ export const make = Effect.gen(function* () {(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??(yield* readConfigValueNullable(cwd, "remote.origin.url"));- const provider = remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;+ const provider = remoteUrl ? sourceControlClients.recognizeRemote(remoteUrl) : null;if (!remoteUrl || provider?.kind !== "unknown") return provider;const handle = yield* sourceControlProviders.resolveHandle({@@ -1516,7 +1515,7 @@ export const make = Effect.gen(function* () {/^https?:\/\//iu.test(remoteUrl) &&(repositoryNameWithOwner?.split("/").length ?? 0) > 2) {- const kind = detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind;+ const kind = sourceControlClients.recognizeRemote(remoteUrl)?.kind;const provider =kind === undefined? undefined@@ -1527,7 +1526,7 @@ export const make = Effect.gen(function* () {}return {remoteUrl,- remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,+ remoteUrlKey: remoteUrl ? sourceControlClients.repositoryKeyFromRemote(remoteUrl) : null,repositoryNameWithOwner,ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),};@@ -2486,7 +2485,9 @@ export const make = Effect.gen(function* () {remoteName === null? Effect.succeed(null): readConfig(`remote.${remoteName}.url`).pipe(- Effect.map((remoteUrl) => (remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null)),+ Effect.map((remoteUrl) =>+ remoteUrl ? sourceControlClients.repositoryKeyFromRemote(remoteUrl) : null,+ ),);const remoteName = remoteNameOverride ?? (yield* readConfig(`branch.${branch}.remote`));const [headRemoteUrlKey, targetRemoteUrlKey] =diff --git a/apps/server/src/git/linkCreatedPullRequest.test.ts b/apps/server/src/git/linkCreatedPullRequest.test.tsindex 23af74c8ba2..d4d48bd9861 100644--- a/apps/server/src/git/linkCreatedPullRequest.test.ts+++ b/apps/server/src/git/linkCreatedPullRequest.test.ts@@ -6,6 +6,7 @@ import {type GitRunStackedActionResult,type OrchestrationV2ServerCommand as OrchestrationCommand,type OrchestrationProjectShell,+ SourceControlProviderKind,} from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";@@ -40,7 +41,7 @@ const project: OrchestrationProjectShell = {remoteName: "origin",remoteUrl: "[email protected]:Platform/API.git",},- provider: "github",+ provider: SourceControlProviderKind.make("github"),displayName: "Platform/API",owner: "Platform",name: "API",diff --git a/apps/server/src/git/linkCreatedPullRequest.ts b/apps/server/src/git/linkCreatedPullRequest.tsindex 29e80f9c13c..0d44a31bf9b 100644--- a/apps/server/src/git/linkCreatedPullRequest.ts+++ b/apps/server/src/git/linkCreatedPullRequest.ts@@ -1,10 +1,7 @@-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import {type CommandId,- pullRequestHostOf,type GitRunStackedActionResult,type OrchestrationProjectShell,- type SourceControlProviderKind,type ThreadId,} from "@t3tools/contracts";import * as Cause from "effect/Cause";@@ -35,11 +32,11 @@ export function createdPullRequestKey(return { host: parsed.host, repository: parsed.repository, number: parsed.number, url };}const identity = project?.repositoryIdentity;- const kind = identity?.provider as SourceControlProviderKind | undefined;- const repository = sourceControlRepositorySelector(identity);+ const kind = identity?.provider;+ const repository = sourceControlClients.repositorySelector(identity);if (!identity || kind === undefined || repository === null) return null;return {- host: pullRequestHostOf(identity, kind),+ host: sourceControlClients.changeRequestHost(identity, kind),repository: repository.toLowerCase(),number,url,diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.tsindex 11bce07bf5b..d1a0170caf5 100644--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts@@ -9,6 +9,7 @@ import {type PullRequestRef,type PullRequestReviewGuideResult,type ThreadPullRequestLink,+ SourceControlProviderKind,} from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";import * as Crypto from "effect/Crypto";@@ -64,7 +65,7 @@ function makeProject(remoteName: "origin",remoteUrl: "[email protected]:T3Tools/T3Code.git",},- provider: "github",+ provider: SourceControlProviderKind.make("github"),displayName: "T3Tools/T3Code",owner: "T3Tools",name: "T3Code",@@ -380,7 +381,7 @@ describe("pull request toolkit handlers", () => {remoteName: "origin",remoteUrl: "[email protected]:group/sub/project.git",},- provider: "gitlab",+ provider: SourceControlProviderKind.make("gitlab"),displayName: "group/sub/project",}),});@@ -415,7 +416,7 @@ describe("pull request toolkit handlers", () => {remoteName: "origin",remoteUrl: "http://dummy:[email protected]:8080/tfs/Collection/Project/_git/Repo",},- provider: "unknown",+ provider: SourceControlProviderKind.make("unknown"),displayName: "tfs/collection/project/_git/repo",}),});@@ -592,7 +593,7 @@ describe("pull request guide tools", () => {remoteName: "origin",remoteUrl: "[email protected]:acme/web.git",},- provider: "github",+ provider: SourceControlProviderKind.make("github"),displayName: "acme/web",owner: "acme",name: "web",@@ -651,7 +652,7 @@ describe("pull request guide tools", () => {remoteName: "origin",remoteUrl: "https://dev.azure.com/org/project/_git/web",},- provider: "azure-devops",+ provider: SourceControlProviderKind.make("azure-devops"),displayName: "org/project/_git/web",owner: "org",name: "web",diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.tsindex ff323fcdd94..191258ca669 100644--- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts+++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts@@ -1,13 +1,11 @@import {CommandId,- pullRequestHostOf,type OrchestrationProjectShell,type OrchestrationV2ThreadShell,type SourceControlProviderKind,type ThreadId,type ThreadPullRequestLink,} from "@t3tools/contracts";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import * as Cause from "effect/Cause";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";@@ -61,10 +59,10 @@ function projectHostAndProvider(project: OrchestrationProjectShell | undefined):readonly kind: SourceControlProviderKind | null;} {const identity = project?.repositoryIdentity;- const kind = (identity?.provider as SourceControlProviderKind | undefined) ?? null;+ const kind = identity?.provider ?? null;if (!identity || kind === null) return { host: null, kind: null };return {- host: pullRequestHostOf(identity, kind),+ host: sourceControlClients.changeRequestHost(identity, kind),kind,};}@@ -173,7 +171,7 @@ function projectForPullRequest(: pullRequestSyncKey({projectId: project.id,- repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? "",+ repository: sourceControlClients.repositorySelector(project.repositoryIdentity) ?? "",number: 1,},project.repositoryIdentity,diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.tsindex b4c32341226..80b17c0e2c2 100644--- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts@@ -137,7 +137,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {remoteName: "origin",remoteUrl: "[email protected]:acme/project.git",},- provider: "github" as const,+ provider: SourceControlProviderKind.make("github"),owner: "acme",name: "project",}),@@ -261,7 +261,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {remoteName: "origin",remoteUrl: "[email protected]:acme/project.git",},- provider: "github" as const,+ provider: SourceControlProviderKind.make("github"),owner: "acme",name: "project",}),diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.tsindex 2c3f03b0d34..f235ef63e8f 100644--- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts+++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts@@ -1,7 +1,3 @@-import {- canonicalRepositoryKey,- sourceControlRepositorySelector,-} from "@t3tools/shared/sourceControl";import {CommandId,type OrchestrationProjectShell,@@ -29,6 +25,7 @@ import * as ProjectStore from "./ProjectStore.ts";import * as PullRequestService from "../pullRequest/PullRequestService.ts";import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";import { forkParked } from "../serverActivation.ts";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";import * as Orchestrator from "./Orchestrator.ts";class ThreadPullRequestServiceV2 extends Context.Service<@@ -59,8 +56,8 @@ function pullRequestMatchesProject(return (pullRequest.repositoryKey !== null &&project.repositoryIdentity != null &&- canonicalRepositoryKey(pullRequest.repositoryKey) ===- canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)+ sourceControlClients.canonicalRepositoryKey(pullRequest.repositoryKey) ===+ sourceControlClients.canonicalRepositoryKey(project.repositoryIdentity.canonicalKey));}@@ -78,7 +75,7 @@ const resolveProjectForPullRequestDiscovery = Effect.fn(});return {project: { ...project, repositoryIdentity },- repository: sourceControlRepositorySelector(repositoryIdentity),+ repository: sourceControlClients.repositorySelector(repositoryIdentity),};});diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.tsindex 7d95dfd035a..bf9b46c41a5 100644--- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts@@ -26,6 +26,7 @@ import * as ServerSettings from "../serverSettings.ts";import { forkParked } from "../serverActivation.ts";import * as TerminalManager from "../terminal/Manager.ts";import * as ProjectStore from "./ProjectStore.ts";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";import * as Orchestrator from "./Orchestrator.ts";import * as ProjectionStore from "./ProjectionStore.ts";@@ -51,18 +52,6 @@ function latestMillis(values: ReadonlyArray<number | null>): number | null {return latest;}-function canonicalRepositoryKey(key: string): string {- return key- .replace(- /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,- "dev.azure.com/$1/$2/_git/$3",- )- .replace(- /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,- "dev.azure.com/$1/$2/_git/$3",- );-}-function pullRequestMatchesProject(pullRequest: GitManager.GitBranchPullRequest,project: {@@ -72,8 +61,8 @@ function pullRequestMatchesProject(return (pullRequest.repositoryKey !== null &&project.repositoryIdentity != null &&- canonicalRepositoryKey(pullRequest.repositoryKey) ===- canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)+ sourceControlClients.canonicalRepositoryKey(pullRequest.repositoryKey) ===+ sourceControlClients.canonicalRepositoryKey(project.repositoryIdentity.canonicalKey));}diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.tsindex 29a55ec22ba..baf0f27f9ed 100644--- a/apps/server/src/project/AgentSessionScanner.test.ts+++ b/apps/server/src/project/AgentSessionScanner.test.ts@@ -745,7 +745,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {yield* fileSystem.makeDirectory(submoduleGitDir, { recursive: true });yield* fileSystem.writeFileString(path.join(submoduleGitDir, "config"),- '[remote "origin"]\n\turl = ssh://github.com/pingdotgg/vendor.git\n',+ '[remote "origin"]\n\turl = ssh://gitlab.com/pingdotgg/libs/vendor.git\n',);yield* fileSystem.writeFileString(path.join(submodule, ".git"),@@ -767,7 +767,10 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {).toEqual([{path: submodule,- git: { remoteKey: "github.com/pingdotgg/vendor", repository: "pingdotgg/vendor" },+ git: {+ remoteKey: "gitlab.com/pingdotgg/libs/vendor",+ repository: "pingdotgg/libs/vendor",+ },},{ path: noRemote, git: { remoteKey: null, repository: null } },{ path: plain, git: null },diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.tsindex e516ce0e53b..ffdee62c01b 100644--- a/apps/server/src/project/AgentSessionScanner.ts+++ b/apps/server/src/project/AgentSessionScanner.ts@@ -24,20 +24,17 @@ import * as Schema from "effect/Schema";import * as Semaphore from "effect/Semaphore";import * as Stream from "effect/Stream";-import {- normalizeGitRemoteUrl,- isBareGitConfig,- parseGitHubRepositoryNameWithOwnerFromRemoteUrl,- parseOriginUrlFromGitConfig,-} from "@t3tools/shared/git";+import { isBareGitConfig, parseOriginUrlFromGitConfig } from "@t3tools/shared/git";import * as HostProcess from "@t3tools/shared/HostProcess";import { normalizeProjectPathForComparison } from "@t3tools/shared/path";+import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";import * as ServerConfig from "../config.ts";import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";import * as ServerSettings from "../serverSettings.ts";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";import {createTranscriptJsonReader,createTranscriptJsonSelector,@@ -725,8 +722,9 @@ export const make = Effect.gen(function* () {return {_tag: "Repository",git: {- remoteKey: originUrl === null ? null : normalizeGitRemoteUrl(originUrl),- repository: parseGitHubRepositoryNameWithOwnerFromRemoteUrl(originUrl),+ remoteKey:+ originUrl === null ? null : sourceControlClients.repositoryKeyFromRemote(originUrl),+ repository: repositoryPathFromRemoteUrl(originUrl),},} as const;});diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.tsindex 0ec948b485f..86a840fec0f 100644--- a/apps/server/src/project/RepositoryIdentityResolver.ts+++ b/apps/server/src/project/RepositoryIdentityResolver.ts@@ -1,9 +1,5 @@import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";-import {- detectSourceControlProviderFromGitRemoteUrl,- normalizeGitRemoteUrl,-} from "@t3tools/shared/git";import * as Cache from "effect/Cache";import * as Context from "effect/Context";import * as Data from "effect/Data";@@ -13,6 +9,7 @@ import * as Exit from "effect/Exit";import * as Layer from "effect/Layer";import * as ProcessRunner from "../processRunner.ts";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts";import * as HostProcess from "@t3tools/shared/HostProcess";@@ -102,7 +99,7 @@ function buildRepositoryOrigin(canonicalKey: string,): RepositoryIdentity["origin"] {if (!originUrl) return undefined;- const originKey = normalizeGitRemoteUrl(originUrl);+ const originKey = sourceControlClients.repositoryKeyFromRemote(originUrl);if (originKey === canonicalKey) return undefined;const displayName = repositoryPathOf(originKey, originUrl);return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };@@ -114,8 +111,8 @@ function buildRepositoryIdentity(input: {readonly originUrl: string | undefined;readonly rootPath: string;}): RepositoryIdentity {- const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);- const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);+ const canonicalKey = sourceControlClients.repositoryKeyFromRemote(input.remoteUrl);+ const sourceControlProvider = sourceControlClients.recognizeRemote(input.remoteUrl);const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);const [owner] = repositoryPathSegments;diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.tsindex edd5dd2c728..e78d850d683 100644--- a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts+++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts@@ -24,7 +24,7 @@ import {} from "@t3tools/contracts";import type { ReviewGuideStackLayer } from "@t3tools/provider-core/server/textGeneration";import { resolveProjectSettings } from "@t3tools/shared/projectSettings";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";import * as ServerConfig from "../config.ts";import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";@@ -104,7 +104,7 @@ const make = Effect.gen(function* () {{projectId: ProjectId.make("own"),number: key.number,- repository: sourceControlRepositorySelector(identity) ?? "",+ repository: sourceControlClients.repositorySelector(identity) ?? "",},identity,);diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex 1d2b879e11a..2a07b5715a3 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -77,7 +77,7 @@ function project(input: {remoteName: "origin",remoteUrl: input.remoteUrl ?? `https://${host}/${input.repository}.git`,},- provider: input.provider ?? "github",+ provider: SourceControlProviderKind.make(input.provider ?? "github"),displayName: input.repository,},}diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex c57375c3dd3..97264c56d13 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -1,9 +1,4 @@-import {- canonicalRepositoryKey,- isSshRemoteUrl,- sourceControlRepositorySelector,-} from "@t3tools/shared/sourceControl";-import { normalizeGitRemoteUrl } from "@t3tools/shared/git";+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";import { parseDiffFilePaths } from "@t3tools/source-control-core/server/diffFileRevisions";import * as Cache from "effect/Cache";import * as Cause from "effect/Cause";@@ -23,7 +18,6 @@ import * as SubscriptionRef from "effect/SubscriptionRef";import {PullRequestOperationError,PullRequestUnavailableError,- pullRequestHostOf,pullRequestProviderRequirement,resolvePullRequestAuthorFilter,type OrchestrationProjectShell,@@ -82,7 +76,7 @@ import {type ThreadPullRequestKey,} from "@t3tools/contracts";import { resolveProjectSettings } from "@t3tools/shared/projectSettings";-import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";import * as ProjectService from "../project/ProjectService.ts";import * as ServerSettings from "../serverSettings.ts";@@ -500,6 +494,9 @@ function withRateLimitBackoff(? {}: { mergeMessageRewrite: api.mergeMessageRewrite }),...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }),+ ...(api.readsPublicHostWithoutCheckout === undefined+ ? {}+ : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }),getViewer:options?.viewerAllowsPause === true? interactive("getViewer", api.getViewer)@@ -648,6 +645,29 @@ function rankFilterOptions<A>(};}+/** Whether the project's remote is SSH on a host whose SSH remotes do not name its web host. */+function sshRemoteHidesWebHost(+ identity: NonNullable<OrchestrationProjectShell["repositoryIdentity"]>,+) {+ return (+ identity.provider !== undefined &&+ sourceControlClients.find(identity.provider)?.sshRemoteHidesWebHost === true &&+ isSshRemoteUrl(identity.locator.remoteUrl)+ );+}++/** An HTTP remote names its server's web host, port included. */+function httpRemoteHost(remoteUrl: string): string | null {+ try {+ const remote = new URL(remoteUrl);+ return remote.protocol === "http:" || remote.protocol === "https:"+ ? remote.host.toLowerCase()+ : null;+ } catch {+ return null;+ }+}+// Capture before the provider read so a slow response keeps its original freshness through caches.const observeRead = Effect.fnUntraced(function* <A, E, R>(read: Effect.Effect<A, E, R>) {const observedAt = yield* Clock.currentTimeMillis;@@ -682,24 +702,22 @@ export const make = Effect.gen(function* () {if (filter.projectId !== undefined && project.id !== filter.projectId) continue;const identity = project.repositoryIdentity;if (- (identity?.provider !== "unknown" &&- !(identity?.provider === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))) ||- sourceControlRepositorySelector(project.repositoryIdentity) === null+ (identity?.provider !== "unknown" && !(identity && sshRemoteHidesWebHost(identity))) ||+ sourceControlClients.repositorySelector(project.repositoryIdentity) === null)continue;- const host = pullRequestHostOf(identity, SourceControlProviderKind.make("unknown"));+ const host = sourceControlClients.changeRequestHost(identity, "unknown");if (filter.host !== undefined &&host !== "unknown" &&host !== filter.host.toLowerCase() &&- pullRequestHostOf(identity, SourceControlProviderKind.make("forgejo")) !==- filter.host.toLowerCase() &&+ httpRemoteHost(identity.locator.remoteUrl) !== filter.host.toLowerCase() &&!isSshRemoteUrl(identity.locator.remoteUrl)) {continue;}const { remoteName, remoteUrl } = identity.locator;- const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);+ const provider = sourceControlClients.recognizeRemote(remoteUrl);if (provider !== null) {const candidates = refinements.get(provider.baseUrl);const candidate = { project, provider, remoteName, remoteUrl };@@ -717,10 +735,9 @@ export const make = Effect.gen(function* () {sourceControlProviders.resolveHandle({cwd: project.workspaceRoot,context: {- provider:- provider.kind === "forgejo"- ? { ...provider, kind: SourceControlProviderKind.make("unknown") }- : provider,+ provider: sourceControlClients.find(provider.kind)?.sshRemoteHidesWebHost+ ? { ...provider, kind: SourceControlProviderKind.make("unknown") }+ : provider,remoteName,remoteUrl,...(filter.host !== undefined && isSshRemoteUrl(remoteUrl)@@ -791,22 +808,20 @@ export const make = Effect.gen(function* () {if (filter.projectId !== undefined && project.id !== filter.projectId) continue;if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;const identity = project.repositoryIdentity;- let kind = identity?.provider as SourceControlProviderKind | undefined;- const repository = sourceControlRepositorySelector(project.repositoryIdentity);+ let kind = identity?.provider;+ const repository = sourceControlClients.repositorySelector(project.repositoryIdentity);if (!identity || kind === undefined || repository === null) continue;let refinedProvider: SourceControlProviderInfo | null | undefined;- if (- kind === "unknown" ||- (kind === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))- ) {- const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl);+ if (kind === "unknown" || sshRemoteHidesWebHost(identity)) {+ const provider = sourceControlClients.recognizeRemote(identity.locator.remoteUrl);refinedProvider = provider === null ? null : refinedProviders.get(provider.baseUrl);kind = refinedProvider?.kind ?? kind;}const host =- refinedProvider?.kind === "forgejo"+ refinedProvider &&+ sourceControlClients.find(refinedProvider.kind)?.sshRemoteHidesWebHost? new URL(refinedProvider.baseUrl).host.toLowerCase()- : pullRequestHostOf(identity, kind);+ : sourceControlClients.changeRequestHost(identity, kind);if (filter.host !== undefined && host !== filter.host.toLowerCase()) {continue;}@@ -833,9 +848,13 @@ export const make = Effect.gen(function* () {api: withRateLimitBackoff(api, host, rateLimits),repository,host,- remote: repositoryKey ?? normalizeGitRemoteUrl(`https://${host}/${repository}`),+ remote:+ repositoryKey ??+ sourceControlClients.repositoryKeyFromRemote(`https://${host}/${repository}`),repositoryKey:- repositoryKey === null ? null : canonicalRepositoryKey(repositoryKey.toLowerCase()),+ repositoryKey === null+ ? null+ : sourceControlClients.canonicalRepositoryKey(repositoryKey.toLowerCase()),});}return { supported, unimplemented, viewerRoots };@@ -866,11 +885,13 @@ export const make = Effect.gen(function* () {}),);}- const repositoryKey = canonicalRepositoryKey(`${host}/${repository}`.toLowerCase());- // Azure SSH and legacy clone hosts differ from the browser URL's host. Compare- // the complete repository identity before narrowing those checkouts by host.+ const referenceKey = `${host}/${repository}`.toLowerCase();+ const repositoryKey = sourceControlClients.canonicalRepositoryKey(referenceKey);+ // A host that spells one repository several ways (Azure's SSH and legacy clone hosts)+ // can differ from the browser URL's host. Compare the complete repository identity+ // before narrowing those checkouts by host.return listWorkspaceProjects(- repositoryKey.startsWith("dev.azure.com/") ? {} : { host },+ sourceControlClients.findByRepositoryKey(referenceKey) ? {} : { host },).pipe(Effect.flatMap(({ supported }) => {const onHost = supported.filter((candidate) => candidate.host === host);@@ -887,11 +908,9 @@ export const make = Effect.gen(function* () {onHost.find((candidate) => candidate.repositoryKey === null);if (route === undefined) {return Effect.gen(function* () {- const provider = ["github.com", "bitbucket.org", "codeberg.org"].includes(host)- ? detectSourceControlProviderFromRemoteUrl(`https://${host}/${repository}.git`)- : null;- const api = provider === null ? null : registry.get(provider.kind);- if (api !== null) {+ const publicHost = sourceControlClients.findByPublicHost(host);+ const api = publicHost === undefined ? null : registry.get(publicHost.kind);+ if (api?.readsPublicHostWithoutCheckout) {const selected = yield* projects.getShell(ref.projectId).pipe(Effect.mapError((cause) =>@@ -909,7 +928,9 @@ export const make = Effect.gen(function* () {api: withRateLimitBackoff(api, host, rateLimits),repository,host,- remote: normalizeGitRemoteUrl(`https://${host}/${repository}`),+ remote: sourceControlClients.repositoryKeyFromRemote(+ `https://${host}/${repository}`,+ ),repositoryKey: null,};}@@ -924,7 +945,9 @@ export const make = Effect.gen(function* () {: {...route,repository,- remote: normalizeGitRemoteUrl(`https://${host}/${repository}`),+ remote: sourceControlClients.repositoryKeyFromRemote(+ `https://${host}/${repository}`,+ ),},);}),diff --git a/apps/server/src/pullRequest/pullRequestSyncKey.test.ts b/apps/server/src/pullRequest/pullRequestSyncKey.test.tsindex 2b21e20d15f..83f61338c19 100644--- a/apps/server/src/pullRequest/pullRequestSyncKey.test.ts+++ b/apps/server/src/pullRequest/pullRequestSyncKey.test.ts@@ -1,4 +1,4 @@-import { ProjectId } from "@t3tools/contracts";+import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";@@ -13,7 +13,7 @@ describe("pullRequestSyncKey", () => {])("resolves hostless and checkout-host Azure references for %s", (canonicalKey) => {const identity = {canonicalKey,- provider: "azure-devops",+ provider: SourceControlProviderKind.make("azure-devops"),name: "web",displayName: canonicalKey.split("/").slice(1).join("/"),locator: {diff --git a/apps/server/src/pullRequest/pullRequestSyncKey.ts b/apps/server/src/pullRequest/pullRequestSyncKey.tsindex 90416e066ca..681dfb07b9d 100644--- a/apps/server/src/pullRequest/pullRequestSyncKey.ts+++ b/apps/server/src/pullRequest/pullRequestSyncKey.ts@@ -1,43 +1,37 @@-import {- pullRequestHostOf,- type PullRequestRef,- type RepositoryIdentity,- SourceControlProviderKind,- type ThreadPullRequestKey,-} from "@t3tools/contracts";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";+import type { PullRequestRef, RepositoryIdentity, ThreadPullRequestKey } from "@t3tools/contracts";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts";export function pullRequestSyncKey(reference: PullRequestRef,identity?: RepositoryIdentity | null,): ThreadPullRequestKey | null {- if (identity?.provider === "azure-devops" && !reference.repository.includes("/")) {+ const host = identity+ ? sourceControlClients.changeRequestHost(identity, identity.provider)+ : undefined;+ // A host whose tools select a repository by something other than its path (Azure DevOps takes+ // the bare name) can only key such a reference through the project's own repository.+ const definition = identity?.provider ? sourceControlClients.find(identity.provider) : undefined;+ if (identity && definition?.repositorySelector && !reference.repository.includes("/")) {if (reference.repository.toLowerCase() !==- sourceControlRepositorySelector(identity)?.toLowerCase() ||- (reference.host !== undefined &&- reference.host.toLowerCase() !==- pullRequestHostOf(identity, SourceControlProviderKind.make("azure-devops")))+ definition.repositorySelector(identity)?.toLowerCase() ||+ (reference.host !== undefined && reference.host.toLowerCase() !== host))return null;- const [host, ...repository] = identity.canonicalKey.split("/");- if (!host || repository.length === 0) return null;+ const [projectHost, ...repository] = identity.canonicalKey.split("/");+ if (!projectHost || repository.length === 0) return null;return normalizeThreadPullRequestKey({- host,+ host: projectHost,repository: repository.join("/"),number: reference.number,});}- const host =- reference.host ??- (identity- ? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)- : undefined);- return host === undefined+ const resolvedHost = reference.host ?? host;+ return resolvedHost === undefined? null: normalizeThreadPullRequestKey({- host,+ host: resolvedHost,repository: reference.repository,number: reference.number,});diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.tsindex 6109fe43c19..5ea6c4037c9 100644--- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts+++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts@@ -13,9 +13,9 @@ import {type SourceControlProviderDiscoveryItem,} from "@t3tools/contracts";import type {} from "@t3tools/contracts";-import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";import * as BuiltInDrivers from "./builtInDrivers.ts";+import { sourceControlClients } from "./sourceControlClients.ts";import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";import {probeSourceControlProvider,@@ -144,7 +144,7 @@ function selectProviderContext(): SourceControlProvider.SourceControlProviderContext | null {const candidates: Array<SourceControlProvider.SourceControlProviderContext> = [];for (const remote of remotes) {- const provider = detectSourceControlProviderFromRemoteUrl(remote.url);+ const provider = sourceControlClients.recognizeRemote(remote.url);if (provider) {candidates.push({provider,@@ -337,7 +337,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWitif (input.url.protocol !== "https:" || input.url.username || input.url.password) {return undefined;}- const kind = detectSourceControlProviderFromRemoteUrl(input.url.href)?.kind;+ const kind = sourceControlClients.recognizeRemote(input.url.href)?.kind;return kind ? providers.get(kind)?.resolveLink?.(input) : undefined;},get,diff --git a/apps/server/src/sourceControl/sourceControlClients.ts b/apps/server/src/sourceControl/sourceControlClients.tsindex bfe6cc8feca..856fe7da39a 100644--- a/apps/server/src/sourceControl/sourceControlClients.ts+++ b/apps/server/src/sourceControl/sourceControlClients.ts@@ -10,7 +10,8 @@ import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";* The same order as the clients' registry in `@t3tools/client-runtime/source-control-clients`.* A change request URL goes to the first host whose shape it has, so GitCafe, which claims* `/pull/` and `/pulls/` only on its own hostnames, claims before GitHub and Forgejo, which- * claim them everywhere.+ * claim them everywhere. A remote goes to the first host that recognises it, and a hostname can+ * carry more than one host's label (`gitea.github.example`), so recognition has its own order.*/export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [GitHubDriver.driver,@@ -23,5 +24,15 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [export const sourceControlClients = makeSourceControlClientRegistry(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.map((driver) => driver.definition),- { claimChangeRequestUrlsFirst: [GitCafeDriver.driver.kind] },+ {+ claimChangeRequestUrlsFirst: [GitCafeDriver.driver.kind],+ recognizeRemotesIn: [+ GitCafeDriver.driver.kind,+ ForgejoDriver.driver.kind,+ GitHubDriver.driver.kind,+ GitLabDriver.driver.kind,+ AzureDevOpsDriver.driver.kind,+ BitbucketDriver.driver.kind,+ ],+ },);diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex b5a523876a5..2bc11cdb045 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -31,7 +31,7 @@ import {type ReviewDiffPreviewSource,type VcsRef,} from "@t3tools/contracts";-import { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from "@t3tools/shared/git";+import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";import * as HostProcess from "@t3tools/shared/HostProcess";import { compactTraceAttributes } from "@t3tools/shared/observability";import { decodeJsonResult } from "@t3tools/shared/schemaJson";@@ -50,6 +50,7 @@ import {parseRemoteRefWithRemoteNames,} from "../git/remoteRefs.ts";import * as ServerConfig from "../config.ts";+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";const DEFAULT_TIMEOUT_MS = 30_000;const gitProcesses = Semaphore.makeUnsafe(8);@@ -1727,7 +1728,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*"ensureRemote",)(function* (input) {const preferredName = sanitizeRemoteName(input.preferredName);- const normalizedTargetUrl = normalizeGitRemoteUrl(input.url);+ const normalizedTargetUrl = sourceControlClients.repositoryKeyFromRemote(input.url);const remoteFetchUrls = yield* runGitStdout("GitVcsDriver.ensureRemote.listRemoteUrls",input.cwd,@@ -1735,7 +1736,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {- if (normalizeGitRemoteUrl(remoteUrl) === normalizedTargetUrl) {+ if (sourceControlClients.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl) {return remoteName;}}diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex ec4fe2a5511..6252b087abe 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1,3 +1,4 @@+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer";import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement";@@ -101,7 +102,6 @@ import {import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";import { resolveProjectSettings } from "@t3tools/shared/projectSettings";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";import { useAtomValue } from "@effect/atom-react";@@ -1911,7 +1911,7 @@ export default function ChatView(props: ChatViewProps) {});// The thread's own change request, placed against the project it belongs to. Without a// project there is nothing to resolve it against, so the caller falls back to the browser.- const activeProjectRepository = sourceControlRepositorySelector(+ const activeProjectRepository = sourceControlClients.repositorySelector(activeProject?.repositoryIdentity,);const {diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsxindex c4577f64fe5..aabd2d5f7ce 100644--- a/apps/web/src/components/RightPanelTabs.tsx+++ b/apps/web/src/components/RightPanelTabs.tsx@@ -1,4 +1,4 @@-import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";import {@@ -715,7 +715,7 @@ function PullRequestSurfaceIcon({const host =surface.host ??(identity?.provider- ? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)+ ? sourceControlClients.changeRequestHost(identity, identity.provider): null);const configs = useServerConfigs();const capabilities =diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsxindex 85c65005b9d..5867b56b3a3 100644--- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx+++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx@@ -1,10 +1,10 @@+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { PullRequestChangeBreakdownRows } from "../pullRequest/PullRequestChangeBreakdownStat";import { ThreadDetailsControl } from "./ThreadDetailsControl";import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";import { selectEnvironmentQueryData } from "@t3tools/client-runtime/state/runtime";import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import type { EnvironmentId, ProjectId, PullRequestRef } from "@t3tools/contracts";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import {ArrowUpRightIcon,EyeIcon,@@ -106,7 +106,7 @@ export function ThreadDetailsPrRow({const serverConfigs = useServerConfigs();const supportsPullRequests =serverConfigs.get(environmentId)?.environment.capabilities.pullRequests === true;- const repository = sourceControlRepositorySelector(project?.repositoryIdentity);+ const repository = sourceControlClients.repositorySelector(project?.repositoryIdentity);const reference: PullRequestRef | null =supportsPullRequests && project !== null? linkedReferencediff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsxindex 17a438bd07f..31362b01f75 100644--- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx+++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx@@ -1,3 +1,4 @@+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query";import { Spinner } from "~/components/ui/spinner";import type { PullRequestSpeedActionResult } from "~/components/pullRequest/PullRequestSpeedActions";@@ -5,7 +6,7 @@ import { usePullRequestCloseBatch } from "~/components/pullRequest/usePullRequesimport { SidebarPointerSensor } from "~/components/Sidebar.pointer";import { resolveSidebarSweepKeys } from "~/components/Sidebar.logic";import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping";-import { pullRequestHostOf, resolveEnvironmentMachineKind } from "@t3tools/contracts";+import { resolveEnvironmentMachineKind } from "@t3tools/contracts";import type {EnvironmentId,ProjectId,@@ -15,7 +16,6 @@ import type {PullRequestListInput,PullRequestListResult,PullRequestListState,- SourceControlProviderKind,} from "@t3tools/contracts";import { useAtomValue } from "@effect/atom-react";import { useNavigate, useSearch } from "@tanstack/react-router";@@ -1014,9 +1014,9 @@ export function PullRequestsPage() {host:activePullRequestSurface.host ??(selectedProject?.repositoryIdentity- ? pullRequestHostOf(+ ? sourceControlClients.changeRequestHost(selectedProject.repositoryIdentity,- selectedProject.repositoryIdentity.provider as SourceControlProviderKind,+ selectedProject.repositoryIdentity.provider,): undefined),}diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.tsindex 292d40bfe40..2883897daf5 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts@@ -85,7 +85,7 @@ describe("pull request checkout commands", () => {remoteName: "origin",remoteUrl: "[email protected]:acme/web.git",},- provider,+ provider: SourceControlProviderKind.make(provider),});it("uses a matching enterprise identity and rejects an explicit host mismatch", () => {diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.tsindex dd29162fbde..9dabaea0992 100644--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts@@ -5,7 +5,6 @@ import {GitCommandError,PullRequestDetail,PullRequestOperationError,- pullRequestHostOf,type PullRequestAction,type PullRequestActor,type PullRequestBaseComparison,@@ -135,7 +134,7 @@ export function loadingPullRequestCheckoutCommand(if (identity?.provider !== undefined &&host &&- pullRequestHostOf(identity, definition.kind) !== host+ sourceControlClients.changeRequestHost(identity, definition.kind) !== host) {return null;}diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.tsindex 44cf97bda85..58f6964e4b9 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts@@ -50,7 +50,7 @@ function entry() {return {environmentId: "env-1",- provider: "github",+ provider: SourceControlProviderKind.make("github"),host: "github.com",projectId: "project-1",projectTitle: "t3code",@@ -752,7 +752,7 @@ describe("findProjectForRepository", () => {repositoryIdentity: {canonicalKey: `dev.azure.com/${path}`,locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },- provider: "azure-devops",+ provider: SourceControlProviderKind.make("azure-devops"),displayName: path,owner: "contoso",name: path.split("/").at(-1)!,@@ -788,7 +788,7 @@ describe("findProjectForRepository", () => {repositoryIdentity: {canonicalKey: `github.com/${repository}`,locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },- provider: "github",+ provider: SourceControlProviderKind.make("github"),displayName: repository,},});diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.tsindex fbd70381f87..656913257a1 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts@@ -1,3 +1,4 @@+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import * as Schema from "effect/Schema";import {@@ -5,13 +6,11 @@ import {PullRequestListEntry,PullRequestListProjectError,PullRequestListResult,- pullRequestHostOf,resolvePullRequestAuthorFilter,} from "@t3tools/contracts";import type {ProjectId,RepositoryIdentity,- SourceControlProviderKind,PullRequestAction,PullRequestActor,PullRequestDiffStat,@@ -23,8 +22,6 @@ import type {PullRequestState,} from "@t3tools/contracts";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";-import { toSortableTimestamp } from "../../lib/threadSort";import type { PullRequestListSort } from "./pullRequestListPreferences";@@ -1078,12 +1075,15 @@ export function findProjectForRepository<return false;}const identity = project.repositoryIdentity;- if (!identity || sourceControlRepositorySelector(identity)?.toLowerCase() !== repository) {+ if (+ !identity ||+ sourceControlClients.repositorySelector(identity)?.toLowerCase() !== repository+ ) {return false;}return (host === undefined ||- pullRequestHostOf(identity, identity.provider as SourceControlProviderKind) === host+ sourceControlClients.changeRequestHost(identity, identity.provider) === host);});// Azure repository names can collide across projects on the same host.diff --git a/apps/web/src/components/pullRequest/usePullRequestListView.ts b/apps/web/src/components/pullRequest/usePullRequestListView.tsindex 347a00b628b..2629fb6a34b 100644--- a/apps/web/src/components/pullRequest/usePullRequestListView.ts+++ b/apps/web/src/components/pullRequest/usePullRequestListView.ts@@ -1,13 +1,12 @@+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { parsePullRequestQuery } from "@t3tools/client-runtime/pull-request-query";import {- pullRequestHostOf,type EnvironmentId,type ProjectId,type PullRequestInvolvement,type PullRequestListFilters,type PullRequestListResult,type PullRequestListState,- type SourceControlProviderKind,} from "@t3tools/contracts";import { useState } from "react";@@ -156,9 +155,9 @@ export function usePullRequestScope(search: PullRequestsSearch) {const expectedHosts = (() => {const byHost = new Map<string, PullRequestExpectedHost>();for (const project of projects) {- const kind = project.repositoryIdentity?.provider as SourceControlProviderKind | undefined;+ const kind = project.repositoryIdentity?.provider;if (kind === undefined) continue;- const host = pullRequestHostOf(project.repositoryIdentity, kind);+ const host = sourceControlClients.changeRequestHost(project.repositoryIdentity, kind);if (!byHost.has(host)) byHost.set(host, { host, kind });}return [...byHost.values()];diff --git a/apps/web/src/hooks/usePullRequestLinking.ts b/apps/web/src/hooks/usePullRequestLinking.tsindex 18c31cd3714..98ed5462cf5 100644--- a/apps/web/src/hooks/usePullRequestLinking.ts+++ b/apps/web/src/hooks/usePullRequestLinking.ts@@ -1,4 +1,3 @@-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import type {EnvironmentId,ScopedThreadRef,@@ -101,7 +100,7 @@ export function usePullRequestLinking(environmentId: EnvironmentId | null | undereference: { ...parsed, url },legacyProjectId: legacyProject?.id ?? null,legacyRepository:- sourceControlRepositorySelector(legacyProject?.repositoryIdentity) ?? undefined,+ sourceControlClients.repositorySelector(legacyProject?.repositoryIdentity) ?? undefined,linked,});if (mutation === null)diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.tsindex 0d3361e73de..8c9a4199864 100644--- a/apps/web/src/lib/openPullRequestLink.ts+++ b/apps/web/src/lib/openPullRequestLink.ts@@ -11,7 +11,6 @@ import {sourceControlClients,type ChangeRequestLink,} from "@t3tools/client-runtime/source-control-clients";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import { useOpenLink } from "../browser/useOpenLink";import { useClientSettings } from "../hooks/useSettings";@@ -117,7 +116,8 @@ export function useOpenChangeRequestLink(const repository =serverConfigs.get(project.environmentId)?.environment.capabilities.threadPullRequests === true? parsed.repository- : (sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository);+ : (sourceControlClients.repositorySelector(project.repositoryIdentity) ??+ parsed.repository);event.preventDefault();event.stopPropagation();if (resolvedPanelRef) {diff --git a/packages/client-runtime/src/changeRequestLinks.test.ts b/packages/client-runtime/src/changeRequestLinks.test.tsindex f5d39305da2..be25a3e5b10 100644--- a/packages/client-runtime/src/changeRequestLinks.test.ts+++ b/packages/client-runtime/src/changeRequestLinks.test.ts@@ -1,4 +1,9 @@-import { EnvironmentId, ProjectId, type RepositoryIdentity } from "@t3tools/contracts";+import {+ EnvironmentId,+ ProjectId,+ type RepositoryIdentity,+ SourceControlProviderKind,+} from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import {@@ -15,7 +20,7 @@ describe("findProjectForChangeRequest", () => {const projects = [project({canonicalKey: "gitlab.com/t3tools/platform/t3code",- provider: "gitlab",+ provider: SourceControlProviderKind.make("gitlab"),displayName: "t3tools/platform/t3code",owner: "t3tools",name: "t3code",@@ -34,7 +39,7 @@ describe("findProjectForChangeRequest", () => {const projects = [project({canonicalKey: "github.com/pingdotgg/t3code",- provider: "github",+ provider: SourceControlProviderKind.make("github"),owner: "pingdotgg",name: "t3code",}),@@ -56,7 +61,7 @@ describe("resolvePullRequestPreviewTarget", () => {environmentId,repositoryIdentity: {canonicalKey: "github.com/acme/web",- provider: "github",+ provider: SourceControlProviderKind.make("github"),displayName: "acme/web",locator: { source: "git-remote", remoteName: "origin", remoteUrl: "[email protected]:acme/web" },} satisfies RepositoryIdentity,@@ -81,7 +86,7 @@ describe("resolvePullRequestPreviewTarget", () => {describe("projectChangeRequestUrl", () => {const identity = (provider: string): RepositoryIdentity => ({canonicalKey: "github.com/acme/default",- provider,+ provider: SourceControlProviderKind.make(provider),locator: {source: "git-remote",remoteName: "origin",@@ -95,6 +100,23 @@ describe("projectChangeRequestUrl", () => {);});+ it("builds the project's own Azure repository from its full path, not its short selector", () => {+ const azure: RepositoryIdentity = {+ canonicalKey: "dev.azure.com/org/project/_git/web",+ provider: SourceControlProviderKind.make("azure-devops"),+ owner: "org",+ name: "web",+ locator: {+ source: "git-remote",+ remoteName: "origin",+ remoteUrl: "https://dev.azure.com/org/project/_git/web",+ },+ };+ expect(projectChangeRequestUrl(azure, "web", 42)).toBe(+ "https://dev.azure.com/org/project/_git/web/pullrequest/42",+ );+ });+it("builds nothing without a project host that knows its URL shape", () => {expect(projectChangeRequestUrl(null, "acme/repository", 1)).toBeNull();expect(projectChangeRequestUrl(identity("unknown"), "acme/repository", 1)).toBeNull();diff --git a/packages/client-runtime/src/changeRequestLinks.ts b/packages/client-runtime/src/changeRequestLinks.tsindex 36c9097c951..3786a9eff06 100644--- a/packages/client-runtime/src/changeRequestLinks.ts+++ b/packages/client-runtime/src/changeRequestLinks.ts@@ -5,7 +5,6 @@ import type {RepositoryIdentity,} from "@t3tools/contracts";import type { ChangeRequestLink } from "@t3tools/source-control-core/client/definition";-import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import { sourceControlClients } from "./sourceControlClients.ts";@@ -53,7 +52,8 @@ export function resolvePullRequestPreviewTarget({input: {projectId: project.id,host: parsed.authority ?? parsed.host,- repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository,+ repository:+ sourceControlClients.repositorySelector(project.repositoryIdentity) ?? parsed.repository,number: parsed.number,},};@@ -66,12 +66,16 @@ export function projectChangeRequestUrl(number: number,): string | null {if (identity?.provider === undefined) return null;- const host = identity.canonicalKey.split("/")[0];+ const [host, ...path] = identity.canonicalKey.split("/");if (!host) return null;+ // The RPC selector can be shorter than the browser path (Azure's `web` for+ // `org/project/_git/web`), so the project's own repository uses its full key.+ const ownRepository = sourceControlClients.repositorySelector(identity) === repository;return sourceControlClients.get(identity.provider).changeRequestUrl({host,- repository,+ repository: ownRepository ? path.join("/") : repository,number,remoteUrl: identity.locator.remoteUrl.trim(),+ ...(ownRepository && identity.webUrl !== undefined ? { webUrl: identity.webUrl } : {}),});}diff --git a/packages/client-runtime/src/pullRequestLinkInput.ts b/packages/client-runtime/src/pullRequestLinkInput.tsindex c897dc45887..30c9e3e89ca 100644--- a/packages/client-runtime/src/pullRequestLinkInput.ts+++ b/packages/client-runtime/src/pullRequestLinkInput.ts@@ -1,4 +1,4 @@-import { pullRequestHostOf, type RepositoryIdentity } from "@t3tools/contracts";+import type { RepositoryIdentity } from "@t3tools/contracts";import { sourceControlClients } from "./sourceControlClients.ts";@@ -42,7 +42,7 @@ export function pullRequestLinkProject(identity: RepositoryIdentity | null | und(identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);if (repository === null) return null;const definition = sourceControlClients.get(identity.provider ?? "unknown");- const host = pullRequestHostOf(identity, definition.kind);+ const host = sourceControlClients.changeRequestHost(identity, definition.kind);return {host,repository,diff --git a/packages/client-runtime/src/sourceControlClients.test.ts b/packages/client-runtime/src/sourceControlClients.test.tsindex 4a646bc9cab..9a2cb20e4a4 100644--- a/packages/client-runtime/src/sourceControlClients.test.ts+++ b/packages/client-runtime/src/sourceControlClients.test.ts@@ -1,4 +1,4 @@-import { ProjectId } from "@t3tools/contracts";+import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import { sourceControlClients } from "./sourceControlClients.ts";@@ -238,3 +238,115 @@ describe("change request URLs built from a parsed link", () => {});});});++describe("sourceControlClients.recognizeRemote", () => {+ const kindOfRemote = (url: string) => sourceControlClients.recognizeRemote(url)?.kind ?? null;++ it("asks hosts in a fixed order when one hostname carries several hosts' labels", () => {+ expect(kindOfRemote("https://gitea.github.example/o/r")).toBe("forgejo");+ expect(kindOfRemote("https://forgejo.gitlab.example/o/r")).toBe("forgejo");+ expect(kindOfRemote("https://gitlab.github.example/o/r")).toBe("github");+ expect(kindOfRemote("https://bitbucket.gitlab.example/o/r")).toBe("gitlab");+ expect(kindOfRemote("https://bitbucket.visualstudio.com/p/_git/r")).toBe("azure-devops");+ expect(kindOfRemote("[email protected]:pingdotgg/t3code.git")).toBe("gitcafe");+ });++ it("reads a remote no host claims as an unknown host, and a local path as no host", () => {+ expect(+ sourceControlClients.recognizeRemote("https://self-hosted.example.test:8443/group/repo.git"),+ ).toEqual({+ kind: "unknown",+ name: "self-hosted.example.test:8443",+ baseUrl: "https://self-hosted.example.test:8443",+ });+ expect(sourceControlClients.recognizeRemote("git@github-work:owner/repo.git")).toEqual({+ kind: "unknown",+ name: "github-work",+ baseUrl: "https://github-work",+ });+ for (const local of ["/srv/git/repo.git", "C:/repos/project", "file:///srv/git/repo.git", ""]) {+ expect(sourceControlClients.recognizeRemote(local), local).toBeNull();+ }+ });+});++describe("sourceControlClients repository keys", () => {+ // Persisted as `repositoryIdentity.canonicalKey` and in thread pull request keys.+ it.each([+ ["[email protected]:T3Tools/T3Code.git", "github.com/t3tools/t3code"],+ ["ssh://[email protected]:2222/team/project.git", "gitlab.company.com/team/project"],+ [+ "[email protected]:v3/T3Tools/Platform/T3Code",+ "dev.azure.com/t3tools/platform/_git/t3code",+ ],+ [+ "[email protected]:v3/T3Tools/Platform/T3Code",+ "t3tools.visualstudio.com/platform/_git/t3code",+ ],+ [+ "https://T3Tools.visualstudio.com/DefaultCollection/Platform/_git/T3Code",+ "t3tools.visualstudio.com/defaultcollection/platform/_git/t3code",+ ],+ ["[email protected]:v3/o/p", "ssh.dev.azure.com/v3/o/p"],+ ["ssh.dev.azure.com/v3/o/p/r", "ssh.dev.azure.com/v3/o/p/r"],+ ["C:/repos/project", "c:/repos/project"],+ ])("keys %s as %s", (remote, key) => {+ expect(sourceControlClients.repositoryKeyFromRemote(remote)).toBe(key);+ });++ it("compares Azure DevOps spellings on dev.azure.com and leaves other keys alone", () => {+ expect(+ sourceControlClients.canonicalRepositoryKey(+ "org.visualstudio.com/defaultcollection/project/_git/repo",+ ),+ ).toBe("dev.azure.com/org/project/_git/repo");+ expect(sourceControlClients.findByRepositoryKey("dev.azure.com/o/r")?.kind).toBe(+ "azure-devops",+ );+ expect(sourceControlClients.canonicalRepositoryKey("tfs.corp.example/c/p/_git/r")).toBe(+ "tfs.corp.example/c/p/_git/r",+ );+ expect(sourceControlClients.findByRepositoryKey("github.com/o/r")).toBeUndefined();+ });+});++describe("sourceControlClients project hosts", () => {+ const identity = {+ canonicalKey: "forge.example/team/repo",+ locator: { remoteUrl: "http://forge.example:3000/team/repo.git" },+ };++ it("keeps an HTTP remote's port for Forgejo only, and falls back to the kind without a key", () => {+ expect(sourceControlClients.changeRequestHost(identity, "forgejo")).toBe("forge.example:3000");+ expect(sourceControlClients.changeRequestHost(identity, "gitlab")).toBe("forge.example");+ expect(sourceControlClients.changeRequestHost(identity, undefined)).toBe("forge.example");+ expect(+ sourceControlClients.changeRequestHost(+ { locator: { remoteUrl: "https://x.example/a/b" } },+ "github",+ ),+ ).toBe("github");+ });++ it("selects a repository by its path except where the host's tools take a name", () => {+ const repository = {+ displayName: "group/subgroup/service",+ owner: "group",+ name: "service",+ };+ expect(sourceControlClients.repositorySelector(repository)).toBe("group/subgroup/service");+ expect(+ sourceControlClients.repositorySelector({+ ...repository,+ provider: SourceControlProviderKind.make("gitlab"),+ }),+ ).toBe("group/subgroup/service");+ expect(+ sourceControlClients.repositorySelector({+ ...repository,+ provider: SourceControlProviderKind.make("azure-devops"),+ }),+ ).toBe("service");+ expect(sourceControlClients.repositorySelector({ owner: "o", name: "r" })).toBe("o/r");+ });+});diff --git a/packages/client-runtime/src/sourceControlClients.ts b/packages/client-runtime/src/sourceControlClients.tsindex 7faf3abcc90..ac67c682c52 100644--- a/packages/client-runtime/src/sourceControlClients.ts+++ b/packages/client-runtime/src/sourceControlClients.ts@@ -22,7 +22,8 @@ import * as GitLab from "@t3tools/source-control-gitlab/client/definition";* GitHub comes first because a repository that has not reported its host yet reads as GitHub,* which is what clients have always shown there. A change request URL goes to the first host* whose shape it has, so GitCafe, which claims `/pull/` and `/pulls/` only on its own hostnames,- * claims before GitHub and Forgejo, which claim them everywhere. The server's+ * claims before GitHub and Forgejo, which claim them everywhere. A hostname can carry more than+ * one host's label (`gitea.github.example`), so remote recognition has its own order. The server's* `sourceControl/sourceControlClients.ts` keeps the same order.*/const BUILT_IN_SOURCE_CONTROL_CLIENTS = [@@ -36,7 +37,17 @@ const BUILT_IN_SOURCE_CONTROL_CLIENTS = [export const sourceControlClients = makeSourceControlClientRegistry(BUILT_IN_SOURCE_CONTROL_CLIENTS,- { claimChangeRequestUrlsFirst: [GitCafe.definition.kind] },+ {+ claimChangeRequestUrlsFirst: [GitCafe.definition.kind],+ recognizeRemotesIn: [+ GitCafe.definition.kind,+ Forgejo.definition.kind,+ GitHub.definition.kind,+ GitLab.definition.kind,+ AzureDevOps.definition.kind,+ Bitbucket.definition.kind,+ ],+ },);export type { GitHubSettings } from "@t3tools/source-control-github/client/definition";diff --git a/packages/client-runtime/src/state/projectGrouping.test.ts b/packages/client-runtime/src/state/projectGrouping.test.tsindex 8ca5ed4dea0..824fb87e3c4 100644--- a/packages/client-runtime/src/state/projectGrouping.test.ts+++ b/packages/client-runtime/src/state/projectGrouping.test.ts@@ -1,4 +1,4 @@-import { EnvironmentId, ProjectId } from "@t3tools/contracts";+import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import type { EnvironmentProject } from "./models.ts";@@ -84,7 +84,7 @@ const repositoryIdentity = {remoteName: "upstream",remoteUrl: "https://github.com/t3tools/t3code.git",},- provider: "github",+ provider: SourceControlProviderKind.make("github"),owner: "t3tools",name: "t3code",displayName: "T3 Code",diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 18d09c304a8..c03b57d2756 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -8,6 +8,7 @@ import {ThreadId,TrimmedNonEmptyString,} from "./baseSchemas.ts";+import { SourceControlProviderKind } from "./sourceControl.ts";export const ORCHESTRATION_PROTOCOL_VERSION = 2;export const ORCHESTRATION_PROTOCOL_VERSION_TEXT = "2";@@ -186,7 +187,7 @@ export const RepositoryIdentity = Schema.Struct({/** Work tree root, or the git dir for a bare repository. */rootPath: Schema.optionalKey(TrimmedNonEmptyString),displayName: Schema.optionalKey(TrimmedNonEmptyString),- provider: Schema.optionalKey(TrimmedNonEmptyString),+ provider: Schema.optionalKey(SourceControlProviderKind),owner: Schema.optionalKey(TrimmedNonEmptyString),name: Schema.optionalKey(TrimmedNonEmptyString),origin: Schema.optionalKey(RepositoryOrigin),diff --git a/packages/contracts/src/pullRequest.test.ts b/packages/contracts/src/pullRequest.test.tsindex bf9d359b0e3..7c56ca8b9df 100644--- a/packages/contracts/src/pullRequest.test.ts+++ b/packages/contracts/src/pullRequest.test.ts@@ -5,7 +5,6 @@ import { describe, expect, it } from "vite-plus/test";import {PullRequestDetail,PullRequestListResult,- pullRequestHostOf,resolvePullRequestAuthorFilter,} from "./pullRequest.ts";@@ -61,24 +60,6 @@ const LIST_RESULT: PullRequestListResult = {};describe("PullRequestListResult", () => {- it("separates Forgejo HTTP ports while preserving other provider host identities", () => {- const identity = {- canonicalKey: "forge.example/team/repo",- locator: { remoteUrl: "http://forge.example:3000/team/repo.git" },- };- expect(pullRequestHostOf(identity, SourceControlProviderKind.make("forgejo"))).toBe(- "forge.example:3000",- );- expect(pullRequestHostOf(identity, SourceControlProviderKind.make("gitlab"))).toBe(- "forge.example",- );- expect(- pullRequestHostOf(- { ...identity, locator: { remoteUrl: "ssh://[email protected]:2222/team/repo.git" } },- SourceControlProviderKind.make("forgejo"),- ),- ).toBe("forge.example");- });/*** The RPC builds this codec at call time, so a shape it cannot lower — an open-keyed record* with an optional value, for one — fails as an interrupted request rather than as a schemadiff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex bf8f124c360..7e371e86772 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -938,27 +938,6 @@ const PROVIDER_REQUIREMENT = new Map<],]);-export function pullRequestHostOf(- identity:- | {- readonly canonicalKey?: string | undefined;- readonly locator?: { readonly remoteUrl: string } | undefined;- }- | null- | undefined,- kind: SourceControlProviderKind,-): string {- if (kind === "forgejo") {- try {- const remote = new URL(identity?.locator?.remoteUrl ?? "");- if (remote.protocol === "http:" || remote.protocol === "https:")- return remote.host.toLowerCase();- } catch {}- }- const host = identity?.canonicalKey?.split("/")[0]?.trim();- return host === undefined || host.length === 0 ? kind : host.toLowerCase();-}-/*** `author:me` names whoever is signed in to the host being read, GitHub's `@me` spelled either* way. A host's own search would answer it, but the page and the server both re-check an authordiff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.tsindex 91d01cd3a18..adf44d2289e 100644--- a/packages/shared/src/git.test.ts+++ b/packages/shared/src/git.test.ts@@ -62,27 +62,6 @@ describe("normalizeGitRemoteUrl", () => {expect(normalizeGitRemoteUrl("C:/repos/project")).toBe("c:/repos/project");expect(normalizeGitRemoteUrl("git@x:team/project.git")).toBe("x/team/project");});-- it("gives an Azure DevOps repository the same key over SSH as over HTTPS", () => {- expect(normalizeGitRemoteUrl("[email protected]:v3/T3Tools/Platform/T3Code")).toBe(- "dev.azure.com/t3tools/platform/_git/t3code",- );- expect(normalizeGitRemoteUrl("ssh://[email protected]:22/v3/T3Tools/Platform/T3Code")).toBe(- "dev.azure.com/t3tools/platform/_git/t3code",- );- expect(- normalizeGitRemoteUrl("https://[email protected]/T3Tools/Platform/_git/T3Code"),- ).toBe("dev.azure.com/t3tools/platform/_git/t3code");- });-- it("puts the organization back in the host on the name dev.azure.com replaced", () => {- expect(- normalizeGitRemoteUrl("[email protected]:v3/T3Tools/Platform/T3Code"),- ).toBe("t3tools.visualstudio.com/platform/_git/t3code");- expect(normalizeGitRemoteUrl("https://T3Tools.visualstudio.com/Platform/_git/T3Code")).toBe(- "t3tools.visualstudio.com/platform/_git/t3code",- );- });});describe("parseOriginUrlFromGitConfig", () => {diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.tsindex 32b7fbf8858..7bf954cc3d8 100644--- a/packages/shared/src/git.ts+++ b/packages/shared/src/git.ts@@ -1,7 +1,6 @@import type {BranchNamingOptions,VcsRef,- SourceControlProviderInfo,VcsStatusLocalResult,VcsStatusRemoteResult,VcsStatusResult,@@ -9,7 +8,6 @@ import type {} from "@t3tools/contracts";import * as Arr from "effect/Array";import * as Result from "effect/Result";-import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";export const WORKTREE_BRANCH_PREFIX = "t3";const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";@@ -125,41 +123,32 @@ export function isTemporaryWorktreeBranch(refName: string): boolean {return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());}-/**- * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and- * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`- * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository- * to every comparison made against a pull request URL, which arrives in the web spelling.- */-function azureDevOpsRepositoryKey(host: string, segments: ReadonlyArray<string>): string | null {- if (host !== "ssh.dev.azure.com" && host !== "vs-ssh.visualstudio.com") return null;- const [marker, organization, project, repository] = segments;- if (segments.length !== 4 || marker !== "v3") return null;- if (!organization || !project || !repository) return null;- return host === "ssh.dev.azure.com"- ? `dev.azure.com/${organization}/${project}/_git/${repository}`- : `${organization}.visualstudio.com/${project}/_git/${repository}`;-}--export function normalizeGitRemoteUrl(value: string): string {- const normalized = value+function lowerCaseRemote(value: string): string {+ return value.trim().replace(/\/+$/g, "").replace(/\.git$/i, "").toLowerCase();+}++/**+ * The host and repository path a remote names, lower case and without a port, or null for a+ * remote that names no host, such as a local path.+ */+export function parseGitRemoteRepository(+ value: string,+): { readonly host: string; readonly path: string } | null {+ const normalized = lowerCaseRemote(value);if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {try {const url = new URL(normalized);const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0);if (url.hostname && repositorySegments.length > 1) {- return (- azureDevOpsRepositoryKey(url.hostname, repositorySegments) ??- `${url.hostname}/${repositorySegments.join("/")}`- );+ return { host: url.hostname, path: repositorySegments.join("/") };}} catch {- return normalized;+ return null;}}@@ -169,11 +158,17 @@ export function normalizeGitRemoteUrl(value: string): string {: /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);const scpHost = scpStyleHostAndPath?.[1];const scpPath = scpStyleHostAndPath?.[2];- if (scpHost && scpPath) {- return azureDevOpsRepositoryKey(scpHost, scpPath.split("/")) ?? `${scpHost}/${scpPath}`;- }+ return scpHost && scpPath ? { host: scpHost, path: scpPath } : null;+}- return normalized;+/**+ * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that+ * spells repositories differently over SSH has its source control registry's+ * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.+ */+export function normalizeGitRemoteUrl(value: string): string {+ const repository = parseGitRemoteRepository(value);+ return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;}function parseGitConfigValue(raw: string): string {@@ -251,20 +246,6 @@ export function parseOriginUrlFromGitConfig(configText: string): string | null {return originUrl ?? firstRemoteUrl;}-export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {- const trimmed = url?.trim() ?? "";- if (trimmed.length === 0) {- return null;- }-- const match =- /^(?:git@github\.com:|ssh:\/\/(?:git@)?github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(- trimmed,- );- const repositoryNameWithOwner = match?.[1]?.trim() ?? "";- return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;-}-function deriveLocalBranchNameCandidatesFromRemoteRef(branchName: string,remoteName?: string,@@ -318,12 +299,6 @@ export function dedupeRemoteBranchesWithLocalMatches(});}-export function detectSourceControlProviderFromGitRemoteUrl(- remoteUrl: string,-): SourceControlProviderInfo | null {- return detectSourceControlProviderFromRemoteUrl(remoteUrl);-}-const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {hasUpstream: false,aheadCount: 0,diff --git a/packages/shared/src/sourceControl.test.ts b/packages/shared/src/sourceControl.test.tsindex 23d0c8b4ba8..bb3ad5716fd 100644--- a/packages/shared/src/sourceControl.test.ts+++ b/packages/shared/src/sourceControl.test.ts@@ -1,171 +1,11 @@import { SourceControlProviderKind } from "@t3tools/contracts";-import { describe, expect, it } from "vite-plus/test";+import { expect, it } from "vite-plus/test";-import {- sourceControlRepositorySelector,- detectSourceControlProviderFromRemoteUrl,- getChangeRequestTerminologyForKind,-} from "./sourceControl.ts";+import { getChangeRequestTerminologyForKind } from "./sourceControl.ts";-describe("detectSourceControlProviderFromRemoteUrl", () => {- it("detects Forgejo and Gitea hosts while preserving HTTP origins", () => {- for (const host of ["codeberg.org", "forgejo.example.test", "gitea.example.test"]) {- expect(detectSourceControlProviderFromRemoteUrl(`http://${host}:3000/team/repo.git`)).toEqual(- {- kind: "forgejo",- name: "Forgejo",- baseUrl: `http://${host}:3000`,- },- );- }- expect(getChangeRequestTerminologyForKind(SourceControlProviderKind.make("forgejo"))).toEqual({- shortLabel: "PR",- singular: "pull request",- });+it("calls a Forgejo change request a pull request", () => {+ expect(getChangeRequestTerminologyForKind(SourceControlProviderKind.make("forgejo"))).toEqual({+ shortLabel: "PR",+ singular: "pull request",});-- it("detects Azure DevOps SSH remotes", () => {- expect(- detectSourceControlProviderFromRemoteUrl("[email protected]:v3/org/project/repo")?.kind,- ).toBe("azure-devops");- expect(- detectSourceControlProviderFromRemoteUrl("ssh://[email protected]:22/v3/org/project/repo")- ?.kind,- ).toBe("azure-devops");- expect(- detectSourceControlProviderFromRemoteUrl("[email protected]:v3/org/project/repo")- ?.kind,- ).toBe("azure-devops");- });-- it("preserves ports while classifying by hostname", () => {- expect(- detectSourceControlProviderFromRemoteUrl("https://gitlab.com:8443/group/repo.git"),- ).toEqual({- kind: "gitlab",- name: "GitLab",- baseUrl: "https://gitlab.com:8443",- });- expect(- detectSourceControlProviderFromRemoteUrl(- "https://self-hosted.example.test:8443/group/repo.git",- ),- ).toEqual({- kind: "unknown",- name: "self-hosted.example.test:8443",- baseUrl: "https://self-hosted.example.test:8443",- });- });-- it("does not reuse SSH ports for HTTPS provider URLs", () => {- expect(- detectSourceControlProviderFromRemoteUrl("ssh://[email protected]:24/group/repo.git"),- ).toEqual({- kind: "gitlab",- name: "GitLab Self-Hosted",- baseUrl: "https://gitlab.example.test",- });- expect(- detectSourceControlProviderFromRemoteUrl("ssh://[email protected]:24/team/project.git"),- ).toEqual({- kind: "unknown",- name: "code.example.test",- baseUrl: "https://code.example.test",- });- });-- it("matches self-hosted providers by complete DNS labels", () => {- expect(- detectSourceControlProviderFromRemoteUrl("https://github.example.com/owner/repo.git")?.kind,- ).toBe("github");- expect(- detectSourceControlProviderFromRemoteUrl("https://gitlab.example.com/group/repo.git")?.kind,- ).toBe("gitlab");- expect(- detectSourceControlProviderFromRemoteUrl("https://bitbucket.example.com/workspace/repo.git")- ?.kind,- ).toBe("bitbucket");- });-- it("detects GitHub Enterprise Cloud data residency hosts on ghe.com", () => {- expect(detectSourceControlProviderFromRemoteUrl("https://acme.ghe.com/owner/repo.git")).toEqual(- {- kind: "github",- name: "GitHub Self-Hosted",- baseUrl: "https://acme.ghe.com",- },- );- expect(detectSourceControlProviderFromRemoteUrl("[email protected]:owner/repo.git")?.kind).toBe(- "github",- );- expect(detectSourceControlProviderFromRemoteUrl("https://ghe.com/owner/repo.git")?.kind).toBe(- "unknown",- );- });-- it("does not match provider names embedded in unrelated DNS labels", () => {- expect(- detectSourceControlProviderFromRemoteUrl("https://notgithub.example.com/owner/repo.git")- ?.kind,- ).toBe("unknown");- expect(- detectSourceControlProviderFromRemoteUrl("https://notgitlab.example.com/group/repo.git")- ?.kind,- ).toBe("unknown");- expect(- detectSourceControlProviderFromRemoteUrl(- "https://notbitbucket.example.com/workspace/repo.git",- )?.kind,- ).toBe("unknown");- });-- it("detects SSH remotes with non-git SSH users (e.g. gitlab@, deploy@)", () => {- expect(- detectSourceControlProviderFromRemoteUrl("[email protected]:group/project.git")?.kind,- ).toBe("gitlab");- expect(- detectSourceControlProviderFromRemoteUrl("[email protected]:group/project.git")- ?.baseUrl,- ).toBe("https://gitlab.example.com");- expect(detectSourceControlProviderFromRemoteUrl("[email protected]:owner/repo.git")?.kind).toBe(- "github",- );- expect(- detectSourceControlProviderFromRemoteUrl("[email protected]:workspace/repo.git")?.kind,- ).toBe("bitbucket");- });-});--it("names an Azure DevOps repository by its own name, not its project path", () => {- // `az repos pr list --repository` takes a name and detects the organisation and project from- // the checkout; the recorded `org/project/_git/repo` path is refused, and the repository then- // reads as unavailable on the page.- const selector = sourceControlRepositorySelector({- provider: "azure-devops",- displayName: "contoso/payments/_git/checkout",- owner: "contoso",- name: "checkout",- });- expect(selector).toBe("checkout");-});--it("decodes an Azure DevOps repository name that the remote URL percent-encodes", () => {- // A remote spells a space as `%20`, and `az repos pr list --repository` reads that literally.- const selector = sourceControlRepositorySelector({- provider: "azure-devops",- displayName: "contoso/payments%20(eu)/_git/checkout%20(eu)",- owner: "contoso",- name: "checkout%20(eu)",- });- expect(selector).toBe("checkout (eu)");-});--it("keeps a GitLab identity's whole path, because a nested group is part of the name", () => {- const selector = sourceControlRepositorySelector({- provider: "gitlab",- displayName: "group/subgroup/service",- owner: "group",- name: "service",- });- expect(selector).toBe("group/subgroup/service");});diff --git a/packages/shared/src/sourceControl.ts b/packages/shared/src/sourceControl.tsindex 5729d201501..f7039961f97 100644--- a/packages/shared/src/sourceControl.ts+++ b/packages/shared/src/sourceControl.ts@@ -1,5 +1,4 @@-import { SourceControlProviderKind } from "@t3tools/contracts";-import type { RepositoryIdentity, SourceControlProviderInfo } from "@t3tools/contracts";+import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";export interface ChangeRequestPresentation {readonly icon:@@ -143,181 +142,3 @@ export function isSshRemoteUrl(remoteUrl: string): boolean {const trimmed = remoteUrl.trim();return SCP_SSH_REMOTE_PATTERN.test(trimmed) || trimmed.toLowerCase().startsWith("ssh://");}--function parseRemoteHost(remoteUrl: string): string | null {- const trimmed = remoteUrl.trim();- if (trimmed.length === 0) {- return null;- }-- const scpMatch = SCP_SSH_REMOTE_PATTERN.exec(trimmed);- if (scpMatch?.[1]) {- return scpMatch[1].toLowerCase();- }-- try {- const url = new URL(trimmed);- return (url.protocol === "ssh:" ? url.hostname : url.host).toLowerCase();- } catch {- return null;- }-}--function parseHostName(host: string): string {- try {- return new URL(`https://${host}`).hostname.toLowerCase();- } catch {- return host.replace(/:\d+$/u, "").toLowerCase();- }-}--function toBaseUrl(host: string): string {- return `https://${host}`;-}--function hasDnsLabel(host: string, label: string): boolean {- return host.split(".").includes(label);-}--/** `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise. */-function isGitHubHost(host: string): boolean {- return host === "github.com" || host.endsWith(".ghe.com") || hasDnsLabel(host, "github");-}--function isGitLabHost(host: string): boolean {- return host === "gitlab.com" || hasDnsLabel(host, "gitlab");-}--function isAzureDevOpsHost(host: string): boolean {- // `ssh.dev.azure.com` is the default Azure DevOps SSH clone host- // ([email protected]:v3/org/project/repo), so match any `*.dev.azure.com`- // subdomain, not just the bare `dev.azure.com`. Legacy hosts stay under- // `.visualstudio.com` (including `vs-ssh.visualstudio.com`).- return (- host === "dev.azure.com" ||- host.endsWith(".dev.azure.com") ||- host.endsWith(".visualstudio.com")- );-}--function isGitCafeHost(host: string): boolean {- return host === "git.cafe" || host === "staging.git.cafe";-}--function isBitbucketHost(host: string): boolean {- return host === "bitbucket.org" || hasDnsLabel(host, "bitbucket");-}--export function detectSourceControlProviderFromRemoteUrl(- remoteUrl: string,-): SourceControlProviderInfo | null {- const host = parseRemoteHost(remoteUrl);- if (!host) {- return null;- }- const hostname = parseHostName(host);-- if (isGitCafeHost(hostname)) {- return {- kind: SourceControlProviderKind.make("gitcafe"),- name: "GitCafe",- baseUrl: toBaseUrl(hostname),- };- }-- if (- hostname === "codeberg.org" ||- hasDnsLabel(hostname, "forgejo") ||- hasDnsLabel(hostname, "gitea")- ) {- return {- kind: SourceControlProviderKind.make("forgejo"),- name: "Forgejo",- baseUrl: /^https?:/iu.test(remoteUrl.trim())- ? new URL(remoteUrl.trim()).origin- : toBaseUrl(host),- };- }-- if (isGitHubHost(hostname)) {- return {- kind: SourceControlProviderKind.make("github"),- name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",- baseUrl: toBaseUrl(host),- };- }-- if (isGitLabHost(hostname)) {- return {- kind: SourceControlProviderKind.make("gitlab"),- name: hostname === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",- baseUrl: toBaseUrl(host),- };- }-- if (isAzureDevOpsHost(hostname)) {- return {- kind: SourceControlProviderKind.make("azure-devops"),- name: "Azure DevOps",- baseUrl: toBaseUrl(host),- };- }-- if (isBitbucketHost(hostname)) {- return {- kind: SourceControlProviderKind.make("bitbucket"),- name: hostname === "bitbucket.org" ? "Bitbucket" : "Bitbucket Self-Hosted",- baseUrl: toBaseUrl(host),- };- }-- return {- kind: SourceControlProviderKind.make("unknown"),- name: host,- baseUrl: toBaseUrl(host),- };-}--function decodeUrlPathSegment(segment: string): string {- try {- return decodeURIComponent(segment);- } catch {- return segment;- }-}--/**- * Azure DevOps is the exception: `az repos pr list --repository` takes a repository name, and- * takes the organisation and project from the checkout it detects — so the recorded- * `org/project/_git/repo` path is refused outright and the whole repository reads as- * unavailable. Its name is the last segment, which is what this hands over. The segment comes- * from the remote URL, where a name with a space reads `my%20repo`; `az` looks that up literally- * and answers 404, so it goes out decoded.- */-export function sourceControlRepositorySelector(- identity:- | Pick<RepositoryIdentity, "provider" | "displayName" | "owner" | "name">- | null- | undefined,-): string | null {- if (!identity) return null;- if (identity.provider === "azure-devops") {- const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");- const name = identity.name || segments.at(-1);- return name ? decodeUrlPathSegment(name) : null;- }- if (identity.displayName) return identity.displayName;- return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;-}--export function canonicalRepositoryKey(key: string): string {- return key- .replace(- /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,- "dev.azure.com/$1/$2/_git/$3",- )- .replace(- /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,- "dev.azure.com/$1/$2/_git/$3",- );-}diff --git a/packages/source-control-azure-devops/src/client/definition.test.ts b/packages/source-control-azure-devops/src/client/definition.test.tsindex c4a0e4fd526..b739e8de831 100644--- a/packages/source-control-azure-devops/src/client/definition.test.ts+++ b/packages/source-control-azure-devops/src/client/definition.test.ts@@ -1,4 +1,9 @@+import { SourceControlProviderKind } from "@t3tools/contracts";import type { ChangeRequestProjectIdentity } from "@t3tools/source-control-core/client/definition";+import {+ makeSourceControlClientRegistry,+ recognizeRemoteWith,+} from "@t3tools/source-control-core/client/definition";import { describe, expect, it } from "vite-plus/test";import { definition } from "./definition.ts";@@ -102,3 +107,89 @@ describe("Azure DevOps change request URLs", () => {}});});++describe("Azure DevOps remotes", () => {+ it("recognises the SSH clone hosts as well as the web ones", () => {+ for (const remote of [+ "[email protected]:v3/org/project/repo",+ "ssh://[email protected]:22/v3/org/project/repo",+ "[email protected]:v3/org/project/repo",+ "https://[email protected]/org/project/_git/repo",+ ]) {+ expect(recognizeRemoteWith(definition, remote)?.kind, remote).toBe("azure-devops");+ }+ expect(recognizeRemoteWith(definition, "https://azure.example/o/p/_git/r")).toBeNull();+ });+});++describe("Azure DevOps repository keys", () => {+ const registry = makeSourceControlClientRegistry([definition]);++ it("gives a repository the same key over SSH as over HTTPS", () => {+ for (const remote of [+ "[email protected]:v3/T3Tools/Platform/T3Code",+ "ssh://[email protected]:22/v3/T3Tools/Platform/T3Code",+ "https://[email protected]/T3Tools/Platform/_git/T3Code",+ ]) {+ expect(registry.repositoryKeyFromRemote(remote), remote).toBe(+ "dev.azure.com/t3tools/platform/_git/t3code",+ );+ }+ });++ it("keeps the organization in the host for the legacy visualstudio.com remotes", () => {+ for (const remote of [+ "[email protected]:v3/T3Tools/Platform/T3Code",+ "https://T3Tools.visualstudio.com/Platform/_git/T3Code",+ ]) {+ expect(registry.repositoryKeyFromRemote(remote), remote).toBe(+ "t3tools.visualstudio.com/platform/_git/t3code",+ );+ }+ });++ it("compares every spelling on dev.azure.com", () => {+ for (const key of [+ "ssh.dev.azure.com/v3/org/project/repo",+ "vs-ssh.visualstudio.com/v3/org/project/repo",+ "org.visualstudio.com/project/_git/repo",+ "org.visualstudio.com/defaultcollection/project/_git/repo",+ "dev.azure.com/org/project/_git/repo",+ ]) {+ expect(registry.canonicalRepositoryKey(key), key).toBe("dev.azure.com/org/project/_git/repo");+ expect(registry.findByRepositoryKey(key), key).toBe(definition);+ }+ expect(registry.canonicalRepositoryKey("tfs.example/c/p/_git/r")).toBe(+ "tfs.example/c/p/_git/r",+ );+ expect(registry.findByRepositoryKey("tfs.example/c/p/_git/r")).toBeUndefined();+ });+});++describe("Azure DevOps repository selector", () => {+ const registry = makeSourceControlClientRegistry([definition]);++ it("names a repository by its own name, not its project path", () => {+ // `az repos pr list --repository` takes a name and detects the organisation and project from+ // the checkout; the recorded `org/project/_git/repo` path is refused.+ expect(+ registry.repositorySelector({+ provider: SourceControlProviderKind.make("azure-devops"),+ displayName: "contoso/payments/_git/checkout",+ owner: "contoso",+ name: "checkout",+ }),+ ).toBe("checkout");+ });++ it("decodes a name the remote URL percent-encodes", () => {+ expect(+ registry.repositorySelector({+ provider: SourceControlProviderKind.make("azure-devops"),+ displayName: "contoso/payments%20(eu)/_git/checkout%20(eu)",+ owner: "contoso",+ name: "checkout%20(eu)",+ }),+ ).toBe("checkout (eu)");+ });+});diff --git a/packages/source-control-azure-devops/src/client/definition.ts b/packages/source-control-azure-devops/src/client/definition.tsindex ac83fb8fc3a..e0753bc82f0 100644--- a/packages/source-control-azure-devops/src/client/definition.ts+++ b/packages/source-control-azure-devops/src/client/definition.ts@@ -1,5 +1,4 @@import { SourceControlProviderKind } from "@t3tools/contracts";-import { canonicalRepositoryKey } from "@t3tools/shared/sourceControl";import {changeRequestUrlBelow,defineSourceControlClient,@@ -14,6 +13,44 @@ const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;const CHANGE_REQUEST_REFERENCE =/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;+/**+ * Azure alone addresses one repository under two names that share no part: `ssh.dev.azure.com` and+ * `v3/{org}/{project}/{repo}` over SSH, against `dev.azure.com` and `{org}/{project}/_git/{repo}`+ * everywhere a person sees it. A project cloned over SSH would otherwise be a different repository+ * to every comparison made against a pull request URL, which arrives in the web spelling.+ */+function repositoryKeyFromRemote(key: string): string | null {+ const match =+ /^(ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u.exec(key);+ if (match === null) return null;+ const [, host, organization, project, repository] = match;+ return host === "ssh.dev.azure.com"+ ? `dev.azure.com/${organization}/${project}/_git/${repository}`+ : `${organization}.visualstudio.com/${project}/_git/${repository}`;+}++/** Every spelling of an Azure DevOps Services repository, on `dev.azure.com`. */+function canonicalRepositoryKey(key: string): string | null {+ const canonical = key+ .replace(+ /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,+ "dev.azure.com/$1/$2/_git/$3",+ )+ .replace(+ /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,+ "dev.azure.com/$1/$2/_git/$3",+ );+ return canonical.startsWith("dev.azure.com/") ? canonical : null;+}++function decodeUrlPathSegment(segment: string): string {+ try {+ return decodeURIComponent(segment);+ } catch {+ return segment;+ }+}+function checkoutCommandId(args: string): string | null {const parts = args.trim().split(/\s+/).filter(Boolean);for (const [index, part] of parts.entries()) {@@ -23,8 +60,10 @@ function checkoutCommandId(args: string): string | null {return parts.find((part) => !part.startsWith("-")) ?? null;}+const KIND = SourceControlProviderKind.make("azure-devops");+export const definition = defineSourceControlClient({- kind: SourceControlProviderKind.make("azure-devops"),+ kind: KIND,label: "Azure DevOps",pickerLabel: "Azure DevOps",icon: "azure-devops",@@ -39,9 +78,8 @@ export const definition = defineSourceControlClient({defaultCloneTransport: "ssh",changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) => {if (webUrl) return changeRequestUrlBelow(webUrl, `pullrequest/${number}`);- const [canonicalHost = host, ...path] = canonicalRepositoryKey(- `${host}/${repository}`.toLowerCase(),- ).split("/");+ const key = `${host}/${repository}`.toLowerCase();+ const [canonicalHost = host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/");return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`;},// Servers on different ports are different servers, so a port stays in the link.@@ -69,9 +107,37 @@ export const definition = defineSourceControlClient({},isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),checkoutChangeRequestHost: () => null,- isChangeRequestInRepository: (identity, link) =>- isChangeRequestAuthorityOfProject(identity, link) &&- canonicalRepositoryKey(identity.canonicalKey.toLowerCase()) ===- canonicalRepositoryKey(`${link.host}/${link.repository}`.toLowerCase()),+ // `ssh.dev.azure.com` is the default SSH clone host ([email protected]:v3/org/project/repo),+ // so any `*.dev.azure.com` subdomain is Azure. Legacy hosts stay under `.visualstudio.com`,+ // including `vs-ssh.visualstudio.com`.+ recognizeRemote: ({ host, hostname }) =>+ hostname === "dev.azure.com" ||+ hostname.endsWith(".dev.azure.com") ||+ hostname.endsWith(".visualstudio.com")+ ? { kind: KIND, name: "Azure DevOps", baseUrl: `https://${host}` }+ : null,+ /**+ * `az repos pr list --repository` takes a repository name, and takes the organisation and+ * project from the checkout it detects, so the recorded `org/project/_git/repo` path is refused+ * outright and the whole repository reads as unavailable. The segment comes from the remote URL,+ * where a name with a space reads `my%20repo`; `az` looks that up literally and answers 404, so+ * it goes out decoded.+ */+ repositorySelector: (identity) => {+ const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");+ const name = identity.name || segments.at(-1);+ return name ? decodeUrlPathSegment(name) : null;+ },+ repositoryKeyFromRemote,+ canonicalRepositoryKey,+ isChangeRequestInRepository: (identity, link) => {+ if (!isChangeRequestAuthorityOfProject(identity, link)) return false;+ const projectKey = identity.canonicalKey.toLowerCase();+ const linkKey = `${link.host}/${link.repository}`.toLowerCase();+ return (+ (canonicalRepositoryKey(projectKey) ?? projectKey) ===+ (canonicalRepositoryKey(linkKey) ?? linkKey)+ );+ },canReadChangeRequestOnHost: () => false,});diff --git a/packages/source-control-bitbucket/src/client/definition.test.ts b/packages/source-control-bitbucket/src/client/definition.test.tsindex 5c53884c337..c28e0dfbac3 100644--- a/packages/source-control-bitbucket/src/client/definition.test.ts+++ b/packages/source-control-bitbucket/src/client/definition.test.ts@@ -1,3 +1,4 @@+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";import { describe, expect, it } from "vite-plus/test";import { definition } from "./definition.ts";@@ -36,3 +37,19 @@ describe("Bitbucket change request URLs", () => {).toBe("https://bitbucket.org/w/repo/pull-requests/5");});});++describe("Bitbucket remotes", () => {+ const recognize = (url: string) => recognizeRemoteWith(definition, url);++ it("recognises bitbucket.org and hosts with a bitbucket label", () => {+ expect(recognize("[email protected]:workspace/repo.git")).toEqual({+ kind: "bitbucket",+ name: "Bitbucket",+ baseUrl: "https://bitbucket.org",+ });+ expect(recognize("https://bitbucket.example.com/workspace/repo.git")?.name).toBe(+ "Bitbucket Self-Hosted",+ );+ expect(recognize("https://notbitbucket.example.com/workspace/repo.git")).toBeNull();+ });+});diff --git a/packages/source-control-bitbucket/src/client/definition.ts b/packages/source-control-bitbucket/src/client/definition.tsindex 2d423fbb227..3ad2e97aefd 100644--- a/packages/source-control-bitbucket/src/client/definition.ts+++ b/packages/source-control-bitbucket/src/client/definition.ts@@ -11,6 +11,7 @@ import {isChangeRequestInProjectRepository,isChangeRequestOnProjectHost,parseChangeRequestPath,+ projectChangeRequestHost,} from "@t3tools/source-control-core/client/definition";const safeShellArgument = /^[A-Za-z0-9._/@+=,-]+$/;@@ -97,9 +98,17 @@ export const definition = defineSourceControlClient({checkoutCommandArgument: () => null,isChangeRequestReference: () => false,checkoutChangeRequestHost: () => null,+ recognizeRemote: ({ host, hostname }) =>+ hostname === "bitbucket.org" || hostname.split(".").includes("bitbucket")+ ? {+ kind: KIND,+ name: hostname === "bitbucket.org" ? "Bitbucket" : "Bitbucket Self-Hosted",+ baseUrl: `https://${host}`,+ }+ : null,isChangeRequestInRepository: (identity, link) =>- isChangeRequestInProjectRepository(KIND, identity, link),+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),canReadChangeRequestOnHost: (identity, link) =>- isChangeRequestOnProjectHost(KIND, identity, link),+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),settings,});diff --git a/packages/source-control-bitbucket/src/server/BitbucketApi.ts b/packages/source-control-bitbucket/src/server/BitbucketApi.tsindex 2da9b4630b4..07c7064b449 100644--- a/packages/source-control-bitbucket/src/server/BitbucketApi.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketApi.ts@@ -17,10 +17,9 @@ import {} from "@t3tools/contracts";import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";import { sanitizeBranchFragment } from "@t3tools/shared/git";-import {- detectSourceControlProviderFromRemoteUrl,- isSshRemoteUrl,-} from "@t3tools/shared/sourceControl";+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";+import { definition } from "../client/definition.ts";import {BitbucketPullRequestListSchema,@@ -791,7 +790,7 @@ export const make = Effect.gen(function* () {);for (const remote of remotes.remotes) {- if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;+ if (recognizeRemoteWith(definition, remote.url) === null) continue;const parsed = parseBitbucketRemoteUrl(remote.url);if (parsed) return parsed;}diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.tsindex 619b138ded5..ac7b947f171 100644--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts@@ -147,6 +147,7 @@ export const make = Effect.gen(function* () {const provider: PullRequestProviderApi = {kind: SourceControlProviderKind.make("bitbucket"),capabilities: CAPABILITIES,+ readsPublicHostWithoutCheckout: true,getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),diff --git a/packages/source-control-core/src/client/definition.ts b/packages/source-control-core/src/client/definition.tsindex 69a4fa40262..9a13dd20a4e 100644--- a/packages/source-control-core/src/client/definition.ts+++ b/packages/source-control-core/src/client/definition.ts@@ -1,14 +1,15 @@import {type PullRequestAction,- pullRequestHostOf,type PullRequestReviewVerdict,type RepositoryIdentity,SourceControlProviderKind,+ type SourceControlProviderInfo,} from "@t3tools/contracts";+import { normalizeGitRemoteUrl, parseGitRemoteRepository } from "@t3tools/shared/git";import * as Schema from "effect/Schema";/**- * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce+ * The two strings are what `changeRequestHost` and the project's `repositoryIdentity` produce* from a git remote — lower case, no port, the full path below the host — because links are* matched against those. `authority` keeps the port for hosts whose identity includes it.*/@@ -43,6 +44,29 @@ export type ChangeRequestProjectIdentity = Pick<"canonicalKey" | "locator" | "webUrl" | "displayName" | "owner" | "name">;+export type ChangeRequestHostIdentity =+ | {+ readonly canonicalKey?: string | undefined;+ readonly locator?: { readonly remoteUrl: string } | undefined;+ }+ | null+ | undefined;++export type RepositorySelectorIdentity = Pick<+ RepositoryIdentity,+ "provider" | "displayName" | "owner" | "name"+>;++/** A git remote's host, as `recognizeRemote` reads it. */+export interface GitRemoteHost {+ /** Trimmed. */+ readonly remoteUrl: string;+ /** Lower case. Keeps the port of an HTTP remote, never an SSH one. */+ readonly host: string;+ /** `host` without its port. */+ readonly hostname: string;+}+export interface ChangeRequestCheckoutInput {readonly number: number;readonly headBranch: string;@@ -91,6 +115,32 @@ export interface SourceControlClientDefinition {link: ChangeRequestLink,) => boolean;readonly checkoutChangeRequestHost: (identity: ChangeRequestProjectIdentity) => string | null;+ /** Null when this host does not claim the remote. Asked in the registry's recognition order. */+ readonly recognizeRemote: (remote: GitRemoteHost) => SourceControlProviderInfo | null;+ /** The host change requests in the project are listed and keyed under. */+ readonly changeRequestHost?: (identity: ChangeRequestHostIdentity) => string;+ /**+ * What the host's tools take to select the project's repository. Absent means the repository+ * path, `owner/name`.+ */+ readonly repositorySelector?: (identity: RepositorySelectorIdentity) => string | null;+ /**+ * For a host that spells one repository differently over SSH and on the web: the web spelling+ * of the `host/path` key `normalizeGitRemoteUrl` made from a remote that names a host. Null when+ * the key is not this host's. Persisted repository keys are built with it, so its output must+ * not change.+ */+ readonly repositoryKeyFromRemote?: (key: string) => string | null;+ /**+ * For a host with more than one spelling of a repository key: the one every spelling compares+ * equal under. Null when the key is not this host's.+ */+ readonly canonicalRepositoryKey?: (key: string) => string | null;+ /**+ * An SSH remote names the SSH server only, so the web host, and its port, come from resolving+ * the provider rather than from the remote.+ */+ readonly sshRemoteHidesWebHost?: boolean;readonly settings?: SourceControlHostSettingsSchema;}@@ -160,14 +210,23 @@ export function isChangeRequestAuthorityOfProject(return true;}+/** The host of the project's repository key, or `kind` when the key has none. */+export function projectChangeRequestHost<const Kind extends string | undefined>(+ identity: ChangeRequestHostIdentity,+ kind: Kind,+): string | Kind {+ const host = identity?.canonicalKey?.split("/")[0]?.trim();+ return host === undefined || host.length === 0 ? kind : host.toLowerCase();+}++/** `projectHost` is the project's `changeRequestHost`. */export function isChangeRequestOnProjectHost(- kind: SourceControlProviderKind,+ projectHost: string,identity: ChangeRequestProjectIdentity,link: ChangeRequestLink,): boolean {if (!isChangeRequestAuthorityOfProject(identity, link)) return false;- const host = pullRequestHostOf(identity, kind);- return host === link.host.toLowerCase() || host === link.authority;+ return projectHost === link.host.toLowerCase() || projectHost === link.authority;}function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string | null {@@ -178,7 +237,7 @@ function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string |}export function isChangeRequestInProjectRepository(- kind: SourceControlProviderKind,+ projectHost: string,identity: ChangeRequestProjectIdentity,link: ChangeRequestLink,): boolean {@@ -186,10 +245,64 @@ export function isChangeRequestInProjectRepository(return (repository !== null &&repository.toLowerCase() === link.repository.toLowerCase() &&- isChangeRequestOnProjectHost(kind, identity, link)+ isChangeRequestOnProjectHost(projectHost, identity, link));}+const SCP_REMOTE = /^[a-zA-Z0-9._-]+@([^:/]+):/;++/** Null when the remote names no host, such as a local path. */+export function parseGitRemoteHost(remoteUrl: string): GitRemoteHost | null {+ const trimmed = remoteUrl.trim();+ if (trimmed.length === 0) return null;+ let host: string;+ const scpHost = SCP_REMOTE.exec(trimmed)?.[1];+ if (scpHost) {+ host = scpHost.toLowerCase();+ } else {+ try {+ const url = new URL(trimmed);+ host = (url.protocol === "ssh:" ? url.hostname : url.host).toLowerCase();+ } catch {+ return null;+ }+ }+ if (host.length === 0) return null;+ let hostname: string;+ try {+ hostname = new URL(`https://${host}`).hostname.toLowerCase();+ } catch {+ hostname = host.replace(/:\d+$/u, "").toLowerCase();+ }+ return { remoteUrl: trimmed, host, hostname };+}++/** What a remote on a host no definition claims reads as. */+export function unknownRemoteProvider(remote: GitRemoteHost): SourceControlProviderInfo {+ return {+ kind: SourceControlProviderKind.make("unknown"),+ name: remote.host,+ baseUrl: `https://${remote.host}`,+ };+}++/** What `definition` alone makes of a remote, for a host's own code that asks only about itself. */+export function recognizeRemoteWith(+ definition: Pick<SourceControlClientDefinition, "recognizeRemote">,+ remoteUrl: string,+): SourceControlProviderInfo | null {+ const remote = parseGitRemoteHost(remoteUrl);+ return remote === null ? null : definition.recognizeRemote(remote);+}++function defaultRepositorySelector(+ identity: RepositorySelectorIdentity | null | undefined,+): string | null {+ if (!identity) return null;+ if (identity.displayName) return identity.displayName;+ return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;+}+export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {kind: SourceControlProviderKind.make("unknown"),label: "source control",@@ -213,10 +326,15 @@ export const UNKNOWN_SOURCE_CONTROL_CLIENT: SourceControlClientDefinition = {checkoutCommandArgument: () => null,isChangeRequestReference: () => false,checkoutChangeRequestHost: () => null,+ recognizeRemote: () => null,isChangeRequestInRepository: (identity, link) =>- isChangeRequestInProjectRepository(SourceControlProviderKind.make("unknown"), identity, link),+ isChangeRequestInProjectRepository(+ projectChangeRequestHost(identity, "unknown"),+ identity,+ link,+ ),canReadChangeRequestOnHost: (identity, link) =>- isChangeRequestOnProjectHost(SourceControlProviderKind.make("unknown"), identity, link),+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, "unknown"), identity, link),};export interface ParsedChangeRequest {@@ -235,6 +353,23 @@ export interface SourceControlClientRegistry {readonly hostLabelForChangeRequestUrl: (url: string) => string;readonly isSameChangeRequest: (left: string, right: string) => boolean;readonly changeRequestUrlFromReferenceAutolink: (url: string) => string | null;+ /**+ * The host a remote is on, from the first definition in recognition order that claims it, or an+ * unknown host. Null when the remote names no host.+ */+ readonly recognizeRemote: (remoteUrl: string) => SourceControlProviderInfo | null;+ /** `normalizeGitRemoteUrl`, in the spelling the remote's host uses on the web. */+ readonly repositoryKeyFromRemote: (remoteUrl: string) => string;+ readonly canonicalRepositoryKey: (key: string) => string;+ /** The host that has more than one spelling of `key`, if any does. */+ readonly findByRepositoryKey: (key: string) => SourceControlClientDefinition | undefined;+ readonly repositorySelector: (+ identity: RepositorySelectorIdentity | null | undefined,+ ) => string | null;+ readonly changeRequestHost: <const Kind extends string | undefined>(+ identity: ChangeRequestHostIdentity,+ kind: Kind,+ ) => string | Kind;}function httpUrl(value: string): URL | null {@@ -246,15 +381,30 @@ function httpUrl(value: string): URL | null {}}+function inOrder(+ definitions: ReadonlyArray<SourceControlClientDefinition>,+ firstKinds: ReadonlyArray<SourceControlProviderKind> | undefined,+): ReadonlyArray<SourceControlClientDefinition> {+ const first = (firstKinds ?? []).flatMap(+ (kind) => definitions.find((definition) => definition.kind === kind) ?? [],+ );+ return [...first, ...definitions.filter((definition) => !first.includes(definition))];+}+/*** `definitions` is display order, and its first entry is what `get` returns for a repository* that has not reported its host yet. A change request URL goes to the first definition that* reads it, trying `claimChangeRequestUrlsFirst` before the rest, so a host that claims a route- * only on its own hostnames can precede one that claims the route everywhere.+ * only on its own hostnames can precede one that claims the route everywhere. A remote likewise+ * goes to the first that recognises it, in `recognizeRemotesIn` order and then the rest, because+ * one hostname can carry several hosts' labels.*/export function makeSourceControlClientRegistry(definitions: ReadonlyArray<SourceControlClientDefinition>,- options?: { readonly claimChangeRequestUrlsFirst?: ReadonlyArray<SourceControlProviderKind> },+ options?: {+ readonly claimChangeRequestUrlsFirst?: ReadonlyArray<SourceControlProviderKind>;+ readonly recognizeRemotesIn?: ReadonlyArray<SourceControlProviderKind>;+ },): SourceControlClientRegistry {const byKind = new Map<string, SourceControlClientDefinition>();for (const definition of definitions) {@@ -263,11 +413,15 @@ export function makeSourceControlClientRegistry(}byKind.set(definition.kind, definition);}- const first = new Set(options?.claimChangeRequestUrlsFirst);- const claimOrder = [- ...definitions.filter((definition) => first.has(definition.kind)),- ...definitions.filter((definition) => !first.has(definition.kind)),- ];+ const claimOrder = inOrder(definitions, options?.claimChangeRequestUrlsFirst);+ const recognitionOrder = inOrder(definitions, options?.recognizeRemotesIn);+ const repositoryKeyOwner = (key: string) => {+ for (const definition of definitions) {+ const canonical = definition.canonicalRepositoryKey?.(key);+ if (canonical != null) return { definition, canonical };+ }+ return undefined;+ };const parseChangeRequestUrl = (value: string): ParsedChangeRequest | null => {const url = httpUrl(value);if (url === null) return null;@@ -311,6 +465,35 @@ export function makeSourceControlClientRegistry(}return null;},+ recognizeRemote: (remoteUrl) => {+ const remote = parseGitRemoteHost(remoteUrl);+ if (remote === null) return null;+ for (const definition of recognitionOrder) {+ const provider = definition.recognizeRemote(remote);+ if (provider !== null) return provider;+ }+ return unknownRemoteProvider(remote);+ },+ repositoryKeyFromRemote: (remoteUrl) => {+ const key = normalizeGitRemoteUrl(remoteUrl);+ if (parseGitRemoteRepository(remoteUrl) === null) return key;+ for (const definition of definitions) {+ const spelled = definition.repositoryKeyFromRemote?.(key);+ if (spelled != null) return spelled;+ }+ return key;+ },+ canonicalRepositoryKey: (key) => repositoryKeyOwner(key)?.canonical ?? key,+ findByRepositoryKey: (key) => repositoryKeyOwner(key)?.definition,+ repositorySelector: (identity) =>+ identity?.provider === undefined+ ? defaultRepositorySelector(identity)+ : (byKind.get(identity.provider)?.repositorySelector ?? defaultRepositorySelector)(+ identity,+ ),+ changeRequestHost: (identity, kind) =>+ (kind === undefined ? undefined : byKind.get(kind)?.changeRequestHost?.(identity)) ??+ projectChangeRequestHost(identity, kind),};}diff --git a/packages/source-control-core/src/client/threadPullRequests.ts b/packages/source-control-core/src/client/threadPullRequests.tsindex a16fbae8572..3655f74e608 100644--- a/packages/source-control-core/src/client/threadPullRequests.ts+++ b/packages/source-control-core/src/client/threadPullRequests.ts@@ -4,7 +4,6 @@ import type {ThreadPullRequestKey,ThreadPullRequestLink,} from "@t3tools/contracts";-import { canonicalRepositoryKey } from "@t3tools/shared/sourceControl";import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";import type { SourceControlClientRegistry } from "./definition.ts";@@ -63,7 +62,10 @@ export type ThreadPullRequestBadge = {* binds these once to its own registry.*/export function makeThreadPullRequests(- registry: Pick<SourceControlClientRegistry, "parseChangeRequestUrl">,+ registry: Pick<+ SourceControlClientRegistry,+ "parseChangeRequestUrl" | "canonicalRepositoryKey" | "findByRepositoryKey"+ >,) {const parse = (url: string) => registry.parseChangeRequestUrl(url)?.link ?? null;@@ -74,7 +76,7 @@ export function makeThreadPullRequests((parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number? parsed.authority: undefined);- const canonical = canonicalRepositoryKey(+ const canonical = registry.canonicalRepositoryKey(`${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,);const separator = canonical.indexOf("/");@@ -91,8 +93,10 @@ export function makeThreadPullRequests(): ThreadPullRequestKey {const parsed = parse(linked.url);if (parsed !== null && parsed.number === linked.number) {- const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);- if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {+ if (+ parsed.authority !== undefined ||+ registry.findByRepositoryKey(`${parsed.host}/${parsed.repository}`) !== undefined+ ) {return normalizeThreadPullRequestKey(parsed);}}diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.tsindex 32a06d2b314..18fb90a3b3b 100644--- a/packages/source-control-core/src/server/PullRequestProvider.ts+++ b/packages/source-control-core/src/server/PullRequestProvider.ts@@ -296,6 +296,11 @@ export interface PullRequestProviderApi {* organization from the checkout, so only a checkout whose key matches the reference serves it.*/readonly repositoryKey?: (input: { readonly canonicalKey: string }) => string;+ /**+ * Names the repository in every request and authenticates by host, so a change request on the+ * definition's `publicHost` can be read from a project with no checkout of its repository.+ */+ readonly readsPublicHostWithoutCheckout?: boolean;readonly getViewer: (input: {readonly cwd: string;diff --git a/packages/source-control-forgejo/src/client/definition.test.ts b/packages/source-control-forgejo/src/client/definition.test.tsindex 74d4cddbcd4..f2d31320212 100644--- a/packages/source-control-forgejo/src/client/definition.test.ts+++ b/packages/source-control-forgejo/src/client/definition.test.ts@@ -1,4 +1,5 @@import type { ChangeRequestProjectIdentity } from "@t3tools/source-control-core/client/definition";+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";import { describe, expect, it } from "vite-plus/test";import { definition } from "./definition.ts";@@ -102,3 +103,29 @@ describe("Forgejo change request URLs", () => {}});});++describe("Forgejo remotes", () => {+ it("recognises Codeberg and Forgejo or Gitea hosts, keeping an HTTP remote's origin", () => {+ for (const host of ["codeberg.org", "forgejo.example.test", "gitea.example.test"]) {+ expect(recognizeRemoteWith(definition, `http://${host}:3000/team/repo.git`)).toEqual({+ kind: "forgejo",+ name: "Forgejo",+ baseUrl: `http://${host}:3000`,+ });+ }+ expect(+ recognizeRemoteWith(definition, "ssh://[email protected]:2222/team/repo.git")?.baseUrl,+ ).toBe("https://forgejo.example.test");+ expect(recognizeRemoteWith(definition, "https://git.example.test/team/repo")).toBeNull();+ });+});++describe("Forgejo change request host", () => {+ it("keeps an HTTP remote's port, because a server's identity includes it", () => {+ const project = identity("http://forge.example:3000/git/team/repo.git");+ expect(definition.changeRequestHost?.(project)).toBe("forge.example:3000");+ expect(+ definition.changeRequestHost?.(identity("ssh://[email protected]:2222/git/team/repo.git")),+ ).toBe("forge.example");+ });+});diff --git a/packages/source-control-forgejo/src/client/definition.ts b/packages/source-control-forgejo/src/client/definition.tsindex 9f8c2aa3573..1411a42c1e2 100644--- a/packages/source-control-forgejo/src/client/definition.ts+++ b/packages/source-control-forgejo/src/client/definition.ts@@ -1,12 +1,14 @@import { SourceControlProviderKind } from "@t3tools/contracts";import {changeRequestUrlBelow,+ type ChangeRequestHostIdentity,type ChangeRequestProjectIdentity,defineSourceControlClient,isChangeRequestAuthorityOfProject,isChangeRequestInProjectRepository,isChangeRequestOnProjectHost,parseChangeRequestPath,+ projectChangeRequestHost,remoteWebOrigin,} from "@t3tools/source-control-core/client/definition";@@ -33,6 +35,19 @@ function resolvedWebUrl(identity: ChangeRequestProjectIdentity): URL | null {}}+/** A server's identity includes its port, which only an HTTP remote names. */+function changeRequestHost(identity: ChangeRequestHostIdentity): string {+ try {+ const remote = new URL(identity?.locator?.remoteUrl ?? "");+ if (remote.protocol === "http:" || remote.protocol === "https:") {+ return remote.host.toLowerCase();+ }+ } catch {+ // SSH remotes do not name the web server.+ }+ return projectChangeRequestHost(identity, KIND);+}+export const definition = defineSourceControlClient({kind: KIND,label: "Forgejo",@@ -40,8 +55,8 @@ export const definition = defineSourceControlClient({icon: "forgejo",changeRequest: { shortLabel: "PR", singular: "pull request" },repositoryPathHint: "owner/repo",- // Forgejo and Gitea are self-hosted, so no hostname names them.- publicHost: null,+ // Codeberg is the public Forgejo; any other server is self-hosted.+ publicHost: "codeberg.org",publishDescription: "Your signed-in server",publishHost: (signedInHost) => signedInHost ?? "your server",newRepositoryOwner: (account) => (account ? { owner: account } : null),@@ -71,10 +86,23 @@ export const definition = defineSourceControlClient({checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),checkoutChangeRequestHost: () => null,+ recognizeRemote: ({ remoteUrl, host, hostname }) =>+ hostname === "codeberg.org" ||+ hostname.split(".").includes("forgejo") ||+ hostname.split(".").includes("gitea")+ ? {+ kind: KIND,+ name: "Forgejo",+ baseUrl: /^https?:/iu.test(remoteUrl) ? new URL(remoteUrl).origin : `https://${host}`,+ }+ : null,+ changeRequestHost,+ sshRemoteHidesWebHost: true,isChangeRequestInRepository: (identity, link) => {if (!isChangeRequestAuthorityOfProject(identity, link)) return false;const web = resolvedWebUrl(identity);- if (!web) return isChangeRequestInProjectRepository(KIND, identity, link);+ if (!web)+ return isChangeRequestInProjectRepository(changeRequestHost(identity), identity, link);return (web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&web.pathname.replace(/^\/+|\/+$/g, "").toLowerCase() === link.repository.toLowerCase()@@ -83,7 +111,7 @@ export const definition = defineSourceControlClient({// A server mounted below a path serves only repositories under that mount.canReadChangeRequestOnHost: (identity, link) => {const web = resolvedWebUrl(identity);- if (!web) return isChangeRequestOnProjectHost(KIND, identity, link);+ if (!web) return isChangeRequestOnProjectHost(changeRequestHost(identity), identity, link);const mount = web.pathname.replace(/^\/+|\/+$/g, "").split("/")diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.tsindex b7616c276c3..2ba5b43a4dd 100644--- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts+++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts@@ -259,6 +259,7 @@ export const make = Effect.gen(function* () {const provider: PullRequestProviderApi = {kind: SourceControlProviderKind.make("forgejo"),capabilities: CAPABILITIES,+ readsPublicHostWithoutCheckout: true,getViewer,listChangeRequests: Effect.fn("ForgejoPullRequestProvider.listChangeRequests")(function* (input) {diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.tsindex c3e8146f5f0..5b4d92418e0 100644--- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts+++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts@@ -597,7 +597,7 @@ it.effect("gives Forgejo identities the browser URL of the login that serves thecanonicalKey: "forge.test/team/repo",locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },rootPath: "/repo",- ...(provider === undefined ? {} : { provider }),+ ...(provider === undefined ? {} : { provider: SourceControlProviderKind.make(provider) }),});const served = (baseUrl: string) => () =>Effect.succeed({diff --git a/packages/source-control-gitcafe/src/client/definition.test.ts b/packages/source-control-gitcafe/src/client/definition.test.tsindex 4bc0c017aaa..9c491417150 100644--- a/packages/source-control-gitcafe/src/client/definition.test.ts+++ b/packages/source-control-gitcafe/src/client/definition.test.ts@@ -1,3 +1,4 @@+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";import { describe, expect, it } from "vite-plus/test";import { definition } from "./definition.ts";@@ -47,3 +48,17 @@ describe("GitCafe change request URLs", () => {).toBe("https://git.cafe/Team/Repo/pulls/8");});});++describe("GitCafe remotes", () => {+ it("recognises its own hosts only, without a port", () => {+ expect(recognizeRemoteWith(definition, "https://git.cafe:8443/a/b")).toEqual({+ kind: "gitcafe",+ name: "GitCafe",+ baseUrl: "https://git.cafe",+ });+ expect(recognizeRemoteWith(definition, "[email protected]:team/repo.git")?.kind).toBe(+ "gitcafe",+ );+ expect(recognizeRemoteWith(definition, "https://cafe.example/a/b")).toBeNull();+ });+});diff --git a/packages/source-control-gitcafe/src/client/definition.ts b/packages/source-control-gitcafe/src/client/definition.tsindex ac7736d541b..f0ea69bdbd2 100644--- a/packages/source-control-gitcafe/src/client/definition.ts+++ b/packages/source-control-gitcafe/src/client/definition.ts@@ -12,6 +12,7 @@ import {isChangeRequestInProjectRepository,isChangeRequestOnProjectHost,parseChangeRequestPath,+ projectChangeRequestHost,} from "@t3tools/source-control-core/client/definition";/** GitCafe has no self-hosted installs: production and staging are its only hosts. */@@ -74,9 +75,13 @@ export const definition = defineSourceControlClient({checkoutCommandArgument: () => null,isChangeRequestReference: () => false,checkoutChangeRequestHost: () => null,+ recognizeRemote: ({ hostname }) =>+ GITCAFE_HOSTS.has(hostname)+ ? { kind: KIND, name: "GitCafe", baseUrl: `https://${hostname}` }+ : null,isChangeRequestInRepository: (identity, link) =>- isChangeRequestInProjectRepository(KIND, identity, link),+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),canReadChangeRequestOnHost: (identity, link) =>- isChangeRequestOnProjectHost(KIND, identity, link),+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),settings,});diff --git a/packages/source-control-github/src/client/definition.test.ts b/packages/source-control-github/src/client/definition.test.tsindex 5e2153bbb05..c929be7167a 100644--- a/packages/source-control-github/src/client/definition.test.ts+++ b/packages/source-control-github/src/client/definition.test.ts@@ -1,3 +1,4 @@+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";import { describe, expect, it } from "vite-plus/test";import { definition } from "./definition.ts";@@ -94,3 +95,29 @@ describe("GitHub change request URLs", () => {expect(candidate("https://code.example.test/acme/web/issues/42")).toBeNull();});});++describe("GitHub remotes", () => {+ const recognize = (url: string) => recognizeRemoteWith(definition, url);++ it("recognises github.com, ghe.com subdomains and hosts with a github label", () => {+ expect(recognize("[email protected]:owner/repo.git")).toEqual({+ kind: "github",+ name: "GitHub",+ baseUrl: "https://github.com",+ });+ expect(recognize("https://acme.ghe.com/owner/repo.git")).toEqual({+ kind: "github",+ name: "GitHub Self-Hosted",+ baseUrl: "https://acme.ghe.com",+ });+ expect(recognize("[email protected]:owner/repo.git")?.kind).toBe("github");+ expect(recognize("https://github.example.com:8443/owner/repo.git")?.baseUrl).toBe(+ "https://github.example.com:8443",+ );+ });++ it("does not claim ghe.com itself or a label that only contains github", () => {+ expect(recognize("https://ghe.com/owner/repo.git")).toBeNull();+ expect(recognize("https://notgithub.example.com/owner/repo.git")).toBeNull();+ });+});diff --git a/packages/source-control-github/src/client/definition.ts b/packages/source-control-github/src/client/definition.tsindex f9db4b87a3a..c022ed824b4 100644--- a/packages/source-control-github/src/client/definition.ts+++ b/packages/source-control-github/src/client/definition.ts@@ -2,7 +2,6 @@ import {GitHubHost,makeProviderSettingsSchema,secretSetting,- pullRequestHostOf,SourceControlProviderKind,TrimmedNonEmptyString,TrimmedString,@@ -15,6 +14,7 @@ import {isChangeRequestInProjectRepository,isChangeRequestOnProjectHost,parseChangeRequestPath,+ projectChangeRequestHost,remoteWebOrigin,} from "@t3tools/source-control-core/client/definition";@@ -118,10 +118,21 @@ export const definition = defineSourceControlClient({reviewSummaryRequired: () => false,checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),- checkoutChangeRequestHost: (identity) => pullRequestHostOf(identity, KIND),+ checkoutChangeRequestHost: (identity) => projectChangeRequestHost(identity, KIND),+ // `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise.+ recognizeRemote: ({ host, hostname }) =>+ hostname === "github.com" ||+ hostname.endsWith(".ghe.com") ||+ hostname.split(".").includes("github")+ ? {+ kind: KIND,+ name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",+ baseUrl: `https://${host}`,+ }+ : null,isChangeRequestInRepository: (identity, link) =>- isChangeRequestInProjectRepository(KIND, identity, link),+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),canReadChangeRequestOnHost: (identity, link) =>- isChangeRequestOnProjectHost(KIND, identity, link),+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),settings,});diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.tsindex ab770dac4e0..f57bf3ee224 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts@@ -243,6 +243,7 @@ export const make = Effect.gen(function* () {const provider: PullRequestProviderApi = {kind: SourceControlProviderKind.make("github"),capabilities: CAPABILITIES,+ readsPublicHostWithoutCheckout: true,mergeMessageRewrite: removeAgentCredits,getRoutingIdentity: (input) =>cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),diff --git a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts b/packages/source-control-github/src/server/gitHubRepositoryResolution.tsindex d9e2e9743e1..ddf57a42c33 100644--- a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts+++ b/packages/source-control-github/src/server/gitHubRepositoryResolution.ts@@ -1,8 +1,7 @@import { normalizeGitRemoteUrl } from "@t3tools/shared/git";-import {- detectSourceControlProviderFromRemoteUrl,- isSshRemoteUrl,-} from "@t3tools/shared/sourceControl";+import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";+import { parseGitRemoteHost } from "@t3tools/source-control-core/client/definition";+import { definition } from "../client/definition.ts";export interface GitHubRepositoryLocator {readonly host: string;@@ -163,13 +162,13 @@ export function parsePullRequestReference(* #6198).*/export function gitHubApiHostForRemote(remoteUrl: string): string | null {- const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);- if (provider === null) return null;- const host = new URL(provider.baseUrl).host.toLowerCase();+ const remote = parseGitRemoteHost(remoteUrl);+ if (remote === null) return null;+ const host = new URL(`https://${remote.host}`).host.toLowerCase();if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {return host.includes("github") ? "github.com" : null;}- return provider.kind === "github" ? host : null;+ return definition.recognizeRemote(remote) === null ? null : host;}function apiHostForHint(host: string): string {diff --git a/packages/source-control-gitlab/src/client/definition.test.ts b/packages/source-control-gitlab/src/client/definition.test.tsindex 4184084e386..02514ee373d 100644--- a/packages/source-control-gitlab/src/client/definition.test.ts+++ b/packages/source-control-gitlab/src/client/definition.test.ts@@ -1,3 +1,4 @@+import { recognizeRemoteWith } from "@t3tools/source-control-core/client/definition";import { describe, expect, it } from "vite-plus/test";import { definition } from "./definition.ts";@@ -48,3 +49,27 @@ describe("GitLab change request URLs", () => {).toBe("https://gitlab.com/group/sub/project/-/merge_requests/4");});});++describe("GitLab remotes", () => {+ const recognize = (url: string) => recognizeRemoteWith(definition, url);++ it("keeps an HTTP port in the base URL and drops an SSH one", () => {+ expect(recognize("https://gitlab.com:8443/group/repo.git")).toEqual({+ kind: "gitlab",+ name: "GitLab",+ baseUrl: "https://gitlab.com:8443",+ });+ expect(recognize("ssh://[email protected]:24/group/repo.git")).toEqual({+ kind: "gitlab",+ name: "GitLab Self-Hosted",+ baseUrl: "https://gitlab.example.test",+ });+ expect(recognize("[email protected]:group/project.git")?.baseUrl).toBe(+ "https://gitlab.example.com",+ );+ });++ it("matches complete DNS labels only", () => {+ expect(recognize("https://notgitlab.example.com/group/repo.git")).toBeNull();+ });+});diff --git a/packages/source-control-gitlab/src/client/definition.ts b/packages/source-control-gitlab/src/client/definition.tsindex a3f4a153a1a..e944270a94e 100644--- a/packages/source-control-gitlab/src/client/definition.ts+++ b/packages/source-control-gitlab/src/client/definition.ts@@ -5,6 +5,7 @@ import {isChangeRequestInProjectRepository,isChangeRequestOnProjectHost,parseChangeRequestPath,+ projectChangeRequestHost,} from "@t3tools/source-control-core/client/definition";const CHECKOUT_COMMAND = /^glab\s+mr\s+checkout\s+(.+)$/i;@@ -51,8 +52,16 @@ export const definition = defineSourceControlClient({checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),checkoutChangeRequestHost: () => null,+ recognizeRemote: ({ host, hostname }) =>+ hostname === "gitlab.com" || hostname.split(".").includes("gitlab")+ ? {+ kind: KIND,+ name: hostname === "gitlab.com" ? "GitLab" : "GitLab Self-Hosted",+ baseUrl: `https://${host}`,+ }+ : null,isChangeRequestInRepository: (identity, link) =>- isChangeRequestInProjectRepository(KIND, identity, link),+ isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),canReadChangeRequestOnHost: (identity, link) =>- isChangeRequestOnProjectHost(KIND, identity, link),+ isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),});diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.tsindex 93defc897d7..2337b8b5fd7 100644--- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts+++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts@@ -1,8 +1,5 @@import { SourceControlProviderKind } from "@t3tools/contracts";-import {- detectSourceControlProviderFromGitRemoteUrl,- normalizeGitRemoteUrl,-} from "@t3tools/shared/git";+import { normalizeGitRemoteUrl } from "@t3tools/shared/git";import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";import { assert, it } from "@effect/vitest";@@ -128,7 +125,10 @@ it.effect.each([canonicalKey: normalizeGitRemoteUrl(remoteUrl),locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },rootPath: "/repo",- provider: detectSourceControlProviderFromGitRemoteUrl(remoteUrl)?.kind ?? "unknown",+ // Only a remote no host recognised is left for glab to refine.+ provider: SourceControlProviderKind.make(+ expectedProvider === "github" ? "github" : "unknown",+ ),};let authCalls = 0;const refined = yield* (@@ -177,7 +177,10 @@ it.effect.each(["https://code.example.test/team/repo/-/merge_requests/42",);}- assert.deepStrictEqual(refined, { ...identity, provider: expectedProvider });+ assert.deepStrictEqual(refined, {+ ...identity,+ provider: SourceControlProviderKind.make(expectedProvider),+ });if (expectedProvider === "github") assert.strictEqual(authCalls, 0);}),);diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.tsindex 38c404e6523..d8404c6dbb7 100644--- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts@@ -3,7 +3,10 @@ import * as Schema from "effect/Schema";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";-import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";+import {+ parseGitRemoteHost,+ unknownRemoteProvider as unknownHostProvider,+} from "@t3tools/source-control-core/client/definition";import * as GitLabCli from "./GitLabCli.ts";import * as GitLabChangeRequestTemplate from "./gitLabChangeRequestTemplate.ts";@@ -105,13 +108,12 @@ function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementIn} as const;}+/** The caller refines only an identity no host recognised, so its remote is on an unknown host. */function unknownRemoteProvider(remoteUrl: string) {- // The shared detector does not recognize userless SCP remotes.+ // Remote host parsing does not recognize userless SCP remotes.const scpHost = /^([^@:/\\\s]{2,}):\/?[^/\s]+(?:\/[^/\s]+)+$/u.exec(remoteUrl.trim())?.[1];- const provider = detectSourceControlProviderFromRemoteUrl(- scpHost ? `ssh://${scpHost}` : remoteUrl,- );- return provider?.kind === "unknown" ? provider : null;+ const remote = parseGitRemoteHost(scpHost ? `ssh://${scpHost}` : remoteUrl);+ return remote === null ? null : unknownHostProvider(remote);}// A glab login confirms a self-hosted GitLab whose hostname does not identify its provider.