diff --git a/src/services/url-parser.js b/src/services/url-parser.js index fa3ccd5..a253ed6 100644 --- a/src/services/url-parser.js +++ b/src/services/url-parser.js @@ -8,6 +8,31 @@ export function cleanUrl(url) { return matchesDomainName && matchesDomainName[1] ? matchesDomainName[1] : ""; } +function isAnIpAddressWithPort(address) { + return /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})$/.test(address); +} + +export function getSuggestions(url) { + const cleanedUrl = cleanUrl(url) || url; + const urlElements = cleanedUrl.split("."); + if (isAnIpAddressWithPort(cleanedUrl) || urlElements.length < 2) { + return []; + } + const baseName = urlElements[urlElements.length - 2]; + const tld = urlElements[urlElements.length - 1]; + return urlElements.reduceRight( + (accumulator, currentValue) => { + const index = urlElements.indexOf(currentValue); + if (index >= 0 && index < urlElements.length - 2) { + const lastValue = accumulator[accumulator.length - 1]; + accumulator.push(currentValue + "." + lastValue); + } + return accumulator; + }, + [baseName, `${baseName}.${tld}`] + ); +} + export function getSite() { return new Promise(resolve => { if ( diff --git a/test/unit/url-parser.js b/test/unit/url-parser.js index d3bb406..31f6173 100644 --- a/test/unit/url-parser.js +++ b/test/unit/url-parser.js @@ -1,7 +1,7 @@ import test from "ava"; import * as urlParser from "../../src/services/url-parser"; -test("getDomainName", t => { +test("cleanUrl", t => { t.is("lesspass.com", urlParser.cleanUrl("https://lesspass.com/#!/")); t.is("lesspass.com", urlParser.cleanUrl("https://lesspass.com/api/")); t.is("api.lesspass.com", urlParser.cleanUrl("https://api.lesspass.com/")); @@ -33,6 +33,30 @@ test("getDomainName", t => { t.is("", urlParser.cleanUrl("chrome://extensions/")); }); +test("getSuggestions", t => { + t.deepEqual( + ["bbc", "bbc.com", "www.bbc.com"], + urlParser.getSuggestions("https://www.bbc.com") + ); + t.deepEqual( + ["example", "example.org", "www.example.org"], + urlParser.getSuggestions("https://www.example.org/api/?offset=100&limit=10") + ); + t.deepEqual( + ["example", "example.org"], + urlParser.getSuggestions("https://example.org") + ); + t.deepEqual( + ["example", "example.org"], + urlParser.getSuggestions("example.org") + ); + t.deepEqual( + [], + urlParser.getSuggestions("https://192.168.1.1:10443/webapp/") + ); + t.deepEqual([], urlParser.getSuggestions("example")); +}); + test("getSite", t => { global.chrome = { tabs: {