Open History to see the last commit
1import type { ScopedThreadRef } from "@t3tools/contracts";
2
3import { readPreparedConnection } from "~/state/session";
4import { buildThreadRoutePath } from "./threadRoutes";
5
6function browserOrigin(value: string | null): string | null {
7 if (value === null) {
8 return null;
9 }
10 return value.startsWith("http://") || value.startsWith("https://") ? value : null;
11}
12
13/**
14 * The address a browser can open to land on a thread.
15 *
16 * In a browser the answer is the address bar: the app is served from the
17 * origin the user is already on. The desktop app has no address bar and its
18 * renderer origin (`t3code://app`) means nothing outside the app, so the link
19 * falls back to the environment's own HTTP base URL — the T3 server that owns
20 * the thread and serves the web client for it. Environments reachable only
21 * through a target we cannot express as an HTTP origin get no link.
22 */
23export function resolveThreadLink(input: {
24 /** `window.location.origin`, or null off a browser origin. */
25 readonly clientOrigin: string | null;
26 readonly environmentHttpBaseUrl: string | null;
27 readonly ref: ScopedThreadRef;
28}): string | null {
29 const base = browserOrigin(input.clientOrigin) ?? browserOrigin(input.environmentHttpBaseUrl);
30 if (base === null) {
31 return null;
32 }
33 try {
34 return new URL(buildThreadRoutePath(input.ref), base).toString();
35 } catch {
36 return null;
37 }
38}
39
40/** `resolveThreadLink` against this client's origin and live connection. */
41export function readThreadLink(ref: ScopedThreadRef): string | null {
42 return resolveThreadLink({
43 clientOrigin: typeof window === "undefined" ? null : window.location.origin,
44 environmentHttpBaseUrl: readPreparedConnection(ref.environmentId)?.httpBaseUrl ?? null,
45 ref,
46 });
47}