Open History to see the last commit
1/**
2 * Pure URL helpers shared between the preview server, desktop main process,
3 * and web renderer. Centralising these guarantees the four call sites agree
4 * on what counts as "loopback" and how to normalise a free-form URL string.
5 */
6
7import * as Schema from "effect/Schema";
8
9const TAB_ID_PREFIX = "tab_";
10let nextPreviewTabSequence = 0;
11
12/**
13 * Generate a fresh preview tab id. Lives in shared (not contracts) because
14 * the contracts package is schema-only — runtime helpers belong here.
15 */
16export function newPreviewTabId(): string {
17 nextPreviewTabSequence += 1;
18 return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;
19}
20
21const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
22
23/** Internal — used by `lsof` parsing where the host string is wire-formatted. */
24export const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([
25 ...LOOPBACK_HOSTS,
26 "*",
27 "[::]",
28 "[::1]",
29]);
30
31const LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
32
33export function isLoopbackHost(host: string): boolean {
34 if (LOOPBACK_HOSTS.has(host)) return true;
35 if (host === "[::1]") return true;
36 return false;
37}
38
39/** True when a raw URL string looks like a loopback dev URL we can preview. */
40export function isPreviewableUrl(rawUrl: string): boolean {
41 try {
42 const parsed = new URL(rawUrl);
43 if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
44 return isLoopbackHost(parsed.hostname);
45 } catch {
46 return false;
47 }
48}
49
50export class PreviewUrlNormalizationError extends Schema.TaggedErrorClass<PreviewUrlNormalizationError>()(
51 "PreviewUrlNormalizationError",
52 {
53 inputLength: Schema.Number,
54 reason: Schema.Literals(["empty", "parse", "unsupported-protocol"]),
55 protocol: Schema.optional(Schema.String),
56 cause: Schema.optional(Schema.Defect()),
57 },
58) {
59 override get message(): string {
60 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
61 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
62 }
63}
64
65export const isPreviewUrlNormalizationError = Schema.is(PreviewUrlNormalizationError);
66
67function previewUrlProtocol(rawUrl: string): string | undefined {
68 return /^([A-Za-z][A-Za-z\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(":");
69}
70
71/**
72 * Normalise a free-form URL string into a fully-qualified `http(s)://` URL.
73 *
74 * - Bare loopback hosts (`localhost`, `localhost:5173`) become `http://...`.
75 * - Bare public hosts (`example.com`) become `https://...`.
76 * - Already-qualified URLs are validated and returned as `URL.href`.
77 *
78 * Throws `PreviewUrlNormalizationError` for empty, unparseable, or
79 * unsupported-protocol inputs.
80 */
81export function normalizePreviewUrl(rawUrl: string): string {
82 const trimmed = rawUrl.trim();
83 if (trimmed.length === 0) {
84 throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: "empty" });
85 }
86 const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);
87 const candidate = trimmed.includes("://")
88 ? trimmed
89 : `${useHttp ? "http" : "https"}://${trimmed}`;
90 let parsed: URL;
91 try {
92 parsed = new URL(candidate);
93 } catch (cause) {
94 throw new PreviewUrlNormalizationError({
95 inputLength: rawUrl.length,
96 reason: "parse",
97 protocol: previewUrlProtocol(candidate),
98 cause,
99 });
100 }
101 if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
102 throw new PreviewUrlNormalizationError({
103 inputLength: rawUrl.length,
104 reason: "unsupported-protocol",
105 protocol: parsed.protocol,
106 });
107 }
108 return parsed.href;
109}