Feature #22634
openAdd a WHATWG URL Standard parser to uri as URI::WHATWG_PARSER
Description
Abstract¶
I propose adding a parser that follows the WHATWG URL Standard to the uri library, as URI::WHATWG_PARSER. It is an option: URI::DEFAULT_PARSER stays RFC 3986, and the behavior of existing code does not change.
URI::WHATWG_PARSER.parse("HTTP://EXAMPLE.com:80/a/../b c")
#=> #<URI::HTTP http://example.com/b%20c>
URI::WHATWG_PARSER.parse("http://0x7f.1/")
#=> #<URI::HTTP http://127.0.0.1/>
URI::WHATWG_PARSER.parse("http://日本語.jp/").host
#=> "xn--wgv71a119e.jp"
URI::WHATWG_PARSER.join("http://example.com/a/b", "../c")
#=> #<URI::HTTP http://example.com/c>
# It can also replace the default parser for the whole process.
URI.parser = URI::WHATWG_PARSER
Background¶
Web browsers, and the specifications built on them (HTML, Fetch), parse URLs by the WHATWG URL Standard, which differs from RFC 3986 in many places. A Ruby program that handles URLs coming from the web (crawlers, link checkers, HTTP clients, web frameworks) often needs to parse them as a browser does:
| Input | URI::WHATWG_PARSER |
URI::RFC3986_PARSER |
|---|---|---|
"HTTP://EXAMPLE.com:80/a/../b c" |
http://example.com/b%20c |
URI::InvalidURIError |
"http://0x7f.1/" |
http://127.0.0.1/ |
http://0x7f.1/ |
"http://日本語.jp/" |
http://xn--wgv71a119e.jp/ |
URI::InvalidURIError |
"https:\\\\example.com\\a\\b" |
https://example.com/a/b |
URI::InvalidURIError |
" http://example.com/\t" |
http://example.com/ |
URI::InvalidURIError |
"http://EXAMPLE.com/" |
http://example.com/ |
URI::InvalidURIError |
In #21617 (IDN support), naruse wrote that "Introducing WHATWG Parser is an option" and "I agree the direction to adopt WHATWG Parser by uri library", while keeping that ticket to IDN. This ticket is for the WHATWG parser itself. Since the URL Standard includes IDNA (domain to ASCII, UTS #46), the parser also covers the IDN conversion that #21617 asks for, for URLs parsed with it.
Proposal¶
-
URI::WHATWG_Parser, a parser class with the interface thatURI.parser=expects (split,parse,join,regexp,extract,make_regexp,escape,unescape), andURI::WHATWG_PARSER, its instance. -
parsereturns instances of the existing classes:URI::HTTP,URI::HTTPS,URI::WS,URI::WSSandURI::Filefor their schemes, andURI::Genericfor the others. -
The components of a URI built by
URI::WHATWG_PARSERare those of the URL record, already serialized, and its setters follow the setters of the URL Standard. A value that the URL Standard ignores raisesURI::InvalidComponentError: -
==,merge,route_toandroute_fromof such a URI follow the URL Standard (equality by serialization, resolution while parsing).