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

target.ts

298 lines8.9 KB

1import { PRIMARY_LOCAL_ENVIRONMENT_ID, type DesktopEnvironmentBootstrap } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3​
4const PrimaryEnvironmentTargetSource = Schema.Literals([
5 "configured",
6 "window-origin",
7 "desktop-managed",
8]);
9type PrimaryEnvironmentTargetSource = typeof PrimaryEnvironmentTargetSource.Type;
10​
11const PrimaryEnvironmentUrlKind = Schema.Literals([
12 "http-base-url",
13 "websocket-base-url",
14 "development-server-url",
15 "window-location-url",
16]);
17type PrimaryEnvironmentUrlKind = typeof PrimaryEnvironmentUrlKind.Type;
18​
19export class PrimaryEnvironmentUrlInvalidError extends Schema.TaggedError<PrimaryEnvironmentUrlInvalidError>()(
20 "PrimaryEnvironmentUrlInvalidError",
21 {
22 source: PrimaryEnvironmentTargetSource,
23 urlKind: PrimaryEnvironmentUrlKind,
24 cause: Schema.Defect(),
25 },
26) {
27 override get message(): string {
28 return `Could not parse ${this.urlKind} for the ${this.source} primary environment target.`;
29 }
31​
32export class PrimaryEnvironmentProtocolUnsupportedError extends Schema.TaggedError<PrimaryEnvironmentProtocolUnsupportedError>()(
33 "PrimaryEnvironmentProtocolUnsupportedError",
34 {
35 source: PrimaryEnvironmentTargetSource,
36 protocol: Schema.String,
37 },
38) {
39 override get message(): string {
40 return `The ${this.source} primary environment target uses unsupported protocol ${this.protocol}.`;
41 }
43​
44export class DesktopEnvironmentBootstrapIncompleteError extends Schema.TaggedError<DesktopEnvironmentBootstrapIncompleteError>()(
45 "DesktopEnvironmentBootstrapIncompleteError",
46 {
47 hasHttpBaseUrl: Schema.Boolean,
48 hasWsBaseUrl: Schema.Boolean,
49 },
50) {
51 override get message(): string {
52 const missing = [
53 ...(this.hasHttpBaseUrl ? [] : ["httpBaseUrl"]),
54 ...(this.hasWsBaseUrl ? [] : ["wsBaseUrl"]),
55 ];
56 return `Desktop bootstrap is missing ${missing.join(" and ")} for the local environment.`;
57 }
59​
60export const isPrimaryEnvironmentUrlInvalidError = Schema.is(PrimaryEnvironmentUrlInvalidError);
61export const isPrimaryEnvironmentProtocolUnsupportedError = Schema.is(
62 PrimaryEnvironmentProtocolUnsupportedError,
63);
64export const isDesktopEnvironmentBootstrapIncompleteError = Schema.is(
65 DesktopEnvironmentBootstrapIncompleteError,
66);
67​
68export interface PrimaryEnvironmentTarget {
69 readonly source: PrimaryEnvironmentTargetSource;
70 readonly target: {
71 readonly httpBaseUrl: string;
72 readonly wsBaseUrl: string;
73 };
75​
76const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
77​
78function getDesktopLocalEnvironmentBootstrap(): DesktopEnvironmentBootstrap | null {
79 // The primary (Windows-native) backend keeps the "primary" id. The
80 // plural list may include a second WSL entry; the primary-target
81 // resolver only cares about the primary, so just find it.
82 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
83 return bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID) ?? null;
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 }
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();
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();
132​
133function normalizeHostname(hostname: string): string {
134 return hostname
135 .trim()
136 .toLowerCase()
137 .replace(/^\[(.*)\]$/, "$1");
139​
140export function isLoopbackHostname(hostname: string): boolean {
141 return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
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;
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 };
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 };
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 };
273​
274export function resolvePrimaryEnvironmentHttpUrl(
275 pathname: string,
276 searchParams?: Record<string, string>,
277): string {
278 const primaryTarget = readPrimaryEnvironmentTarget();
279​
280 const url = parseTargetUrl({
281 rawValue: resolveHttpRequestBaseUrl(primaryTarget),
282 source: primaryTarget.source,
283 urlKind: "http-base-url",
284 });
285 url.pathname = pathname;
286 if (searchParams) {
287 url.search = new URLSearchParams(searchParams).toString();
288 }
289 return url.toString();
291​
292export function readPrimaryEnvironmentTarget(): PrimaryEnvironmentTarget {
293 return (
294 resolveDesktopPrimaryTarget() ??
295 resolveConfiguredPrimaryTarget() ??
296 resolveWindowOriginPrimaryTarget()
297 );