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

target.ts

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