resolveImageUrl static method

String resolveImageUrl(
  1. String imageUrl
)

Resolves an image URL or path into a full valid URI string.

Handles:

  • Full URLs with schemes (e.g. http://..., https://...)
  • Protocol-relative URLs (e.g. //cdn.example.com/...)
  • Full domains without scheme (e.g. cdn.example.com/..., res.cloudinary.com/...)
  • Relative paths with or without leading slashes (e.g. /images/..., images/..., pic.jpg)

Implementation

static String resolveImageUrl(String imageUrl) {
  final trimmed = imageUrl.trim();
  if (trimmed.isEmpty) return trimmed;

  final lower = trimmed.toLowerCase();

  // 1. Full URL with scheme (http:// or https://)
  if (lower.startsWith('http://') || lower.startsWith('https://')) {
    return trimmed;
  }

  // 2. Protocol-relative URL (//cdn.example.com/...)
  if (trimmed.startsWith('//')) {
    return 'https:$trimmed';
  }

  // 3. Domain without scheme (e.g., cdn.example.com/image.jpg)
  final firstSlash = trimmed.indexOf('/');
  if (firstSlash > 0) {
    final host = trimmed.substring(0, firstSlash);
    final domainRegex = RegExp(
      r'^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(:\d+)?$',
    );
    final ipRegex = RegExp(
      r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$',
    );
    if (domainRegex.hasMatch(host) ||
        ipRegex.hasMatch(host) ||
        host.startsWith('localhost')) {
      return 'https://$trimmed';
    }
  }

  // 4. Relative path: combine with coreKitInstance.imageBaseUrl
  var baseUrl = '';
  try {
    baseUrl = coreKitInstance.imageBaseUrl.trim();
  } catch (_) {
    baseUrl = '';
  }

  if (baseUrl.isEmpty) {
    return trimmed;
  }

  var cleanBase = baseUrl;
  while (cleanBase.endsWith('/')) {
    cleanBase = cleanBase.substring(0, cleanBase.length - 1);
  }
  var cleanPath = trimmed;
  while (cleanPath.startsWith('/')) {
    cleanPath = cleanPath.substring(1);
  }

  return cleanBase.isEmpty ? cleanPath : '$cleanBase/$cleanPath';
}