Infer missing client environment URLs from one another

- Allow primary environment config to derive HTTP or WS base URLs when only one is set
- Preserve saved environment records during registry hydration
- Pass VITE_HTTP_URL through dev runner and Vite define
This commit is contained in:
Julius Marminge committed 2026-04-09 20:02:26 -07:00
1 parent 184de87e91
commit 45c8899c02
7 files changed
+108 -9

No files matched your search

@@ -110,6 +110,32 @@ describe("environmentBootstrap", () => {
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
});
it("derives the websocket url when only VITE_HTTP_URL is configured", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
expect(getPrimaryKnownEnvironment()?.target).toEqual({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
});
});
it("derives the http url when only VITE_WS_URL is configured", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
expect(getPrimaryKnownEnvironment()?.target).toEqual({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
});
});
it("uses the current origin as the descriptor base for local dev environments", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
+23 -7
View File
@@ -16,6 +16,15 @@ function normalizeBaseUrl(rawValue: string): string {
return new URL(rawValue, window.location.origin).toString();
}
function swapBaseUrlProtocol(
rawValue: string,
nextProtocol: "http:" | "https:" | "ws:" | "wss:",
): string {
const url = new URL(normalizeBaseUrl(rawValue));
url.protocol = nextProtocol;
return url.toString();
}
function normalizeHostname(hostname: string): string {
return hostname
.trim()
@@ -54,22 +63,29 @@ function resolveHttpRequestBaseUrl(httpBaseUrl: string): string {
}
function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim();
const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim();
const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined;
const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined;
if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
return null;
}
if (!configuredHttpBaseUrl || !configuredWsBaseUrl) {
throw new Error("Configured primary environments require both VITE_HTTP_URL and VITE_WS_URL.");
}
const resolvedHttpBaseUrl =
configuredHttpBaseUrl ??
(configuredWsBaseUrl?.startsWith("wss:")
? swapBaseUrlProtocol(configuredWsBaseUrl, "https:")
: swapBaseUrlProtocol(configuredWsBaseUrl!, "http:"));
const resolvedWsBaseUrl =
configuredWsBaseUrl ??
(configuredHttpBaseUrl?.startsWith("https:")
? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:")
: swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:"));
return {
source: "configured",
target: {
httpBaseUrl: normalizeBaseUrl(configuredHttpBaseUrl),
wsBaseUrl: normalizeBaseUrl(configuredWsBaseUrl),
httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl),
wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl),
},
};
}
@@ -1,4 +1,4 @@
import { EnvironmentId, type LocalApi } from "@t3tools/contracts";
import { EnvironmentId, type LocalApi, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
@@ -6,6 +6,7 @@ import {
resetSavedEnvironmentRuntimeStoreForTests,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
waitForSavedEnvironmentRegistryHydration,
} from "./catalog";
describe("environment runtime catalog stores", () => {
@@ -88,4 +89,49 @@ describe("environment runtime catalog stores", () => {
expect(errorSpy).toHaveBeenCalledWith("[SAVED_ENVIRONMENTS] persist failed", expect.any(Error));
});
it("does not let stale hydration overwrite records added while hydration is in flight", async () => {
let resolveRegistryRead: () => void = () => {
throw new Error("Registry read resolver was not initialized.");
};
vi.stubGlobal("window", {
nativeApi: {
persistence: {
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: () =>
new Promise<readonly PersistedSavedEnvironmentRecord[]>((resolve) => {
resolveRegistryRead = () => resolve([]);
}),
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
},
} satisfies Pick<LocalApi, "persistence">,
});
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
const hydrationPromise = waitForSavedEnvironmentRegistryHydration();
const environmentId = EnvironmentId.makeUnsafe("environment-1");
const record = {
environmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
} as const;
useSavedEnvironmentRegistryStore.getState().upsert(record);
resolveRegistryRead();
await hydrationPromise;
expect(useSavedEnvironmentRegistryStore.getState().byId[environmentId]).toEqual(record);
});
});
+6 -1
View File
@@ -74,8 +74,13 @@ function persistSavedEnvironmentRegistryState(
function replaceSavedEnvironmentRegistryState(
records: ReadonlyArray<SavedEnvironmentRecord>,
): void {
const currentById = useSavedEnvironmentRegistryStore.getState().byId;
const hydratedById = Object.fromEntries(records.map((record) => [record.environmentId, record]));
useSavedEnvironmentRegistryStore.setState({
byId: Object.fromEntries(records.map((record) => [record.environmentId, record])),
byId: {
...hydratedById,
...currentById,
},
});
}
+2
View File
@@ -7,6 +7,7 @@ import pkg from "./package.json" with { type: "json" };
const port = Number(process.env.PORT ?? 5733);
const host = process.env.HOST?.trim() || "localhost";
const configuredHttpUrl = process.env.VITE_HTTP_URL?.trim();
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
@@ -58,6 +59,7 @@ export default defineConfig({
include: ["@pierre/diffs", "@pierre/diffs/react", "@pierre/diffs/worker/worker.js"],
},
define: {
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
"import.meta.env.APP_VERSION": JSON.stringify(pkg.version),
+2
View File
@@ -84,6 +84,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.T3CODE_HOME, resolve("/tmp/custom-t3"));
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_HTTP_URL, "http://localhost:4222");
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
assert.equal(env.T3CODE_NO_BROWSER, "1");
assert.equal(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD, "0");
@@ -183,6 +184,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.VITE_DEV_SERVER_URL, "http://127.0.0.1:5733");
assert.equal(env.HOST, "127.0.0.1");
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:4222");
assert.equal(env.T3CODE_MODE, undefined);
assert.equal(env.T3CODE_NO_BROWSER, undefined);
assert.equal(env.T3CODE_HOST, undefined);
+2
View File
@@ -159,9 +159,11 @@ export function createDevRunnerEnv({
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
} else {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
delete output.T3CODE_MODE;
delete output.T3CODE_NO_BROWSER;