import { SCHEME_PREFIX, tryHostForKnot } from "#lib/api/_request.ts";
// Special case for knot1.tangled.sh because we route it through our tangled.org URL to look cool. Otherwise all knot 3rd party knot URLs go through as-is.
// Don't forget that scheme/port are both allowed to be changed, technically speaking.
declare const tag: unique symbol;
type Branded<N extends string> = string & { readonly [tag]: N };
export type SshRemote = Branded<"SshRemote">;
const sshHostOf = (knot: string): Branded<"SshHost"> => {
const stripped = knot.replace(SCHEME_PREFIX, "");
const bare = (tryHostForKnot(stripped) ?? stripped).replace(/:[0-9]{1,5}$/, "");
return (bare.toLowerCase() === "knot1.tangled.sh" ? "tangled.org" : bare) as Branded<"SshHost">;
};
const sshUser = (viewerHandle: string | undefined): Branded<"SshUser"> =>
(viewerHandle && !viewerHandle.startsWith("did:") ? viewerHandle : "git") as Branded<"SshUser">;
export const sshRemote = (
knot: string,
viewerHandle: string | undefined,
path: string
): SshRemote => `${sshUser(viewerHandle)}@${sshHostOf(knot)}:${path}` as SshRemote;