Open History to see the last commit
1import type {
2 AdvertisedEndpoint,
3 AdvertisedEndpointHostedHttpsCompatibility,
4 AdvertisedEndpointProvider,
5 AdvertisedEndpointReachability,
6 AdvertisedEndpointSource,
7 AdvertisedEndpointStatus,
8} from "@t3tools/contracts";
9
10export interface CreateAdvertisedEndpointInput {
11 readonly id: string;
12 readonly label: string;
13 readonly provider: AdvertisedEndpointProvider;
14 readonly httpBaseUrl: string;
15 readonly reachability: AdvertisedEndpointReachability;
16 readonly hostedHttpsCompatibility?: AdvertisedEndpointHostedHttpsCompatibility;
17 readonly desktopCompatibility?: "compatible" | "unknown";
18 readonly source: AdvertisedEndpointSource;
19 readonly status?: AdvertisedEndpointStatus;
20 readonly isDefault?: boolean;
21 readonly description?: string;
22}
23
24export function normalizeHttpBaseUrl(rawValue: string): string {
25 const url = new URL(rawValue);
26 if (url.protocol === "ws:") {
27 url.protocol = "http:";
28 } else if (url.protocol === "wss:") {
29 url.protocol = "https:";
30 }
31
32 if (url.protocol !== "http:" && url.protocol !== "https:") {
33 throw new Error(`Endpoint must use HTTP or HTTPS. Received ${url.protocol}`);
34 }
35
36 url.pathname = "/";
37 url.search = "";
38 url.hash = "";
39 return url.toString();
40}
41
42export function deriveWsBaseUrl(httpBaseUrl: string): string {
43 const url = new URL(normalizeHttpBaseUrl(httpBaseUrl));
44 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
45 return url.toString();
46}
47
48export function classifyHostedHttpsCompatibility(
49 httpBaseUrl: string,
50 fallback: AdvertisedEndpointHostedHttpsCompatibility = "unknown",
51): AdvertisedEndpointHostedHttpsCompatibility {
52 const url = new URL(normalizeHttpBaseUrl(httpBaseUrl));
53 if (url.protocol === "http:") {
54 return "mixed-content-blocked";
55 }
56 return fallback === "mixed-content-blocked" ? "unknown" : fallback;
57}
58
59export function createAdvertisedEndpoint(input: CreateAdvertisedEndpointInput): AdvertisedEndpoint {
60 const httpBaseUrl = normalizeHttpBaseUrl(input.httpBaseUrl);
61 return {
62 id: input.id,
63 label: input.label,
64 provider: input.provider,
65 httpBaseUrl,
66 wsBaseUrl: deriveWsBaseUrl(httpBaseUrl),
67 reachability: input.reachability,
68 compatibility: {
69 hostedHttpsApp:
70 input.hostedHttpsCompatibility ?? classifyHostedHttpsCompatibility(httpBaseUrl),
71 desktopApp: input.desktopCompatibility ?? "compatible",
72 },
73 source: input.source,
74 status: input.status ?? "available",
75 ...(input.isDefault === undefined ? {} : { isDefault: input.isDefault }),
76 ...(input.description === undefined ? {} : { description: input.description }),
77 };
78}