73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
/** Both websites share environment routing for business APIs and private attachments. */
|
|
export const apiOrigins = {
|
|
development: "https://dev-cadworld-api.robotquan.com",
|
|
production: "https://cadworld-api.robotquan.com",
|
|
} as const;
|
|
|
|
export function isLocalHostname(hostname: string): boolean {
|
|
const host = hostname.toLowerCase();
|
|
if (
|
|
host === "localhost" ||
|
|
host.endsWith(".localhost") ||
|
|
host.endsWith(".local") ||
|
|
host === "[::1]" ||
|
|
host === "::1"
|
|
)
|
|
return true;
|
|
const octets = host.split(".").map(Number);
|
|
return (
|
|
/^\d+\.\d+\.\d+\.\d+$/.test(host) &&
|
|
octets.every(
|
|
(part) => Number.isInteger(part) && part >= 0 && part <= 255,
|
|
) &&
|
|
(octets[0] === 127 ||
|
|
octets[0] === 10 ||
|
|
(octets[0] === 192 && octets[1] === 168) ||
|
|
(octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
|
|
(octets[0] === 169 && octets[1] === 254))
|
|
);
|
|
}
|
|
|
|
export function apiOrigin(pageOrigin: string): string {
|
|
const hostname = new URL(pageOrigin).hostname.toLowerCase();
|
|
if (isLocalHostname(hostname)) return "";
|
|
if (
|
|
["dev-cadworld.robotquan.com", "dev-cadworld-admin.robotquan.com"].includes(
|
|
hostname,
|
|
)
|
|
)
|
|
return apiOrigins.development;
|
|
if (
|
|
["cadworld.robotquan.com", "cadworld-admin.robotquan.com"].includes(
|
|
hostname,
|
|
)
|
|
)
|
|
return apiOrigins.production;
|
|
throw Error(`当前网站域名尚未配置 API 地址:${hostname}`);
|
|
}
|
|
|
|
export function apiUrl(
|
|
value: string,
|
|
pageOrigin = typeof window === "undefined"
|
|
? "http://localhost"
|
|
: window.location.origin,
|
|
): string {
|
|
const url = new URL(value, pageOrigin);
|
|
const servicePath =
|
|
url.pathname.startsWith("/admin-api/") ||
|
|
url.pathname.startsWith("/api/auth/") ||
|
|
url.pathname.startsWith("/api/users/") ||
|
|
url.pathname.startsWith("/api/projects") ||
|
|
url.pathname.startsWith("/api/plaza/") ||
|
|
url.pathname.startsWith("/api/robot-");
|
|
if (!servicePath) return url.href;
|
|
const origin = apiOrigin(pageOrigin);
|
|
let path = url.pathname;
|
|
if (origin && path.startsWith("/api/robot-model-assets/"))
|
|
path = path.replace(
|
|
/^\/api\/robot-model-assets\//,
|
|
"/admin-api/component-assets/",
|
|
);
|
|
return `${origin}${path}${url.search}`;
|
|
}
|