Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement URL.from #28482

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions doc/api/url.md
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,45 @@ console.log(JSON.stringify(myURLs));
// Prints ["https://www.example.com/","https://test.example.org/"]
```

#### Static: URL.from(input)
viktor-ku marked this conversation as resolved.
Show resolved Hide resolved

* `input` {Object}
* `protocol` {string} any valid protocol. See [`url.protocol`][].
viktor-ku marked this conversation as resolved.
Show resolved Hide resolved
* `username` {string} any valid username. See [`url.username`][].
* `password` {string} any valid password. See [`url.password`][].
* `host` {string} any valid host. See [`url.host`][].
* `port` {string|number} any valid port. See [`url.port`][].
* `query` {string} is a string representing the query.
It gets parsed into a valid [`URLSearchParams`][] and used inside of
the [`url.href`][] and [`url.search`][].
* `path` {string[]} unlike [`url.pathname`][] it is not a string,
but rather an array representing the path.
* `fragment` {string} represents the fragment (part after `#`).

Creates a new `URL` instance based on the input object.

```js
const myURL = URL.from({
protocol: 'http',
username: 'root',
password: '1234',
port: '3000',
host: 'localhost',
path: ['main'],
fragment: 'app',
query: 'el=%3Cdiv%20%2F%3E',
});
// http://root:1234@localhost:3000/main?el=%3Cdiv%20%2F%3E#app
```

All properties are optional in case you want to build your url object
viktor-ku marked this conversation as resolved.
Show resolved Hide resolved
gradually.

```js
const myURL = URL.from();
// :
viktor-ku marked this conversation as resolved.
Show resolved Hide resolved
```

### Class: URLSearchParams
<!-- YAML
added:
Expand Down
58 changes: 58 additions & 0 deletions lib/internal/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,64 @@ class URL {
onParseError);
}

static from(input) {
viktor-ku marked this conversation as resolved.
Show resolved Hide resolved
input = input || {};

const {
username = '',
password = '',
host = null,
port = null,
query = null,
path = [],
fragment = null,
} = input;
const protocol = `${input.protocol || ''}:`;

let flags = 0;

if (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we instead wrote this more like we do in the existing codebase?:

    if (protocol === 'file:' ||
        protocol === 'https:' ||
        protocol === 'wss:' ||
        protocol === 'http:' ||
        protocol === 'ftp:' ||
        protocol === 'ws:' ||
        protocol === 'gopher:') {
      flags |= URL_FLAGS_SPECIAL;
    } else if (!host) {
      flags |= URL_FLAGS_CANNOT_BE_BASE;
    }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean? Where would be such example?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example of what it would look like? I provided one above.

protocol === 'file:' ||
protocol === 'https:' ||
protocol === 'wss:' ||
protocol === 'http:' ||
protocol === 'ftp:' ||
protocol === 'ws:' ||
protocol === 'gopher:'
)
flags |= URL_FLAGS_SPECIAL;
else if (!host)
flags |= URL_FLAGS_CANNOT_BE_BASE;

if (path.length)
flags |= URL_FLAGS_HAS_PATH;
if (host)
flags |= URL_FLAGS_HAS_HOST;
if (query)
flags |= URL_FLAGS_HAS_QUERY;
if (username)
flags |= URL_FLAGS_HAS_USERNAME;
if (password)
flags |= URL_FLAGS_HAS_PASSWORD;
if (fragment)
flags |= URL_FLAGS_HAS_FRAGMENT;

// TODO: maybe don't need to support this since it was used for
// the host setter hack at src/node_url.cc:1816
if (port == '-1') // eslint-disable-line eqeqeq
flags |= URL_FLAGS_IS_DEFAULT_SCHEME_PORT;

const self = Object.create(URL.prototype);
self[context] = new URLContext();

onParseComplete.apply(self, [
flags, protocol, username, password,
host, port, path, query, fragment
]);

return self;
}

get [special]() {
return (this[context].flags & URL_FLAGS_SPECIAL) !== 0;
}
Expand Down
91 changes: 91 additions & 0 deletions test/parallel/test-whatwg-url-from.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
'use strict';

require('../common');

const assert = require('assert');
const { URL } = require('url');

function t(expectedUrl, actualConfig) {
viktor-ku marked this conversation as resolved.
Show resolved Hide resolved
const url = URL.from(actualConfig);
assert.strictEqual(String(url), expectedUrl);
}

t(':', {});
t(':', []);
t(':', undefined);
viktor-ku marked this conversation as resolved.
Show resolved Hide resolved
t(':', null);
t(':', false);
t(':', 0);
t(':', 42);
t(':', new Date());
t(':', class {});
t(':', 'str');
t(':', new RegExp());
t(':', Symbol());
t('https://nodejs.org', new Proxy({}, {
get(target, p) {
if (p === 'protocol')
return 'https';
else if (p === 'host')
return 'nodejs.org';
}
}));

t('https://nodejs.org', {
protocol: 'https',
host: 'nodejs.org'
});

t('https://[email protected]', {
protocol: 'https',
host: 'site.com',
username: 'root'
});

t('https://:[email protected]', {
protocol: 'https',
host: 'site.com',
password: '1234'
});

t('https://root:[email protected]', {
protocol: 'https',
host: 'site.com',
username: 'root',
password: '1234'
});

t('https://site.com?a=1&b=2', {
protocol: 'https',
host: 'site.com',
query: 'a=1&b=2'
});

t('https://site.com/one/two', {
protocol: 'https',
host: 'site.com',
path: ['one', 'two']
});

t('http://localhost:3000', {
protocol: 'http',
host: 'localhost',
port: '3000',
});

t('http://localhost#fr', {
protocol: 'http',
host: 'localhost',
fragment: 'fr'
});

t('http://root:1234@localhost:3000/main?el=%3Cdiv%20%2F%3E#app', {
protocol: 'http',
username: 'root',
password: '1234',
port: '3000',
host: 'localhost',
path: ['main'],
fragment: 'app',
query: 'el=%3Cdiv%20%2F%3E'
});