resolveURLFromReference static method

Future<Uri?> resolveURLFromReference(
  1. ResourceContent? reference,
  2. String? url
)

Resolves an url using another ResourceContent as reference (base Uri).

Implementation

static Future<Uri?> resolveURLFromReference(
    ResourceContent? reference, String? url) async {
  if (url == null) return null;
  url = url.trim();

  if (url.startsWith(patternUrlInit)) {
    return Uri.parse(url);
  }

  if (url.startsWith(RegExp(r'^[\w-]'))) {
    url = './$url';
  }

  if (url.startsWith('./')) {
    var uri = reference != null ? await reference.uriResolved : null;
    uri ??= await ResourceContent.fromURI('./')!.uriResolved;

    var uriPath = '${Uri.decodeComponent(uri!.path)}/';

    var uriPathParts = uriPath.split('/');
    if (uriPath.endsWith('/')) uriPathParts.removeLast();

    String? resolvedPath;
    if (uriPathParts.isNotEmpty) {
      uriPathParts.removeLast();
      uriPathParts.add(url.substring(2));
      resolvedPath = uriPathParts.join('/');
    } else {
      resolvedPath = url.substring(2);
    }

    return Uri(
        scheme: uri.scheme,
        userInfo: uri.userInfo,
        host: uri.host,
        port: uri.port,
        path: resolvedPath);
  } else if (url.startsWith('/')) {
    var uri = reference != null ? await reference.uriResolved : null;
    uri ??= await ResourceContent.fromURI('./')!.uriResolved;

    return Uri(
        scheme: uri!.scheme,
        userInfo: uri.userInfo,
        host: uri.host,
        port: uri.port,
        path: url);
  }

  return Uri.parse(url);
}