normalizeCollectionUri function
Normalizes a collection URI to a safe relative path.
Implementation
String normalizeCollectionUri(String value) {
if (value.isEmpty || value.contains('\u0000')) {
throw const FormatException('Collection URI must not be empty');
}
final normalizedSlashes = value.replaceAll('\\', '/');
final parsed = Uri.tryParse(normalizedSlashes);
if (parsed == null ||
parsed.hasScheme ||
parsed.hasAuthority ||
parsed.hasQuery ||
parsed.hasFragment ||
normalizedSlashes.startsWith('/') ||
RegExp(r'^[A-Za-z]:').hasMatch(normalizedSlashes)) {
throw FormatException('Collection URI must be relative: $value');
}
final rawSegments = normalizedSlashes.split('/');
if (rawSegments.any((segment) => segment.isEmpty)) {
throw FormatException('Collection URI has an empty component: $value');
}
final segments = <String>[];
for (final raw in rawSegments) {
late String decoded;
try {
decoded = Uri.decodeComponent(raw);
} on FormatException {
throw FormatException('Collection URI has invalid encoding: $value');
}
if (decoded.isEmpty ||
decoded == '.' ||
decoded == '..' ||
decoded.contains('/') ||
decoded.contains('\\')) {
throw FormatException('Collection URI is unsafe: $value');
}
segments.add(decoded);
}
return segments.join('/');
}