Open History to see the last commit
1import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5import {
6 getPrimaryKnownEnvironment,
7 isDesktopEnvironmentBootstrapIncompleteError,
8 isPrimaryEnvironmentProtocolUnsupportedError,
9 isPrimaryEnvironmentUrlInvalidError,
10 readPrimaryEnvironmentTarget,
11 resolvePrimaryEnvironmentHttpUrl,
12 resolveInitialPrimaryEnvironmentDescriptor,
13 resetPrimaryEnvironmentDescriptorForTests,
14 writePrimaryEnvironmentDescriptor,
15} from ".";
16import { installEnvironmentHttpTest } from "../../../test/environmentHttpTest";
17
18const BASE_ENVIRONMENT = {
19 environmentId: EnvironmentId.make("environment-local"),
20 label: "Local environment",
21 platform: {
22 os: "darwin",
23 arch: "arm64",
24 },
25 serverVersion: "0.0.0-test",
26 capabilities: {
27 repositoryIdentity: true,
28 },
29} satisfies ExecutionEnvironmentDescriptor;
30
31let disposeHttpTest: (() => Promise<void>) | undefined;
32
33async function installDescriptorApi() {
34 const testApi = await installEnvironmentHttpTest({
35 descriptor: () => Effect.succeed(BASE_ENVIRONMENT),
36 });
37 disposeHttpTest = testApi.dispose;
38 return testApi;
39}
40
41function installTestBrowser(url: string) {
42 vi.stubGlobal("window", {
43 location: new URL(url),
44 history: {
45 replaceState: vi.fn(),
46 },
47 });
48}
49
50function captureThrown(run: () => unknown): unknown {
51 try {
52 run();
53 } catch (error) {
54 return error;
55 }
56 throw new Error("Expected the operation to throw.");
57}
58
59describe("environmentBootstrap", () => {
60 beforeEach(() => {
61 vi.restoreAllMocks();
62 vi.useRealTimers();
63 installTestBrowser("http://localhost/");
64 });
65
66 afterEach(async () => {
67 await disposeHttpTest?.();
68 disposeHttpTest = undefined;
69 resetPrimaryEnvironmentDescriptorForTests();
70 vi.unstubAllEnvs();
71 vi.useRealTimers();
72 vi.restoreAllMocks();
73 vi.unstubAllGlobals();
74 });
75
76 it("attaches the bootstrapped environment descriptor to the primary environment", () => {
77 vi.stubGlobal("window", {
78 location: {
79 origin: "http://localhost:3773",
80 },
81 desktopBridge: undefined,
82 });
83 writePrimaryEnvironmentDescriptor({
84 environmentId: EnvironmentId.make("environment-local"),
85 label: "Bootstrapped environment",
86 platform: {
87 os: "darwin",
88 arch: "arm64",
89 },
90 serverVersion: "0.0.0-test",
91 capabilities: {
92 repositoryIdentity: true,
93 },
94 });
95
96 expect(getPrimaryKnownEnvironment()).toEqual({
97 id: "environment-local",
98 label: "Bootstrapped environment",
99 source: "window-origin",
100 environmentId: "environment-local",
101 target: {
102 httpBaseUrl: "http://localhost:3773/",
103 wsBaseUrl: "ws://localhost:3773/",
104 },
105 });
106 });
107
108 it("reuses an in-flight descriptor bootstrap request", async () => {
109 const testApi = await installDescriptorApi();
110
111 await Promise.all([
112 resolveInitialPrimaryEnvironmentDescriptor(),
113 resolveInitialPrimaryEnvironmentDescriptor(),
114 ]);
115
116 expect(testApi.calls.descriptor).toBe(1);
117 });
118
119 it("uses https descriptor urls when the primary environment uses wss", async () => {
120 vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
121 vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
122 await installDescriptorApi();
123
124 await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
125 expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(
126 "https://remote.example.com/.well-known/t3/environment",
127 );
128 });
129
130 it("derives the websocket url when only VITE_HTTP_URL is configured", async () => {
131 vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
132 await installDescriptorApi();
133
134 await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
135 expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(
136 "https://remote.example.com/.well-known/t3/environment",
137 );
138 expect(getPrimaryKnownEnvironment()?.target).toEqual({
139 httpBaseUrl: "https://remote.example.com/",
140 wsBaseUrl: "wss://remote.example.com/",
141 });
142 });
143
144 it("derives the http url when only VITE_WS_URL is configured", async () => {
145 vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
146 await installDescriptorApi();
147
148 await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
149 expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(
150 "https://remote.example.com/.well-known/t3/environment",
151 );
152 expect(getPrimaryKnownEnvironment()?.target).toEqual({
153 httpBaseUrl: "https://remote.example.com/",
154 wsBaseUrl: "wss://remote.example.com/",
155 });
156 });
157
158 it("keeps an uppercase wss scheme secure when deriving the http url", () => {
159 vi.stubEnv("VITE_WS_URL", "WSS://remote.example.com");
160
161 expect(readPrimaryEnvironmentTarget()?.target).toEqual({
162 httpBaseUrl: "https://remote.example.com/",
163 wsBaseUrl: "wss://remote.example.com/",
164 });
165 });
166
167 it("keeps an uppercase https scheme secure when deriving the websocket url", () => {
168 vi.stubEnv("VITE_HTTP_URL", "HTTPS://remote.example.com");
169
170 expect(readPrimaryEnvironmentTarget()?.target).toEqual({
171 httpBaseUrl: "https://remote.example.com/",
172 wsBaseUrl: "wss://remote.example.com/",
173 });
174 });
175
176 it("uses the current origin as the descriptor base for local dev environments", async () => {
177 installTestBrowser("http://localhost:5735/");
178 await installDescriptorApi();
179
180 await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
181 expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(
182 "http://localhost:5735/.well-known/t3/environment",
183 );
184 });
185
186 it("uses the vite proxy for desktop-managed loopback descriptor requests during local dev", async () => {
187 vi.stubEnv("VITE_DEV_SERVER_URL", "http://127.0.0.1:5733");
188 vi.stubGlobal("window", {
189 location: new URL("http://127.0.0.1:5733/"),
190 history: {
191 replaceState: vi.fn(),
192 },
193 desktopBridge: {
194 getLocalEnvironmentBootstraps: () => [
195 {
196 id: "primary",
197 label: "Windows",
198 httpBaseUrl: "http://127.0.0.1:3773",
199 wsBaseUrl: "ws://127.0.0.1:3773",
200 bootstrapToken: "desktop-bootstrap-token",
201 },
202 ],
203 },
204 });
205 await installDescriptorApi();
206
207 await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
208 expect(resolvePrimaryEnvironmentHttpUrl("/.well-known/t3/environment")).toBe(
209 "http://127.0.0.1:5733/.well-known/t3/environment",
210 );
211 });
212
213 it("retains the URL parser cause without exposing the configured URL in its message", () => {
214 vi.stubEnv("VITE_HTTP_URL", "http://[");
215
216 const error = captureThrown(readPrimaryEnvironmentTarget);
217
218 expect(isPrimaryEnvironmentUrlInvalidError(error)).toBe(true);
219 if (!isPrimaryEnvironmentUrlInvalidError(error)) {
220 throw new Error("Expected a structured primary environment URL error.");
221 }
222 expect(error).toMatchObject({
223 source: "configured",
224 urlKind: "http-base-url",
225 message: "Could not parse http-base-url for the configured primary environment target.",
226 });
227 expect(error.cause).toBeInstanceOf(TypeError);
228 expect(error.message).not.toContain("http://[");
229 });
230
231 it("describes which desktop bootstrap endpoint is missing", () => {
232 vi.stubGlobal("window", {
233 location: new URL("http://127.0.0.1:5733/"),
234 history: { replaceState: vi.fn() },
235 desktopBridge: {
236 getLocalEnvironmentBootstraps: () => [
237 {
238 id: "primary",
239 label: "Local environment",
240 httpBaseUrl: "http://127.0.0.1:3773",
241 bootstrapToken: "desktop-bootstrap-token",
242 },
243 ],
244 },
245 });
246
247 const error = captureThrown(readPrimaryEnvironmentTarget);
248
249 expect(isDesktopEnvironmentBootstrapIncompleteError(error)).toBe(true);
250 if (!isDesktopEnvironmentBootstrapIncompleteError(error)) {
251 throw new Error("Expected a structured desktop bootstrap error.");
252 }
253 expect(error).toMatchObject({
254 hasHttpBaseUrl: true,
255 hasWsBaseUrl: false,
256 message: "Desktop bootstrap is missing wsBaseUrl for the local environment.",
257 });
258 });
259
260 it("has no primary target when the desktop local environment is disabled", () => {
261 vi.stubGlobal("window", {
262 location: new URL("t3code://app/"),
263 desktopBridge: {
264 getLocalEnvironmentEnabled: () => false,
265 getLocalEnvironmentBootstraps: () => [],
266 },
267 });
268
269 expect(readPrimaryEnvironmentTarget()).toBeNull();
270 expect(getPrimaryKnownEnvironment()).toBeNull();
271 expect(() => resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toThrow(
272 "The local environment is disabled.",
273 );
274 });
275
276 it("preserves an unsupported window-origin protocol", () => {
277 vi.stubGlobal("window", {
278 location: { origin: "file:///tmp/t3code/" },
279 history: { replaceState: vi.fn() },
280 });
281
282 const error = captureThrown(readPrimaryEnvironmentTarget);
283
284 expect(isPrimaryEnvironmentProtocolUnsupportedError(error)).toBe(true);
285 if (!isPrimaryEnvironmentProtocolUnsupportedError(error)) {
286 throw new Error("Expected a structured primary environment protocol error.");
287 }
288 expect(error).toMatchObject({
289 source: "window-origin",
290 protocol: "file:",
291 message: "The window-origin primary environment target uses unsupported protocol file:.",
292 });
293 });
294});