-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Url.js
80 lines (75 loc) · 2.15 KB
/
Url.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import {URL_WEBSITE_REGEX} from 'expensify-common/lib/Url';
/**
* Add / to the end of any URL if not present
* @param {String} url
* @returns {String}
*/
function addTrailingForwardSlash(url) {
if (!url.endsWith('/')) {
return `${url}/`;
}
return url;
}
/**
* Parse href to URL object
* @param {String} href
* @returns {Object}
*/
function getURLObject(href) {
const urlRegex = new RegExp(URL_WEBSITE_REGEX, 'gi');
const match = urlRegex.exec(href);
if (!match) {
return {
href: undefined,
protocol: undefined,
hostname: undefined,
path: undefined,
};
}
const baseUrl = match[0];
const protocol = match[1];
return {
href,
protocol,
hostname: baseUrl.replace(protocol, ''),
path: href.startsWith(baseUrl) ? href.replace(baseUrl, '') : '',
};
}
/**
* Determine if we should remove w3 from hostname
* E.g www.expensify.com should be the same as expensify.com
* @param {String} hostname
* @returns {Boolean}
*/
function shouldRemoveW3FromExpensifyUrl(hostname) {
// Since expensify.com.dev is accessible with and without www subdomain
if (hostname === 'www.expensify.com.dev') {
return true;
}
const parts = hostname.split('.').reverse();
const subDomain = parts[2];
return subDomain === 'www';
}
/**
* Determine if two urls have the same origin
* Just care about expensify url to avoid the second-level domain (www.example.co.uk)
* @param {String} url1
* @param {String} url2
* @returns {Boolean}
*/
function hasSameExpensifyOrigin(url1, url2) {
const host1 = getURLObject(url1).hostname;
const host2 = getURLObject(url2).hostname;
if (!host1 || !host2) {
return false;
}
const host1WithoutW3 = shouldRemoveW3FromExpensifyUrl(host1) ? host1.replace('www.', '') : host1;
const host2WithoutW3 = shouldRemoveW3FromExpensifyUrl(host2) ? host2.replace('www.', '') : host2;
return host1WithoutW3 === host2WithoutW3;
}
export {
// eslint-disable-next-line import/prefer-default-export
addTrailingForwardSlash,
hasSameExpensifyOrigin,
getURLObject,
};