Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

target.ts

317 lines9.5 KB

1import { PRIMARY_LOCAL_ENVIRONMENT_ID, type DesktopEnvironmentBootstrap } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3​
4import { isLocalEnvironmentDisabled } from "../../localEnvironment";
5​
6const PrimaryEnvironmentTargetSource = Schema.Literals([
7 "configured",
8 "window-origin",
9 "desktop-managed",
10]);
11type PrimaryEnvironmentTargetSource = typeof PrimaryEnvironmentTargetSource.Type;
12​
13const PrimaryEnvironmentUrlKind = Schema.Literals([
14 "http-base-url",
15 "websocket-base-url",
16 "development-server-url",
17 "window-location-url",
18]);
19type PrimaryEnvironmentUrlKind = typeof PrimaryEnvironmentUrlKind.Type;
20​
21export class PrimaryEnvironmentUrlInvalidError extends Schema.TaggedError<PrimaryEnvironmentUrlInvalidError>()(
22 "PrimaryEnvironmentUrlInvalidError",
23 {
24 source: PrimaryEnvironmentTargetSource,
25 urlKind: PrimaryEnvironmentUrlKind,
26 cause: Schema.Defect(),
27 },
28) {
29 override get message(): string {
30 return `Could not parse ${this.urlKind} for the ${this.source} primary environment target.`;
31 }
33​
34export class PrimaryEnvironmentProtocolUnsupportedError extends Schema.TaggedError<PrimaryEnvironmentProtocolUnsupportedError>()(
35 "PrimaryEnvironmentProtocolUnsupportedError",
36 {
37 source: PrimaryEnvironmentTargetSource,
38 protocol: Schema.String,
39 },
40) {
41 override get message(): string {
42 return `The ${this.source} primary environment target uses unsupported protocol ${this.protocol}.`;
43 }
45​
46export class DesktopEnvironmentBootstrapIncompleteError extends Schema.TaggedError<DesktopEnvironmentBootstrapIncompleteError>()(
47 "DesktopEnvironmentBootstrapIncompleteError",
48 {
49 hasHttpBaseUrl: Schema.Boolean,
50 hasWsBaseUrl: Schema.Boolean,
51 },
52) {
53 override get message(): string {
54 const missing = [
55 ...(this.hasHttpBaseUrl ? [] : ["httpBaseUrl"]),
56 ...(this.hasWsBaseUrl ? [] : ["wsBaseUrl"]),
57 ];
58 return `Desktop bootstrap is missing ${missing.join(" and ")} for the local environment.`;
59 }
61​
62export class PrimaryEnvironmentDisabledError extends Schema.TaggedError<PrimaryEnvironmentDisabledError>()(
63 "PrimaryEnvironmentDisabledError",
64 {},
65) {
66 override get message(): string {
67 return "The local environment is disabled.";
68 }
70​
71export const isPrimaryEnvironmentUrlInvalidError = Schema.is(PrimaryEnvironmentUrlInvalidError);
72export const isPrimaryEnvironmentProtocolUnsupportedError = Schema.is(
73 PrimaryEnvironmentProtocolUnsupportedError,
74);
75export const isDesktopEnvironmentBootstrapIncompleteError = Schema.is(
76 DesktopEnvironmentBootstrapIncompleteError,
77);
78​
79export interface PrimaryEnvironmentTarget {
80 readonly source: PrimaryEnvironmentTargetSource;
81 readonly target: {
82 readonly httpBaseUrl: string;
83 readonly wsBaseUrl: string;
84 };
86​
87const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
88​
89function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | null {
90 // The primary (Windows-native) backend keeps the "primary" id. The
91 // plural list may include a second WSL entry; the primary-target
92 // resolver only cares about the primary, so just find it.
93 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
94 return bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID) ?? null;
96​
97function parseTargetUrl(input: {
98 readonly rawValue: string;
99 readonly baseUrl?: string;
100 readonly source: PrimaryEnvironmentTargetSource;
101 readonly urlKind: PrimaryEnvironmentUrlKind;
102}): URL {
103 try {
104 return input.baseUrl === undefined
105 ? new URL(input.rawValue)
106 : new URL(input.rawValue, input.baseUrl);
107 } catch (cause) {
108 throw new PrimaryEnvironmentUrlInvalidError({
109 source: input.source,
110 urlKind: input.urlKind,
111 cause,
112 });
113 }
115​
116function normalizeBaseUrl(
117 rawValue: string,
118 source: PrimaryEnvironmentTargetSource,
119 urlKind: PrimaryEnvironmentUrlKind,
120): string {
121 return parseTargetUrl({
122 rawValue,
123 baseUrl: window.location.origin,
124 source,
125 urlKind,
126 }).toString();
128​
129function swapBaseUrlProtocol(
130 rawValue: string,
131 nextProtocol: "http:" | "https:" | "ws:" | "wss:",
132 urlKind: PrimaryEnvironmentUrlKind,
133): string {
134 const url = parseTargetUrl({
135 rawValue,
136 baseUrl: window.location.origin,
137 source: "configured",
138 urlKind,
139 });
140 url.protocol = nextProtocol;
141 return url.toString();
143​
144function normalizeHostname(hostname: string): string {
145 return hostname
146 .trim()
147 .toLowerCase()
148 .replace(/^\[(.*)\]$/, "$1");
150​
151export function isLoopbackHostname(hostname: string): boolean {
152 return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
154​
155function resolveHttpRequestBaseUrl(primaryTarget: PrimaryEnvironmentTarget): string {
156 const httpBaseUrl = primaryTarget.target.httpBaseUrl;
157 const configuredDevServerUrl = import.meta.env.VITE_DEV_SERVER_URL?.trim();
158 if (!configuredDevServerUrl) {
159 return httpBaseUrl;
160 }
161​
162 const currentUrl = parseTargetUrl({
163 rawValue: window.location.href,
164 source: "window-origin",
165 urlKind: "window-location-url",
166 });
167 const targetUrl = parseTargetUrl({
168 rawValue: httpBaseUrl,
169 source: primaryTarget.source,
170 urlKind: "http-base-url",
171 });
172 const devServerUrl = parseTargetUrl({
173 rawValue: configuredDevServerUrl,
174 baseUrl: currentUrl.origin,
175 source: "configured",
176 urlKind: "development-server-url",
177 });
178​
179 const isCurrentOriginDevServer =
180 (currentUrl.protocol === "http:" || currentUrl.protocol === "https:") &&
181 currentUrl.origin === devServerUrl.origin;
182​
183 if (
184 !isCurrentOriginDevServer ||
185 currentUrl.origin === targetUrl.origin ||
186 !isLoopbackHostname(currentUrl.hostname) ||
187 !isLoopbackHostname(targetUrl.hostname)
188 ) {
189 return httpBaseUrl;
190 }
191​
192 return currentUrl.origin;
194​
195function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
196 const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined;
197 const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined;
198​
199 if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
200 return null;
201 }
202​
203 // Scheme checks run on the raw configured string, while the URL parser
204 // folds schemes to lowercase ("WSS://host" parses fine). Without the
205 // case folding an uppercase scheme would be classified as plaintext and
206 // swapped to http/ws, silently downgrading TLS.
207 const resolvedHttpBaseUrl =
208 configuredHttpBaseUrl ??
209 (configuredWsBaseUrl?.toLowerCase().startsWith("wss:")
210 ? swapBaseUrlProtocol(configuredWsBaseUrl, "https:", "websocket-base-url")
211 : swapBaseUrlProtocol(configuredWsBaseUrl!, "http:", "websocket-base-url"));
212 const resolvedWsBaseUrl =
213 configuredWsBaseUrl ??
214 (configuredHttpBaseUrl?.toLowerCase().startsWith("https:")
215 ? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:", "http-base-url")
216 : swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:", "http-base-url"));
217​
218 return {
219 source: "configured",
220 target: {
221 httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl, "configured", "http-base-url"),
222 wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl, "configured", "websocket-base-url"),
223 },
224 };
226​
227function resolveWindowOriginPrimaryTarget(): PrimaryEnvironmentTarget {
228 const url = parseTargetUrl({
229 rawValue: window.location.origin,
230 source: "window-origin",
231 urlKind: "http-base-url",
232 });
233 const httpBaseUrl = url.toString();
234 if (url.protocol === "http:") {
235 url.protocol = "ws:";
236 } else if (url.protocol === "https:") {
237 url.protocol = "wss:";
238 } else {
239 throw new PrimaryEnvironmentProtocolUnsupportedError({
240 source: "window-origin",
241 protocol: url.protocol,
242 });
243 }
244 return {
245 source: "window-origin",
246 target: {
247 httpBaseUrl,
248 wsBaseUrl: url.toString(),
249 },
250 };
252​
253function resolveDesktopPrimaryTarget(): PrimaryEnvironmentTarget | null {
254 const desktopBootstrap = getDesktopLocalEnvironmentBootstrap();
255 if (!desktopBootstrap) {
256 return null;
257 }
258 if (!desktopBootstrap.httpBaseUrl && !desktopBootstrap.wsBaseUrl) {
259 return null;
260 }
261 if (!desktopBootstrap.httpBaseUrl || !desktopBootstrap.wsBaseUrl) {
262 throw new DesktopEnvironmentBootstrapIncompleteError({
263 hasHttpBaseUrl: Boolean(desktopBootstrap.httpBaseUrl),
264 hasWsBaseUrl: Boolean(desktopBootstrap.wsBaseUrl),
265 });
266 }
267​
268 return {
269 source: "desktop-managed",
270 target: {
271 httpBaseUrl: normalizeBaseUrl(
272 desktopBootstrap.httpBaseUrl,
273 "desktop-managed",
274 "http-base-url",
275 ),
276 wsBaseUrl: normalizeBaseUrl(
277 desktopBootstrap.wsBaseUrl,
278 "desktop-managed",
279 "websocket-base-url",
280 ),
281 },
282 };
284​
285export function resolvePrimaryEnvironmentHttpUrl(
286 pathname: string,
287 searchParams?: Record<string, string>,
288): string {
289 const primaryTarget = readPrimaryEnvironmentTarget();
290 if (!primaryTarget) {
291 throw new PrimaryEnvironmentDisabledError();
292 }
293​
294 const url = parseTargetUrl({
295 rawValue: resolveHttpRequestBaseUrl(primaryTarget),
296 source: primaryTarget.source,
297 urlKind: "http-base-url",
298 });
299 url.pathname = pathname;
300 if (searchParams) {
301 url.search = new URLSearchParams(searchParams).toString();
302 }
303 return url.toString();
305​
306// Null only when the desktop app runs with its local environment disabled;
307// every other host has a primary (falling back to the page origin).
308export function readPrimaryEnvironmentTarget(): PrimaryEnvironmentTarget | null {
309 if (isLocalEnvironmentDisabled()) {
310 return null;
311 }
312 return (
313 resolveDesktopPrimaryTarget() ??
314 resolveConfiguredPrimaryTarget() ??
315 resolveWindowOriginPrimaryTarget()
316 );