All files / src/plugin vitek-resolve.ts

100% Statements 13/13
90% Branches 9/10
100% Functions 2/2
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                            27x         8x 8x 5x 5x 5x 5x 5x 4x 4x 4x        
/**
 * vitek:resolve — resolveId for relative imports in API files
 */
 
import type { Plugin } from 'vite';
import * as path from 'path';
import { pathToFileURL } from 'url';
import {
  normalizeImporterPath,
  resolveWithExtension,
} from '../adapters/vite/path-utils.js';
import type { PluginContext } from './context.js';
 
export function createResolvePlugin(ctx: PluginContext): Plugin {
  return {
    name: 'vitek:resolve',
    enforce: 'pre',
 
    resolveId(id, importer) {
      const root = ctx.root ?? process.cwd();
      if (!id.startsWith('.') || !importer) return null;
      const fullApiDir = path.resolve(root, ctx.apiDirOption);
      const importerPath = normalizeImporterPath(importer, root);
      const normalizedApiDir = path.resolve(fullApiDir);
      const normalizedImporter = path.resolve(importerPath);
      if (!normalizedImporter.startsWith(normalizedApiDir)) return null;
      const candidate = path.resolve(path.dirname(normalizedImporter), id);
      const resolved = resolveWithExtension(candidate);
      return resolved ? pathToFileURL(resolved).href : null;
    },
  };
}