All files / coherent.js/packages/runtime/src/utils module-resolver.js

45.96% Statements 188/409
51.16% Branches 22/43
30.55% Functions 11/36
45.96% Lines 188/409

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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 4571x 1x 1x 1x       1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   1x 1x 7x 7x 7x 1x 1x   6x 6x 6x 6x 7x   1x 6x 6x 6x 6x 6x   6x 2x 6x 4x 6x   6x   6x   6x 6x   1x 6x 6x       6x 6x       6x 6x 2x 2x   4x 6x                 4x 4x   4x 4x 6x                   4x 4x 6x   1x               1x 2x 2x 2x 2x       2x       2x 2x 2x 2x 2x 2x 2x 2x 2x   1x 4x 4x 4x 4x 4x 1x 4x 4x 3x 4x 4x   4x 4x   4x 4x 4x   4x 4x   4x 4x   1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                 4x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   1x                         1x                         1x                         1x                         1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                   1x                                           1x 1x                       1x         1x       1x       1x 1x         1x         1x         1x         1x 1x                   1x 1x                   1x 1x 7x 7x   1x       1x             1x 1x                                             1x 1x                             1x   1x 1x       1x 1x   1x 1x       1x       1x      
/**
 * Module Resolver - Universal module path resolution and mapping
 * Handles different module systems and environments
 */
 
import { detectRuntime, RuntimeEnvironment } from './runtime-detector.js';
 
export class ModuleResolver {
  constructor(options = {}) {
    this.options = {
      baseUrl: '',
      paths: {},
      aliases: {},
      extensions: ['.js', '.mjs', '.cjs', '.ts', '.jsx', '.tsx'],
      moduleMap: {},
      cdnTemplate: 'https://unpkg.com/{name}@{version}/{path}',
      fallbacks: [],
      ...options
    };
    
    this.environment = detectRuntime();
    this.resolutionCache = new Map();
  }
 
  // Main resolution method
  resolve(modulePath, context = {}) {
    const cacheKey = this.getCacheKey(modulePath, context);
    
    if (this.resolutionCache.has(cacheKey)) {
      return this.resolutionCache.get(cacheKey);
    }
 
    const resolved = this.doResolve(modulePath, context);
    this.resolutionCache.set(cacheKey, resolved);
    
    return resolved;
  }
 
  doResolve(modulePath, context = {}) {
    // Handle different module path types
    const pathInfo = this.analyzePath(modulePath);
    
    switch (pathInfo.type) {
      case 'absolute':
        return this.resolveAbsolute(pathInfo, context);
      case 'relative':
        return this.resolveRelative(pathInfo, context);
      case 'package':
        return this.resolvePackage(pathInfo, context);
      case 'alias':
        return this.resolveAlias(pathInfo, context);
      case 'mapped':
        return this.resolveMapped(pathInfo, context);
      default:
        throw new Error(`Unable to resolve module: ${modulePath}`);
    }
  }
 
  analyzePath(modulePath) {
    // Absolute URLs
    if (/^https?:\/\//.test(modulePath)) {
      return { type: 'absolute', path: modulePath, original: modulePath };
    }
 
    // File protocol
    if (modulePath.startsWith('file://')) {
      return { type: 'absolute', path: modulePath, original: modulePath };
    }
 
    // Relative paths
    if (modulePath.startsWith('./') || modulePath.startsWith('../')) {
      return { type: 'relative', path: modulePath, original: modulePath };
    }
 
    // Check for mapped paths
    if (this.options.moduleMap[modulePath]) {
      return { 
        type: 'mapped', 
        path: modulePath, 
        mapped: this.options.moduleMap[modulePath],
        original: modulePath 
      };
    }
 
    // Check for aliases
    const aliasKey = Object.keys(this.options.aliases).find(alias => 
      modulePath.startsWith(`${alias  }/`) || modulePath === alias
    );
    
    if (aliasKey) {
      return { 
        type: 'alias', 
        path: modulePath, 
        alias: aliasKey,
        remainder: modulePath.slice(aliasKey.length + 1),
        original: modulePath 
      };
    }
 
    // Package imports
    return { type: 'package', path: modulePath, original: modulePath };
  }
 
  resolveAbsolute(pathInfo) {
    return {
      resolved: pathInfo.path,
      type: 'absolute',
      original: pathInfo.original
    };
  }
 
  resolveRelative(pathInfo, context) {
    let baseUrl = context.baseUrl || this.options.baseUrl || '';
    
    // Use current location in browsers
    if (this.environment === RuntimeEnvironment.BROWSER && !baseUrl) {
      baseUrl = window.location.href;
    }
 
    if (!baseUrl) {
      throw new Error(`Cannot resolve relative path "${pathInfo.path}" without base URL`);
    }
 
    const resolved = new URL(pathInfo.path, baseUrl).href;
    
    return {
      resolved,
      type: 'relative',
      original: pathInfo.original,
      baseUrl
    };
  }
 
  resolvePackage(pathInfo, context) {
    const packageName = this.parsePackageName(pathInfo.path);
    
    // Try different resolution strategies based on environment
    switch (this.environment) {
      case RuntimeEnvironment.BROWSER:
        return this.resolveBrowserPackage(packageName, context);
      
      case RuntimeEnvironment.NODE:
        return this.resolveNodePackage(packageName, context);
        
      case RuntimeEnvironment.DENO:
        return this.resolveDenoPackage(packageName, context);
        
      case RuntimeEnvironment.BUN:
        return this.resolveBunPackage(packageName, context);
        
      case RuntimeEnvironment.CLOUDFLARE:
      case RuntimeEnvironment.EDGE:
        return this.resolveEdgePackage(packageName, context);
        
      default:
        return this.resolveGenericPackage(packageName, context);
    }
  }
 
  parsePackageName(modulePath) {
    const parts = modulePath.split('/');
    
    if (modulePath.startsWith('@')) {
      // Scoped package
      return {
        name: `${parts[0]}/${parts[1]}`,
        subpath: parts.slice(2).join('/'),
        scope: parts[0],
        packageName: parts[1]
      };
    } else {
      // Regular package
      return {
        name: parts[0],
        subpath: parts.slice(1).join('/'),
        scope: null,
        packageName: parts[0]
      };
    }
  }
 
  resolveBrowserPackage(packageInfo, context) {
    // Try CDN resolution first
    const cdnUrl = this.resolveToCdn(packageInfo, context);
    
    return {
      resolved: cdnUrl,
      type: 'package',
      strategy: 'cdn',
      original: packageInfo.name + (packageInfo.subpath ? `/${  packageInfo.subpath}` : ''),
      package: packageInfo
    };
  }
 
  resolveNodePackage(packageInfo) {
    // Node.js resolution - return as-is for require/import to handle
    const modulePath = packageInfo.name + (packageInfo.subpath ? `/${  packageInfo.subpath}` : '');
    
    return {
      resolved: modulePath,
      type: 'package',
      strategy: 'node',
      original: modulePath,
      package: packageInfo
    };
  }
 
  resolveDenoPackage(packageInfo) {
    // Use npm: specifier for Deno
    const modulePath = `npm:${  packageInfo.name  }${packageInfo.subpath ? `/${  packageInfo.subpath}` : ''}`;
    
    return {
      resolved: modulePath,
      type: 'package',
      strategy: 'deno-npm',
      original: packageInfo.name + (packageInfo.subpath ? `/${  packageInfo.subpath}` : ''),
      package: packageInfo
    };
  }
 
  resolveBunPackage(packageInfo) {
    // Bun can handle npm packages directly
    const modulePath = packageInfo.name + (packageInfo.subpath ? `/${  packageInfo.subpath}` : '');
    
    return {
      resolved: modulePath,
      type: 'package',
      strategy: 'bun',
      original: modulePath,
      package: packageInfo
    };
  }
 
  resolveEdgePackage(packageInfo, context) {
    // Edge environments typically use CDN or bundled modules
    const cdnUrl = this.resolveToCdn(packageInfo, context);
    
    return {
      resolved: cdnUrl,
      type: 'package',
      strategy: 'edge-cdn',
      original: packageInfo.name + (packageInfo.subpath ? `/${  packageInfo.subpath}` : ''),
      package: packageInfo
    };
  }
 
  resolveGenericPackage(packageInfo) {
    // Generic fallback
    const modulePath = packageInfo.name + (packageInfo.subpath ? `/${  packageInfo.subpath}` : '');
    
    return {
      resolved: modulePath,
      type: 'package',
      strategy: 'generic',
      original: modulePath,
      package: packageInfo
    };
  }
 
  resolveToCdn(packageInfo, context = {}) {
    const version = context.version || 'latest';
    const subpath = packageInfo.subpath || 'dist/index.js';
    
    return this.options.cdnTemplate
      .replace('{name}', packageInfo.name)
      .replace('{version}', version)
      .replace('{path}', subpath);
  }
 
  resolveAlias(pathInfo, context) {
    const aliasTarget = this.options.aliases[pathInfo.alias];
    const resolvedPath = pathInfo.remainder 
      ? `${aliasTarget}/${pathInfo.remainder}`
      : aliasTarget;
    
    // Recursively resolve the aliased path
    const resolved = this.doResolve(resolvedPath, context);
    
    return {
      ...resolved,
      type: 'alias',
      alias: pathInfo.alias,
      aliasTarget,
      original: pathInfo.original
    };
  }
 
  resolveMapped(pathInfo, context) {
    const mapped = pathInfo.mapped;
    
    // If mapped value is a function, call it
    if (typeof mapped === 'function') {
      const result = mapped(pathInfo.path, context);
      return {
        resolved: result,
        type: 'mapped',
        original: pathInfo.original,
        mapFunction: true
      };
    }
    
    // Static mapping
    return {
      resolved: mapped,
      type: 'mapped',
      original: pathInfo.original
    };
  }
 
  // Path utilities
  addExtension(path, extensions = null) {
    const exts = extensions || this.options.extensions;
    
    // Already has extension
    if (exts.some(ext => path.endsWith(ext))) {
      return path;
    }
    
    // Add default extension
    return path + exts[0];
  }
 
  stripExtension(path) {
    const ext = this.options.extensions.find(e => path.endsWith(e));
    return ext ? path.slice(0, -ext.length) : path;
  }
 
  isRelative(path) {
    return path.startsWith('./') || path.startsWith('../');
  }
 
  isAbsolute(path) {
    return /^https?:\/\//.test(path) || path.startsWith('file://');
  }
 
  // Configuration methods
  addAlias(alias, target) {
    this.options.aliases[alias] = target;
    this.clearCache();
  }
 
  addMapping(from, to) {
    this.options.moduleMap[from] = to;
    this.clearCache();
  }
 
  setBaseUrl(baseUrl) {
    this.options.baseUrl = baseUrl;
    this.clearCache();
  }
 
  setCdnTemplate(template) {
    this.options.cdnTemplate = template;
    this.clearCache();
  }
 
  // Path patterns and wildcards
  resolvePattern(pattern, replacements = {}) {
    let resolved = pattern;
    
    Object.entries(replacements).forEach(([key, value]) => {
      resolved = resolved.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
    });
    
    return resolved;
  }
 
  // Batch resolution
  resolveAll(modulePaths, context = {}) {
    return modulePaths.map(path => {
      try {
        return { path, resolution: this.resolve(path, context), success: true };
      } catch (error) {
        return { path, error, success: false };
      }
    });
  }
 
  // Cache management
  getCacheKey(modulePath, context) {
    return `${modulePath}::${JSON.stringify(context)}`;
  }
 
  clearCache() {
    this.resolutionCache.clear();
  }
 
  getCacheStats() {
    return {
      size: this.resolutionCache.size,
      keys: Array.from(this.resolutionCache.keys())
    };
  }
 
  // Validation
  validateResolution(resolution) {
    if (!resolution || !resolution.resolved) {
      return { valid: false, error: 'Invalid resolution object' };
    }
    
    // Additional validation based on type
    switch (resolution.type) {
      case 'absolute':
        if (!this.isAbsolute(resolution.resolved)) {
          return { valid: false, error: 'Absolute resolution must be a valid URL' };
        }
        break;
      
      case 'relative':
        if (!resolution.baseUrl) {
          return { valid: false, error: 'Relative resolution must include baseUrl' };
        }
        break;
    }
    
    return { valid: true };
  }
 
  // Debug utilities
  debug(modulePath, context = {}) {
    const pathInfo = this.analyzePath(modulePath);
    const resolution = this.resolve(modulePath, context);
    const validation = this.validateResolution(resolution);
    
    return {
      input: modulePath,
      context,
      pathInfo,
      resolution,
      validation,
      environment: this.environment,
      options: this.options
    };
  }
}
 
// Factory function
export function createModuleResolver(options = {}) {
  return new ModuleResolver(options);
}
 
// Default resolver instance
export const moduleResolver = new ModuleResolver();
 
// Convenience functions
export function resolveModule(modulePath, context = {}) {
  return moduleResolver.resolve(modulePath, context);
}
 
export function addAlias(alias, target) {
  return moduleResolver.addAlias(alias, target);
}
 
export function addMapping(from, to) {
  return moduleResolver.addMapping(from, to);
}