backend-resolver.ts 4.45 KB
/*
 * @Author: liimin 17653212@qq.com
 * @Date: 2026-10-12 10:21:57
 * @LastEditors: liimin 17653212@qq.com
 * @LastEditTime: 2026-10-12 11:48:50
 * @FilePath: \uj-store\src\api\core\backend-resolver.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 浏览器侧:根据「当前访问地址」动态解析后端服务地址。
// 映射表用于「访问域名 → 不同后端」的显式改写(可选,优先级最高)。
// 开发者无需在此登记自己的 IP —— 本地 / 开发地址(localhost、127.0.0.1、私有网段 IP 如 192.168.x.x)
// 会自动回退到 .env 的 VITE_API_TARGET(默认测试服务器),避免「用自己 IP 访问前端却打到自己机器上
// 根本不存在的后端」导致请求全部失败。只有正式域名(youjia.dev.glsx.com.cn 等)才走同源。
const HOST_BACKEND_MAP: Record<string, string> = {
  // 例:把某个生产/预发前端域名映射到指定后端(不受本地回退规则影响)
  // 'youjia.dev.glsx.com.cn': 'youjia-api.glsx.com.cn',
};

function stripTrailingSlash(url: string): string {
  return url.replace(/\/+$/, '');
}

/** 当前页面协议('http:' / 'https:');非浏览器环境回退 https。 */
function currentProtocol(): string {
  if (typeof window !== 'undefined' && window.location) return window.location.protocol;
  return 'https:';
}

/**
 * 判断 host(不含端口)是否为「本地 / 开发地址」,需要回退到 .env 默认服务端:
 *   - localhost / 127.0.0.1 / ::1
 *   - 私有网段:10.x.x.x、172.16-31.x.x、192.168.x.x、169.254.x.x(链路本地)
 * 这些地址下开发者机器上通常没有后端,用同源 IP 访问必然失败。
 */
function isLocalDevHost(hostNoPort: string): boolean {
  const h = hostNoPort.toLowerCase();
  if (h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]') return true;
  const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
  if (!m) return false;
  const a = Number(m[1]);
  const b = Number(m[2]);
  if (a === 10) return true; // 10.0.0.0/8
  if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
  if (a === 192 && b === 168) return true; // 192.168.0.0/16
  if (a === 169 && b === 254) return true; // 169.254.0.0/16 链路本地
  return false;
}

/**
 * 给映射值补协议,兼容 http / https:
 *   - 已含协议(http:// / https://)→ 原样返回;
 *   - 协议相对(//host)→ 跟随当前页协议;
 *   - 仅 host(youjia-api.xxx.com / host:port / host/path)→ 跟随当前页协议补上。
 * 这样映射表不必写死协议,http 访问解析到 http 后端、https 访问解析到 https 后端。
 */
function withProtocol(raw: string): string {
  const v = raw.trim();
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) return v;
  if (v.startsWith('//')) return currentProtocol() + v;
  return currentProtocol() + '//' + v;
}

/**
 * 解析 direct 模式下的后端 origin。仅在浏览器侧调用(config.ts 加载期),Node 侧不会走到此函数。
 * 优先级:① 映射表 HOST_BACKEND_MAP(显式改写,最高)② 本地/开发地址(localhost、私有网段 IP)→ .env 的 VITE_API_TARGET
 *         ③ 非本地(正式域名)→ 同源 window.location.origin ④ 兜底 → VITE_API_TARGET
 */
export function resolveBackendOrigin(): string {
  const envTarget = stripTrailingSlash(
    String((import.meta.env as Record<string, string | undefined>).VITE_API_TARGET ?? '').trim(),
  );

  if (typeof window === 'undefined' || !window.location) return envTarget;

  const host = window.location.host; // 含端口
  const hostNoPort = host.split(':')[0];

  const mapped = HOST_BACKEND_MAP[host] ?? HOST_BACKEND_MAP[hostNoPort];
  if (mapped) return stripTrailingSlash(withProtocol(mapped));

  // 开发模式(DEV,即 pnpm dev)→ 直接用 .env 默认服务端,开发者无需配自己的 IP;
  // 非开发模式但用本地/私有 IP 访问(如测试服务器以 IP 部署)→ 同样回退到默认服务端;
  // 正式域名(youjia.dev.glsx.com.cn 等)→ 走下方同源逻辑。
  if ((import.meta.env.DEV || isLocalDevHost(hostNoPort)) && envTarget) return envTarget;

  const origin = window.location.origin;
  if (origin && origin !== 'null' && !origin.startsWith('file:')) return origin;

  // 极端兜底:非浏览器 / origin 不可用 / env 未配置
  return envTarget;
}