Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

1.8 KB
Raw Blame
import { access } from 'node:fs/promises';

import type { Plugin } from 'vite';

type Platform = 'web' | 'mobile' | 'desktop' | 'auth';

/**
 * Resolves platform-specific file variants by suffix priority:
 *   1. `.vite`    β€” Vite-specific override (highest)
 *   2. `.mobile`  β€” mobile build only
 *   ∞. fallback   β€” original file
 *
 * Example: importing `./locale.ts` on a mobile build tries
 *   locale.vite.ts β†’ locale.mobile.ts β†’ locale.ts
 */
export function vitePlatformResolve(platform?: Platform): Plugin {
  const suffixes: string[] = [];
  if (platform) suffixes.push(`.${platform}`);
  suffixes.push('.vite');
  const EXT_RE = /\.(ts|tsx|js|jsx)$/;
  const PLATFORM_RE = /\.(?:vite|web|mobile|desktop|auth)\.(?:ts|tsx|js|jsx)$/;

  return {
    enforce: 'pre',
    name: 'vite-platform-resolve',
    async resolveId(source, importer, options) {
      if (!importer || importer.includes('node_modules')) return null;

      const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
      if (!resolved) return null;

      const id = resolved.id.split('?')[0];

      const extMatch = id.match(EXT_RE);
      if (!extMatch) return null;

      // Already a platform-specific file β€” skip to avoid infinite loop
      if (PLATFORM_RE.test(id)) return null;

      const basePath = id.slice(0, -extMatch[0].length);
      const ext = extMatch[0];

      for (const suffix of suffixes) {
        const candidate = `${basePath}${suffix}${ext}`;
        // An override may reuse its base module; do not redirect it to itself.
        if (importer.split('?')[0].replaceAll('\\', '/') === candidate.replaceAll('\\', '/')) {
          return null;
        }
        try {
          await access(candidate);
          return candidate;
        } catch {
          // Not found, try next
        }
      }

      return null;
    },
  };
}