merge-route-defs.ts 3.28 KB
import type { SubAppManifest } from '@uj/contracts';

/**
 * 运行时动态注册的【纯逻辑】:构建期子应用 ∪ 运行时清单。
 *
 * 特意与 subapps.ts / runtime-manifest.ts 分开:那两个模块分别带 import.meta.glob
 * 与浏览器 fetch,只能在 Vite 环境里加载;本文件只做数据合并,可脱离浏览器单测。
 *
 * 规则(按优先级):
 *  1. shortName 是唯一键;构建期已注册的以构建期 route 为准,清单不覆写
 *     (静态路由已编进 bundle,运行时改 route 会生成两条互相打架的规则)。
 *  2. 清单新增项 route 缺省 = shortName;可用 route 字段覆写(对齐 uj.route)。
 *  3. route 与主壳静态页、或与其它子应用冲突 → 跳过并告警,不让 React Router
 *     静默命中先注册的那条(构建期 subapps.ts 直接抛错,运行时不能抛错白屏)。
 *  4. 清单条目缺 url / 名字非法 → 跳过并告警。
 */

export interface RouteDef {
  shortName: string;
  route: string;
}

/** 主壳自身的静态页面首段,子应用不得占用(否则 React Router 匹配会变得含糊)。 */
const RESERVED_ROUTES = new Set(['login', 'dashboard', 'profile']);
const VALID_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;

export function mergeRouteDefs(
  builtIn: RouteDef[],
  manifest: SubAppManifest | null,
): { routes: RouteDef[]; warnings: string[] } {
  const warnings: string[] = [];
  const byName = new Map<string, RouteDef>();
  const byRoute = new Map<string, string>();

  for (const app of builtIn) {
    byName.set(app.shortName, app);
    byRoute.set(app.route, app.shortName);
  }

  const subapps = manifest?.subapps;
  if (subapps && typeof subapps === 'object') {
    for (const [shortName, meta] of Object.entries(subapps)) {
      if (!VALID_SEGMENT.test(shortName)) {
        warnings.push(`清单条目「${shortName}」名字非法,已跳过`);
        continue;
      }
      if (!meta || typeof meta.url !== 'string' || meta.url.length === 0) {
        warnings.push(`清单条目 ${shortName} 缺少有效 url,已跳过`);
        continue;
      }

      const route = meta.route || shortName;
      if (!VALID_SEGMENT.test(route)) {
        warnings.push(`清单条目 ${shortName} 的 route=${route} 非法,已跳过`);
        continue;
      }

      const known = byName.get(shortName);
      if (known) {
        if (known.route !== route) {
          warnings.push(
            `清单为 ${shortName} 指定 route=${route},但构建期已注册 ${known.route};` +
              `运行时不覆写构建期路由,仍用 ${known.route}(要改路由需重建 host)`,
          );
        }
        continue; // 已注册,无需重复加入
      }

      if (RESERVED_ROUTES.has(route)) {
        warnings.push(`清单条目 ${shortName} 的 route=${route} 与主壳静态页冲突,已跳过`);
        continue;
      }
      const owner = byRoute.get(route);
      if (owner) {
        warnings.push(`清单条目 ${shortName} 的 route=${route} 与 ${owner} 冲突,已跳过`);
        continue;
      }

      const def = { shortName, route };
      byName.set(shortName, def);
      byRoute.set(route, shortName);
    }
  }

  return {
    routes: [...byName.values()].sort((a, b) => a.route.localeCompare(b.route)),
    warnings,
  };
}