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

refactor(decodeURL): update to whatwg api #117

Merged
merged 1 commit into from
Nov 2, 2019
Merged
Changes from all commits
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
37 changes: 15 additions & 22 deletions lib/decode_url.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
'use strict';

// To be refactored to WHATWG URL API
// after support for Node 8 is dropped.
// url.format(WHATWG URL object) in Node 8 doesn't support port number

const { parse, format } = require('url');
const { URL } = require('url');
const { toUnicode } = require('./punycode');

const urlObj = (str) => {
try {
return new URL(str);
} catch (err) {
return str;
}
};

const safeDecodeURI = (str) => {
try {
return decodeURI(str);
Expand All @@ -16,24 +20,13 @@ const safeDecodeURI = (str) => {
};

const decodeURL = (str) => {
const parsed = parse(str);
if (parsed.protocol) {
const obj = Object.assign({}, {
auth: parsed.auth,
protocol: parsed.protocol,
host: toUnicode(parsed.host),
pathname: safeDecodeURI(parsed.pathname)
});

if (parsed.hash) {
Object.assign(obj, { hash: safeDecodeURI(parsed.hash) });
}

if (parsed.search) {
Object.assign(obj, { search: safeDecodeURI(parsed.search) });
}
const parsed = urlObj(str);
if (typeof parsed === 'object') {
if (parsed.origin === 'null') return str;

return format(obj);
// TODO: refactor to `url.format()` once Node 8 is dropped
const url = parsed.toString().replace(parsed.hostname, toUnicode(parsed.hostname));
return safeDecodeURI(url);
}

return safeDecodeURI(str);
Expand Down