normalizeType static method

String normalizeType(
  1. String type
)

Normalizes a given service type.

References :

Implementation

static String normalizeType(String type) {
  List<String> parts = type.split('.');
  if (parts.length != 2) {
    return defaultServiceType;
  }

  // Extracts the second part.
  String secondPart = parts.last;

  // For applications using any transport protocol other than TCP, the second label is "_udp".
  if (secondPart != '_tcp') {
    secondPart = '_udp';
  }

  // Extracts the first part.
  String firstPart = parts.first;
  if (firstPart.startsWith('_')) {
    firstPart = firstPart.substring(1, firstPart.length);
  }

  // Service types MUST NOT begin with a hyphen.
  while (firstPart.startsWith('-')) {
    firstPart = firstPart.substring(1, firstPart.length);
  }

  // Service types MUST NOT end with a hyphen.
  while (firstPart.endsWith('-')) {
    firstPart = firstPart.substring(0, firstPart.length - 1);
  }

  // Hyphens must not be adjacent to other hyphens.
  firstPart = firstPart.replaceAll(RegExp(r'-+'), '-');

  // Service types MUST contain only US-ASCII [ANSI.X3.4-1986] letters 'A' - 'Z' and 'a' - 'z', digits '0' - '9', and hyphens ('-', ASCII 0x2D or decimal 45).
  firstPart = firstPart.replaceAll(RegExp(r'[^a-zA-Z0-9-]'), '');

  // Service types MUST be no more than 15 characters long.
  if (firstPart.length > 15) {
    firstPart = firstPart.substring(0, 15);
  }

  // Service types MUST be at least 1 character and MUST contain at least one letter ('A' - 'Z' or 'a' - 'z').
  if (firstPart.isEmpty || !firstPart.contains(RegExp(r'[A-Za-z]'))) {
    return defaultServiceType;
  }

  return '_$firstPart.$secondPart';
}