domainToAscii function
Converts a domain name to its Punycode-encoded ASCII representation.
If validate is true (default), the function enforces RFC 1034 and
RFC 5890 rules:
- Label length between 1 and 63 characters.
- Total domain length not exceeding 253 characters.
- Labels must not start or end with a hyphen.
- Labels must not have hyphens in 3rd and 4th positions unless starting with 'xn--'.
- Labels must only contain LDH (Letter-Digit-Hyphen) characters.
Implementation
String domainToAscii(String domain, {bool validate = true}) {
final labels = _splitBySeparators(domain);
final encodedLabels = <String>[];
for (final label in labels) {
if (_isAscii(label)) {
encodedLabels.add(label.toLowerCase());
} else {
final encoded = punycode.encode(label.toLowerCase());
encodedLabels.add('xn--$encoded');
}
}
final result = encodedLabels.join('.');
if (validate) {
_validateDomain(result, encodedLabels);
}
return result;
}