Spaces:
Runtime error
Runtime error
File size: 1,998 Bytes
fb38ec5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import { env } from "../env.js";
/**
* Returns the appropriate protocol based on the protocol type and HTTPS setting
* @param protocolType 'http' or 'ws' - base protocol type
* @returns The protocol string with or without 's' suffix based on env.USE_SSL
*/
function getProtocol(protocolType: "http" | "ws"): string {
return env.USE_SSL ? `${protocolType}s` : protocolType;
}
/**
* Returns the base URL for the server, handling DOMAIN vs HOST:PORT appropriately
* @param protocolType 'http' or 'ws' - determines the protocol prefix
* @returns Formatted base URL with appropriate protocol and trailing slash
*/
export function getBaseUrl(protocolType: "http" | "ws" = "http"): string {
const baseUrl = env.DOMAIN ?? `${env.HOST}:${env.PORT}`;
const protocol = getProtocol(protocolType);
return `${protocol}://${baseUrl}/`;
}
/**
* Returns a fully qualified URL with the given path
* @param path The path to append to the base URL
* @param protocolType 'http' or 'ws' - determines the protocol prefix
* @returns Formatted URL with appropriate protocol
*/
export function getUrl(path: string, protocolType: "http" | "ws" = "http"): string {
const base = getBaseUrl(protocolType);
// Handle paths that might already have a leading slash
const formattedPath = path.startsWith("/") ? path.substring(1) : path;
return `${base}${formattedPath}`;
}
/**
* Normalizes a URL by adding https:// protocol if missing
* @param url The URL to normalize
* @returns The normalized URL with proper protocol, or null if invalid
*/
export function normalizeUrl(url: string): string | null {
if (!url || typeof url !== "string") {
return null;
}
const trimmedUrl = url.trim();
if (!trimmedUrl) {
return null;
}
if (trimmedUrl.startsWith("http://") || trimmedUrl.startsWith("https://")) {
return trimmedUrl;
}
const normalizedUrl = `https://${trimmedUrl}`;
try {
new URL(normalizedUrl);
return normalizedUrl;
} catch {
return null;
}
}
|