Open History to see the last commit
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 }
32}
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 }
44}
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 }
60}
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 }
69}
70
71export interface PrimaryEnvironmentTarget {
72 readonly source: PrimaryEnvironmentTargetSource;
73 readonly target: {
74 readonly httpBaseUrl: string;
75 readonly wsBaseUrl: string;
76 };
77}
78
79const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
80
81function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | null {
82 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
83 return bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID) ?? null;
84}
85
86function parseTargetUrl(input: {
87 readonly rawValue: string;
88 readonly baseUrl?: string;
89 readonly source: PrimaryEnvironmentTargetSource;
90 readonly urlKind: PrimaryEnvironmentUrlKind;
91}): URL {
92 try {
93 return input.baseUrl === undefined
94 ? new URL(input.rawValue)
95 : new URL(input.rawValue, input.baseUrl);
96 } catch (cause) {
97 throw new PrimaryEnvironmentUrlInvalidError({
98 source: input.source,
99 urlKind: input.urlKind,
100 cause,
101 });
102 }
103}
104
105function normalizeBaseUrl(
106 rawValue: string,
107 source: PrimaryEnvironmentTargetSource,
108 urlKind: PrimaryEnvironmentUrlKind,
109): string {
110 return parseTargetUrl({
111 rawValue,
112 baseUrl: window.location.origin,
113 source,
114 urlKind,
115 }).toString();
116}
117
118function swapBaseUrlProtocol(
119 rawValue: string,
120 nextProtocol: "http:" | "https:" | "ws:" | "wss:",
121 urlKind: PrimaryEnvironmentUrlKind,
122): string {
123 const url = parseTargetUrl({
124 rawValue,
125 baseUrl: window.location.origin,
126 source: "configured",
127 urlKind,
128 });
129 url.protocol = nextProtocol;
130 return url.toString();
131}
132
133function normalizeHostname(hostname: string): string {
134 return hostname
135 .trim()
136 .toLowerCase()
137 .replace(/^\[(.*)\]$/, "$1");
138}
139
140export function isLoopbackHostname(hostname: string): boolean {
141 return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
142}
143
144function resolveHttpRequestBaseUrl(primaryTarget: PrimaryEnvironmentTarget): string {
145 const httpBaseUrl = primaryTarget.target.httpBaseUrl;
146 const configuredDevServerUrl = import.meta.env.VITE_DEV_SERVER_URL?.trim();
147 if (!configuredDevServerUrl) {
148 return httpBaseUrl;
149 }
150
151 const currentUrl = parseTargetUrl({
152 rawValue: window.location.href,
153 source: "window-origin",
154 urlKind: "window-location-url",
155 });
156 const targetUrl = parseTargetUrl({
157 rawValue: httpBaseUrl,
158 source: primaryTarget.source,
159 urlKind: "http-base-url",
160 });
161 const devServerUrl = parseTargetUrl({
162 rawValue: configuredDevServerUrl,
163 baseUrl: currentUrl.origin,
164 source: "configured",
165 urlKind: "development-server-url",
166 });
167
168 const isCurrentOriginDevServer =
169 (currentUrl.protocol === "http:" || currentUrl.protocol === "https:") &&
170 currentUrl.origin === devServerUrl.origin;
171
172 if (
173 !isCurrentOriginDevServer ||
174 currentUrl.origin === targetUrl.origin ||
175 !isLoopbackHostname(currentUrl.hostname) ||
176 !isLoopbackHostname(targetUrl.hostname)
177 ) {
178 return httpBaseUrl;
179 }
180
181 return currentUrl.origin;
182}
183
184function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
185 const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined;
186 const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined;
187
188 if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
189 return null;
190 }
191
192 // Scheme checks run on the raw configured string, while the URL parser
193 // folds schemes to lowercase ("WSS://host" parses fine). Without the
194 // case folding an uppercase scheme would be classified as plaintext and
195 // swapped to http/ws, silently downgrading TLS.
196 const resolvedHttpBaseUrl =
197 configuredHttpBaseUrl ??
198 (configuredWsBaseUrl?.toLowerCase().startsWith("wss:")
199 ? swapBaseUrlProtocol(configuredWsBaseUrl, "https:", "websocket-base-url")
200 : swapBaseUrlProtocol(configuredWsBaseUrl!, "http:", "websocket-base-url"));
201 const resolvedWsBaseUrl =
202 configuredWsBaseUrl ??
203 (configuredHttpBaseUrl?.toLowerCase().startsWith("https:")
204 ? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:", "http-base-url")
205 : swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:", "http-base-url"));
206
207 return {
208 source: "configured",
209 target: {
210 httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl, "configured", "http-base-url"),
211 wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl, "configured", "websocket-base-url"),
212 },
213 };
214}
215
216function resolveWindowOriginPrimaryTarget(): PrimaryEnvironmentTarget {
217 const url = parseTargetUrl({
218 rawValue: window.location.origin,
219 source: "window-origin",
220 urlKind: "http-base-url",
221 });
222 const httpBaseUrl = url.toString();
223 if (url.protocol === "http:") {
224 url.protocol = "ws:";
225 } else if (url.protocol === "https:") {
226 url.protocol = "wss:";
227 } else {
228 throw new PrimaryEnvironmentProtocolUnsupportedError({
229 source: "window-origin",
230 protocol: url.protocol,
231 });
232 }
233 return {
234 source: "window-origin",
235 target: {
236 httpBaseUrl,
237 wsBaseUrl: url.toString(),
238 },
239 };
240}
241
242function resolveDesktopPrimaryTarget(): PrimaryEnvironmentTarget | null {
243 const desktopBootstrap = getDesktopLocalEnvironmentBootstrap();
244 if (!desktopBootstrap) {
245 return null;
246 }
247 if (!desktopBootstrap.httpBaseUrl && !desktopBootstrap.wsBaseUrl) {
248 return null;
249 }
250 if (!desktopBootstrap.httpBaseUrl || !desktopBootstrap.wsBaseUrl) {
251 throw new DesktopEnvironmentBootstrapIncompleteError({
252 hasHttpBaseUrl: Boolean(desktopBootstrap.httpBaseUrl),
253 hasWsBaseUrl: Boolean(desktopBootstrap.wsBaseUrl),
254 });
255 }
256
257 return {
258 source: "desktop-managed",
259 target: {
260 httpBaseUrl: normalizeBaseUrl(
261 desktopBootstrap.httpBaseUrl,
262 "desktop-managed",
263 "http-base-url",
264 ),
265 wsBaseUrl: normalizeBaseUrl(
266 desktopBootstrap.wsBaseUrl,
267 "desktop-managed",
268 "websocket-base-url",
269 ),
270 },
271 };
272}
273
274export function resolvePrimaryEnvironmentHttpUrl(
275 pathname: string,
276 searchParams?: Record<string, string>,
277): string {
278 const primaryTarget = readPrimaryEnvironmentTarget();
279 if (!primaryTarget) {
280 throw new PrimaryEnvironmentDisabledError();
281 }
282
283 const url = parseTargetUrl({
284 rawValue: resolveHttpRequestBaseUrl(primaryTarget),
285 source: primaryTarget.source,
286 urlKind: "http-base-url",
287 });
288 url.pathname = pathname;
289 if (searchParams) {
290 url.search = new URLSearchParams(searchParams).toString();
291 }
292 return url.toString();
293}
294
295// Null only when the desktop app runs with its local environment disabled;
296// every other host has a primary (falling back to the page origin).
297export function readPrimaryEnvironmentTarget(): PrimaryEnvironmentTarget | null {
298 if (isLocalEnvironmentDisabled()) {
299 return null;
300 }
301 return (
302 resolveDesktopPrimaryTarget() ??
303 resolveConfiguredPrimaryTarget() ??
304 resolveWindowOriginPrimaryTarget()
305 );
306}