relativizeIri function
Converts an absolute IRI to a relative form when possible.
Takes an iri and attempts to express it relative to the given baseIri.
This is useful for creating shorter, more readable RDF serializations.
Returns the original iri unchanged if:
baseIriis null or empty- The IRI cannot be safely relativized
- The IRIs have different schemes or authorities
- The relativization would violate the provided
optionsconstraints
Examples:
relativizeIri('http://example.org/path/file.txt', 'http://example.org/path/')
// Returns: 'file.txt'
relativizeIri('http://example.org/path#section', 'http://example.org/path#')
// Returns: '#section'
relativizeIri('https://other.org/file', 'http://example.org/')
// Returns: 'https://other.org/file' (unchanged - different domains)
// With conservative options
relativizeIri('http://example.org/other/file', 'http://example.org/path/',
options: IriRelativizationOptions.local())
// Returns: 'http://example.org/other/file' (unchanged - no cross-directory navigation)
The function guarantees that resolveIri(relativizeIri(iri, base, options: opts), base)
will return the original iri.
Implementation
String relativizeIri(String iri, String? baseIri,
{IriRelativizationOptions? options}) {
if (baseIri == null || baseIri.isEmpty) {
return iri;
}
final relativizationOptions =
options ?? const IriRelativizationOptions.full();
final result = _relativizeUri(iri, baseIri, relativizationOptions);
if (result == iri) {
return iri;
}
if (iri != resolveIri(result, baseIri)) {
// If the relativized IRI does not resolve back to the original, return original
return iri;
}
return result;
}