Skip to content

Commit

Permalink
[fix] Improve handling of empty port
Browse files Browse the repository at this point in the history
Make `Url.prototype.toString()` add a trailing colon to the host if the
hostname ends with a port number and the parsed port is empty.

Refs: d5c64791ef49
  • Loading branch information
lpinca committed Feb 21, 2022
1 parent 0071490 commit ce7a01f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var required = require('requires-port')
, controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
, CRHTLF = /[\n\r\t]/g
, slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
, port = /:\d+$/
, protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
, windowsDriveLetter = /^[a-zA-Z]:/;

Expand Down Expand Up @@ -452,7 +453,7 @@ function set(part, value, fn) {
case 'host':
url[part] = value;

if (/:\d+$/.test(value)) {
if (port.test(value)) {
value = value.split(':');
url.port = value.pop();
url.hostname = value.join(':');
Expand Down Expand Up @@ -560,7 +561,10 @@ function toString(stringify) {
// ends with a colon, then add back the trailing colon that was removed. This
// prevents an invalid URL from being transformed into a valid one.
//
if (host[host.length - 1] === ':') host += ':';
if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {
host += ':';
}

result += host + url.pathname;

query = 'object' === typeof url.query ? stringify(url.query) : url.query;
Expand Down
20 changes: 20 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,26 @@ describe('url-parse', function () {
assume(parsed.pathname).equals('/');
assume(parsed.origin).equals('http://example.com:');
assume(parsed.href).equals('http://example.com::/');

parsed = parse('http://example.com:8080:');

assume(parsed.protocol).equals('http:');
assume(parsed.port).equals('');
assume(parsed.host).equals('example.com:8080');
assume(parsed.hostname).equals('example.com:8080');
assume(parsed.pathname).equals('/');
assume(parsed.origin).equals('http://example.com:8080');
assume(parsed.href).equals('http://example.com:8080:/');

parsed = parse('http://example.com:8000:8080');

assume(parsed.protocol).equals('http:');
assume(parsed.port).equals('8080');
assume(parsed.host).equals('example.com:8000:8080');
assume(parsed.hostname).equals('example.com:8000');
assume(parsed.pathname).equals('/');
assume(parsed.origin).equals('http://example.com:8000:8080');
assume(parsed.href).equals('http://example.com:8000:8080/');
});

describe('origin', function () {
Expand Down

0 comments on commit ce7a01f

Please sign in to comment.