diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 06db175..0000000 --- a/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - '15' diff --git a/README.md b/README.md index 1e7e1d7..61cb395 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Learn more about [What is a URL](https://developer.mozilla.org/en-US/docs/Learn/ ## Supports -Both the browser and nodejs. +The browser, Nodejs, and Bun. ## Usage @@ -24,21 +24,10 @@ $ npm i --save extract-domain # Install bun https://bun.sh/ curl -fsSL https://bun.sh/install | bash - # tests bun test:watch ``` -### API - -- @param {Urls} urls ["https://www.google.com", "https://www.github.com"] or "https://www.google.com" -- @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk` -- @returns {Urls | Promise} Returns URL(s) or a promise of URL(s) if the PSL lib is being used - -```js -const res = extractDomain(urls, options); -``` - ES6 Import ```js @@ -54,19 +43,10 @@ const extractDomain = require('extract-domain'); Examples ```js -const urls = [ - 'https://www.npmjs.com/package/extract-domain', - 'http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument', - 'http://user:password@example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument', - 'https://npmjs.com/package/extract-domain', - 'ftp://example.org/resource.txt', - 'http://example.co.uk/', - 'this.is.my@email.com', -]; - -extractDomain(urls[0]); // npmjs.com - -extractDomain(urls); // [ 'npmjs.com', 'example.com', 'example.com', 'npmjs.com', 'example.org', 'co.uk', 'email.com' ] +extractDomain('https://www.npmjs.com/package/extract-domain'); // npmjs.com + +// Use the TLD flag, see the section beneath. Returns a promise. +extractDomain(urls, { tld: true }); ``` ## TLD support diff --git a/dist/extract-domain.cjs b/dist/extract-domain.cjs index 522318e..5797fed 100644 --- a/dist/extract-domain.cjs +++ b/dist/extract-domain.cjs @@ -1,2 +1,2 @@ -function r(r){if(r&&r.__esModule)return r;var e=Object.create(null);return r&&Object.keys(r).forEach(function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:function(){return r[t]}})}}),e.default=r,e}var e=["/",":","?","#"],t=[".","/","@"];function n(n,o){for(var i,u=0,f=0,s=0,a=n.length,c=0;a--&&++c&&!(u&&e.indexOf(n[c])>-1);)"."===n[c]&&(++u,f=c);for(i=c,c=f;c--;)if(-1!==t.indexOf(n[c])){s=c+1;break}if(0===s&&i>3)return n;if(s>0&&s<2)return"";if(o.tld){for(var l=0,p=["/","@"],v=f;v--;)if(p.indexOf(n[v])>-1){l=v+1;break}return Promise.resolve().then(function(){/*#__PURE__*/return r(require("psl"))}).then(function(r){return Promise.resolve(r.get(n.slice(l,i)))}).catch(function(r){throw console.error(r),Error("You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option")})}return n.slice(s,i)}module.exports=function(r,e){if(void 0===e&&(e={}),"string"==typeof r)return n(r,e);if(Array.isArray(r)){for(var t=[],o=r.length,i=0;i-1);)"."===o[u]&&(++s,a=u);for(i=u,u=a;u--;)if(-1!==t.indexOf(o[u])){c=u+1;break}if(0===c&&i>3)return o;if(c>0&&c<2)return"";if(n.tld){for(var f=0,p=["/","@"],d=a;d--;)if(p.indexOf(o[d])>-1){f=d+1;break}return Promise.resolve().then(function(){/*#__PURE__*/return e(require("psl"))}).then(function(e){return Promise.resolve(e.get(o.slice(f,i)))}).catch(function(e){throw console.error(e),Error("You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option")})}return o.slice(c,i)}(o,n);if(Array.isArray(o))return console.error("Sorry, it is no longer possible to pass an array of URLs. Please use a string instead.","I.e. extractDomain('https://www.google.com')."),o}catch(e){throw console.error(e),new TypeError("The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL")}}; //# sourceMappingURL=extract-domain.cjs.map diff --git a/dist/extract-domain.cjs.map b/dist/extract-domain.cjs.map index 6fe6932..d99dbb9 100644 --- a/dist/extract-domain.cjs.map +++ b/dist/extract-domain.cjs.map @@ -1 +1 @@ -{"version":3,"file":"extract-domain.cjs","sources":["../index.ts"],"sourcesContent":["function throwTypeError(): never {\n throw new TypeError('The given URL is not a string. Please verify your string|array.');\n}\n\nconst endings = ['/', ':', '?', '#'];\nconst starters = ['.', '/', '@'];\n\ntype Url = string;\ntype Urls = string | Array;\ntype ReturnUrls = Array | Array>;\ntype ReturnUrl = Url | Promise;\n\n/**\n * Options to extract domain.\n */\ntype GetDomainOptions = {\n tld?: boolean;\n};\n\n/**\n * @param {Url} url\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {ReturnUrl} Returns a URL or a promise of a URL if the PSL lib is being used\n */\nfunction getDomainFromUrl(url: Url, opts: GetDomainOptions): ReturnUrl {\n let domainInc: number = 0;\n let offsetDomain: number = 0;\n let offsetStartSlice: number = 0;\n let offsetPath: number = 0;\n let len: number = url.length;\n let i: number = 0;\n\n // Find end offset of domain\n while (len-- && ++i) {\n if (domainInc && endings.indexOf(url[i]) > -1) {\n break;\n }\n\n if (url[i] !== '.') {\n continue;\n }\n\n ++domainInc;\n\n offsetDomain = i;\n }\n\n offsetPath = i;\n\n i = offsetDomain;\n\n // Find offset before domain name.\n while (i--) {\n // Look for sub domain, protocol or basic auth\n if (starters.indexOf(url[i]) === -1) {\n continue;\n }\n\n offsetStartSlice = i + 1;\n\n break;\n }\n\n if (offsetStartSlice === 0 && offsetPath > 3) {\n return url;\n }\n\n if (offsetStartSlice > 0 && offsetStartSlice < 2) {\n return '';\n }\n\n // Very customized if statement for tlds\n if (opts.tld) {\n let offsetStart: number = 0;\n const starters: Array = ['/', '@'];\n let i: number = offsetDomain;\n\n while (i--) {\n if (starters.indexOf(url[i]) > -1) {\n offsetStart = i + 1;\n\n break;\n }\n }\n\n return import('psl')\n .then((psl) => Promise.resolve(psl.get(url.slice(offsetStart, offsetPath))))\n .catch((error) => {\n console.error(error);\n\n throw Error(\n 'You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option'\n );\n });\n }\n\n // Tried several approaches slicing a string. Can't get it any faster than this.\n return url.slice(offsetStartSlice, offsetPath);\n}\n\n/**\n * @param {Urls} urls [\"https://www.google.com\", \"https://www.github.com\"] or \"https://www.google.com\"\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {Urls | Promise} Return URLs or a promise of URLs if the PSL lib is being used\n */\nexport default function extractDomain(\n urls: Urls,\n opts: GetDomainOptions = {}\n): ReturnUrl | ReturnUrls | null {\n if (typeof urls === 'string') {\n return getDomainFromUrl(urls, opts);\n } else if (Array.isArray(urls)) {\n // lazy type checking (^o^)\n const extractedUrls: any = [];\n const len: number = urls.length;\n let i: number = 0;\n\n for (; i < len; i++) {\n const url = getDomainFromUrl(urls[i], opts);\n\n extractedUrls.push(url);\n }\n\n return extractedUrls;\n } else {\n throwTypeError();\n }\n}\n"],"names":["endings","starters","getDomainFromUrl","url","opts","offsetPath","domainInc","offsetDomain","offsetStartSlice","len","length","i","indexOf","tld","offsetStart","Promise","resolve","then","_interopNamespace","require","psl","get","slice","error","console","Error","urls","Array","isArray","extractedUrls","push","TypeError","throwTypeError"],"mappings":"8QAIA,IAAMA,EAAU,CAAC,IAAK,IAAK,IAAK,KAC1BC,EAAW,CAAC,IAAK,IAAK,KAmB5B,SAASC,EAAiBC,EAAUC,GAShC,IARA,IAGIC,EAHAC,EAAoB,EACpBC,EAAuB,EACvBC,EAA2B,EAE3BC,EAAcN,EAAIO,OAClBC,EAAY,EAGTF,OAAWE,KACVL,GAAaN,EAAQY,QAAQT,EAAIQ,KAAO,IAI7B,MAAXR,EAAIQ,OAINL,EAEFC,EAAeI,GAQnB,IALAN,EAAaM,EAEbA,EAAIJ,EAGGI,KAEH,IAAkC,IAA9BV,EAASW,QAAQT,EAAIQ,IAAzB,CAIAH,EAAmBG,EAAI,EAEvB,KAJC,CAOL,GAAyB,IAArBH,GAA0BH,EAAa,EACvC,OAAOF,EAGX,GAAIK,EAAmB,GAAKA,EAAmB,EAC3C,MAAO,GAIX,GAAIJ,EAAKS,IAAK,CAKV,IAJA,IAAIC,EAAsB,EACpBb,EAA0B,CAAC,IAAK,KAClCU,EAAYJ,EAETI,KACH,GAAIV,EAASW,QAAQT,EAAIQ,KAAO,EAAG,CAC/BG,EAAcH,EAAI,EAElB,KACH,CAGL,OAAaI,QAAAC,UAAAC,KAAA,wBAAA,OAAAC,EAAAC,QAAC,OAAM,GACfF,KAAK,SAACG,UAAQL,QAAQC,QAAQI,EAAIC,IAAIlB,EAAImB,MAAMR,EAAaT,IAAa,GAAC,MACrE,SAACkB,GAGJ,MAFAC,QAAQD,MAAMA,GAERE,MACF,uFAER,EACP,CAGD,OAAOtB,EAAImB,MAAMd,EAAkBH,EACvC,gBAOwB,SACpBqB,EACAtB,GAEA,YAFAA,IAAAA,EAAyB,CAAE,GAEP,iBAATsB,EACP,OAAOxB,EAAiBwB,EAAMtB,GAC3B,GAAIuB,MAAMC,QAAQF,GAAO,CAM5B,IAJA,IAAMG,EAAqB,GACrBpB,EAAciB,EAAKhB,OACrBC,EAAY,EAETA,EAAIF,EAAKE,IAAK,CACjB,IAAMR,EAAMD,EAAiBwB,EAAKf,GAAIP,GAEtCyB,EAAcC,KAAK3B,EACtB,CAED,OAAO0B,CACV,EA5HL,WACI,MAAM,IAAIE,UAAU,kEACxB,CA2HQC,EAER"} \ No newline at end of file +{"version":3,"file":"extract-domain.cjs","sources":["../index.ts"],"sourcesContent":["const endings = ['/', ':', '?', '#'];\nconst starters = ['.', '/', '@'];\n\ntype Url = string;\ntype ReturnUrl = Url | Promise;\n\n/**\n * Options to extract domain.\n */\ntype GetDomainOptions = {\n tld?: boolean;\n};\n\n/**\n * @param {Url} url\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {ReturnUrl} Returns a URL or a promise of a URL if the PSL lib is being used\n */\nfunction getDomainFromUrl(url: Url, opts: GetDomainOptions): ReturnUrl {\n let domainInc: number = 0;\n let offsetDomain: number = 0;\n let offsetStartSlice: number = 0;\n let offsetPath: number = 0;\n let len: number = url.length;\n let i: number = 0;\n\n // Find end offset of domain\n while (len-- && ++i) {\n if (domainInc && endings.indexOf(url[i]) > -1) {\n break;\n }\n\n if (url[i] !== '.') {\n continue;\n }\n\n ++domainInc;\n\n offsetDomain = i;\n }\n\n offsetPath = i;\n\n i = offsetDomain;\n\n // Find offset before domain name.\n while (i--) {\n // Look for sub domain, protocol or basic auth\n if (starters.indexOf(url[i]) === -1) {\n continue;\n }\n\n offsetStartSlice = i + 1;\n\n break;\n }\n\n if (offsetStartSlice === 0 && offsetPath > 3) {\n return url;\n }\n\n if (offsetStartSlice > 0 && offsetStartSlice < 2) {\n return '';\n }\n\n // Very customized if statement for tlds\n if (opts.tld) {\n let offsetStart: number = 0;\n const starters: Array = ['/', '@'];\n let i: number = offsetDomain;\n\n while (i--) {\n if (starters.indexOf(url[i]) > -1) {\n offsetStart = i + 1;\n\n break;\n }\n }\n\n return import('psl')\n .then((psl) => Promise.resolve(psl.get(url.slice(offsetStart, offsetPath))))\n .catch((error) => {\n console.error(error);\n\n throw Error(\n 'You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option'\n );\n });\n }\n\n // Tried several approaches slicing a string. Can't get it any faster than this.\n return url.slice(offsetStartSlice, offsetPath);\n}\n\n/**\n * @param {Url} url https://www.google.com\"\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {Url | Promise} Return URLs or a promise of URLs if the PSL lib is being used\n */\nexport default function extractDomain(\n url: Url,\n opts: GetDomainOptions = {}\n): ReturnUrl | undefined {\n try {\n if (typeof url === 'string') {\n return getDomainFromUrl(url, opts);\n } else if (Array.isArray(url)) {\n console.error(\n 'Sorry, it is no longer possible to pass an array of URLs. Please use a string instead.',\n \"I.e. extractDomain('https://www.google.com').\"\n );\n\n return url;\n }\n } catch (err) {\n console.error(err);\n\n throw new TypeError(\n 'The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL'\n );\n }\n}\n"],"names":["starters","url","opts","domainInc","offsetDomain","offsetStartSlice","len","length","i","endings","indexOf","offsetPath","tld","offsetStart","resolve","then","_interopNamespace","require","psl","get","slice","error","console","Error","getDomainFromUrl","Array","isArray","err"],"mappings":"8QAAA,MAAgB,CAAC,IAAK,IAAK,IAAK,KAC1BA,EAAW,CAAC,IAAK,IAAK,oBAkGJ,SACpBC,EACAC,YAAAA,IAAAA,EAAyB,CAAE,GAE3B,IACI,GAAmB,iBAAfD,EACA,OAvFZ,SAA0BA,EAAUC,GAShC,IARA,MAAIC,EAAoB,EACRC,EAAW,EACPC,EAAW,EAE3BC,EAAcL,EAAIM,OACjBC,EAAW,EAGTF,OAAWE,KACVL,GAAaM,EAAQC,QAAQT,EAAIO,KAAO,IAI7B,MAAXP,EAAIO,OAINL,EAEFC,EAAeI,GAQnB,IALAG,EAAaH,EAEbA,EAAIJ,EAGGI,KAEH,IAAkC,IAA9BR,EAASU,QAAQT,EAAIO,IAAzB,CAIAH,EAAmBG,EAAI,EAEvB,KAJC,CAOL,GAAyB,IAArBH,GAA0BM,EAAa,EACvC,SAGJ,GAAIN,EAAmB,GAAKA,EAAmB,EAC3C,MAAO,GAIX,GAAIH,EAAKU,IAAK,CAKV,IAJA,MAA0B,EACpBZ,EAA0B,CAAC,IAAK,OACtBI,EAETI,KACH,GAAIR,EAASU,QAAQT,EAAIO,KAAO,EAAG,CAC/BK,EAAcL,EAAI,EAElB,KACH,CAGL,eAAcM,UAAAC,KAAA,wBAAA,OAAAC,EAAAC,QAAA,OAAP,GACFF,KAAK,SAACG,GAAD,eAAiBJ,QAAQI,EAAIC,IAAIlB,EAAImB,MAAMP,EAAaF,IAAxD,GADH,MAEI,SAACU,GAGJ,MAFAC,QAAQD,MAAMA,GAEHE,MACP,uFAEP,EACR,CAGD,SAAWH,MAAMf,EAAkBM,EACtC,CAakCa,CAACvB,EAAKC,GACtBuB,GAAAA,MAAMC,QAAQzB,GAMrB,OALAqB,QAAQD,MACJ,yFACA,kDAWX,CANC,MAAOM,GAGL,MAFAL,QAAQD,MAAMM,GAER,cACF,mIAEP,CACJ"} \ No newline at end of file diff --git a/dist/extract-domain.modern.js b/dist/extract-domain.modern.js index 76ae8ee..2527f95 100644 --- a/dist/extract-domain.modern.js +++ b/dist/extract-domain.modern.js @@ -1,2 +1,2 @@ -const r=["/",":","?","#"],t=[".","/","@"];function e(e,n){let o=0,i=0,s=0,f=0,l=e.length,a=0;for(;l--&&++a&&!(o&&r.indexOf(e[a])>-1);)"."===e[a]&&(++o,i=a);for(f=a,a=i;a--;)if(-1!==t.indexOf(e[a])){s=a+1;break}if(0===s&&f>3)return e;if(s>0&&s<2)return"";if(n.tld){let r=0;const t=["/","@"];let n=i;for(;n--;)if(t.indexOf(e[n])>-1){r=n+1;break}return import("psl").then(t=>Promise.resolve(t.get(e.slice(r,f)))).catch(r=>{throw console.error(r),Error("You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option")})}return e.slice(s,f)}function n(r,t={}){if("string"==typeof r)return e(r,t);if(Array.isArray(r)){const n=[],o=r.length;let i=0;for(;i-1);)"."===o[c]&&(++n,s=c);for(a=c,c=s;c--;)if(-1!==e.indexOf(o[c])){i=c+1;break}if(0===i&&a>3)return o;if(i>0&&i<2)return"";if(t.tld){let r=0;const e=["/","@"];let t=s;for(;t--;)if(e.indexOf(o[t])>-1){r=t+1;break}return import("psl").then(e=>Promise.resolve(e.get(o.slice(r,a)))).catch(r=>{throw console.error(r),Error("You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option")})}return o.slice(i,a)}(o,t);if(Array.isArray(o))return console.error("Sorry, it is no longer possible to pass an array of URLs. Please use a string instead.","I.e. extractDomain('https://www.google.com')."),o}catch(r){throw console.error(r),new TypeError("The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL")}}export{o as default}; //# sourceMappingURL=extract-domain.modern.js.map diff --git a/dist/extract-domain.modern.js.map b/dist/extract-domain.modern.js.map index 16a2f1f..2f85ea5 100644 --- a/dist/extract-domain.modern.js.map +++ b/dist/extract-domain.modern.js.map @@ -1 +1 @@ -{"version":3,"file":"extract-domain.modern.js","sources":["../index.ts"],"sourcesContent":["function throwTypeError(): never {\n throw new TypeError('The given URL is not a string. Please verify your string|array.');\n}\n\nconst endings = ['/', ':', '?', '#'];\nconst starters = ['.', '/', '@'];\n\ntype Url = string;\ntype Urls = string | Array;\ntype ReturnUrls = Array | Array>;\ntype ReturnUrl = Url | Promise;\n\n/**\n * Options to extract domain.\n */\ntype GetDomainOptions = {\n tld?: boolean;\n};\n\n/**\n * @param {Url} url\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {ReturnUrl} Returns a URL or a promise of a URL if the PSL lib is being used\n */\nfunction getDomainFromUrl(url: Url, opts: GetDomainOptions): ReturnUrl {\n let domainInc: number = 0;\n let offsetDomain: number = 0;\n let offsetStartSlice: number = 0;\n let offsetPath: number = 0;\n let len: number = url.length;\n let i: number = 0;\n\n // Find end offset of domain\n while (len-- && ++i) {\n if (domainInc && endings.indexOf(url[i]) > -1) {\n break;\n }\n\n if (url[i] !== '.') {\n continue;\n }\n\n ++domainInc;\n\n offsetDomain = i;\n }\n\n offsetPath = i;\n\n i = offsetDomain;\n\n // Find offset before domain name.\n while (i--) {\n // Look for sub domain, protocol or basic auth\n if (starters.indexOf(url[i]) === -1) {\n continue;\n }\n\n offsetStartSlice = i + 1;\n\n break;\n }\n\n if (offsetStartSlice === 0 && offsetPath > 3) {\n return url;\n }\n\n if (offsetStartSlice > 0 && offsetStartSlice < 2) {\n return '';\n }\n\n // Very customized if statement for tlds\n if (opts.tld) {\n let offsetStart: number = 0;\n const starters: Array = ['/', '@'];\n let i: number = offsetDomain;\n\n while (i--) {\n if (starters.indexOf(url[i]) > -1) {\n offsetStart = i + 1;\n\n break;\n }\n }\n\n return import('psl')\n .then((psl) => Promise.resolve(psl.get(url.slice(offsetStart, offsetPath))))\n .catch((error) => {\n console.error(error);\n\n throw Error(\n 'You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option'\n );\n });\n }\n\n // Tried several approaches slicing a string. Can't get it any faster than this.\n return url.slice(offsetStartSlice, offsetPath);\n}\n\n/**\n * @param {Urls} urls [\"https://www.google.com\", \"https://www.github.com\"] or \"https://www.google.com\"\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {Urls | Promise} Return URLs or a promise of URLs if the PSL lib is being used\n */\nexport default function extractDomain(\n urls: Urls,\n opts: GetDomainOptions = {}\n): ReturnUrl | ReturnUrls | null {\n if (typeof urls === 'string') {\n return getDomainFromUrl(urls, opts);\n } else if (Array.isArray(urls)) {\n // lazy type checking (^o^)\n const extractedUrls: any = [];\n const len: number = urls.length;\n let i: number = 0;\n\n for (; i < len; i++) {\n const url = getDomainFromUrl(urls[i], opts);\n\n extractedUrls.push(url);\n }\n\n return extractedUrls;\n } else {\n throwTypeError();\n }\n}\n"],"names":["endings","starters","getDomainFromUrl","url","opts","domainInc","offsetDomain","offsetStartSlice","offsetPath","len","length","i","indexOf","tld","offsetStart","import","then","psl","Promise","resolve","get","slice","catch","error","console","Error","extractDomain","urls","Array","isArray","extractedUrls","push","TypeError","throwTypeError"],"mappings":"AAIA,MAAMA,EAAU,CAAC,IAAK,IAAK,IAAK,KAC1BC,EAAW,CAAC,IAAK,IAAK,KAmB5B,SAASC,EAAiBC,EAAUC,GAChC,IAAIC,EAAoB,EACpBC,EAAuB,EACvBC,EAA2B,EAC3BC,EAAqB,EACrBC,EAAcN,EAAIO,OAClBC,EAAY,EAGhB,KAAOF,OAAWE,KACVN,GAAaL,EAAQY,QAAQT,EAAIQ,KAAO,IAI7B,MAAXR,EAAIQ,OAINN,EAEFC,EAAeK,GAQnB,IALAH,EAAaG,EAEbA,EAAIL,EAGGK,KAEH,IAAkC,IAA9BV,EAASW,QAAQT,EAAIQ,IAAzB,CAIAJ,EAAmBI,EAAI,EAEvB,KAJC,CAOL,GAAyB,IAArBJ,GAA0BC,EAAa,EACvC,OAAOL,EAGX,GAAII,EAAmB,GAAKA,EAAmB,EAC3C,MAAO,GAIX,GAAIH,EAAKS,IAAK,CACV,IAAIC,EAAsB,EAC1B,MAAMb,EAA0B,CAAC,IAAK,KACtC,IAAIU,EAAYL,EAEhB,KAAOK,KACH,GAAIV,EAASW,QAAQT,EAAIQ,KAAO,EAAG,CAC/BG,EAAcH,EAAI,EAElB,KACH,CAGL,OAAOI,OAAO,OACTC,KAAMC,GAAQC,QAAQC,QAAQF,EAAIG,IAAIjB,EAAIkB,MAAMP,EAAaN,MAC7Dc,MAAOC,IAGJ,MAFAC,QAAQD,MAAMA,GAERE,MACF,uFAAsF,EAGrG,CAGD,OAAOtB,EAAIkB,MAAMd,EAAkBC,EACvC,CAOwB,SAAAkB,EACpBC,EACAvB,EAAyB,CAAA,GAEzB,GAAoB,iBAATuB,EACP,OAAOzB,EAAiByB,EAAMvB,GACvBwB,GAAAA,MAAMC,QAAQF,GAAO,CAE5B,MAAMG,EAAqB,GACrBrB,EAAckB,EAAKjB,OACzB,IAAIC,EAAY,EAEhB,KAAOA,EAAIF,EAAKE,IAAK,CACjB,MAAMR,EAAMD,EAAiByB,EAAKhB,GAAIP,GAEtC0B,EAAcC,KAAK5B,EACtB,CAED,OAAO2B,CACV,EA5HL,WACI,MAAM,IAAIE,UAAU,kEACxB,CA2HQC,EAER"} \ No newline at end of file +{"version":3,"file":"extract-domain.modern.js","sources":["../index.ts"],"sourcesContent":["const endings = ['/', ':', '?', '#'];\nconst starters = ['.', '/', '@'];\n\ntype Url = string;\ntype ReturnUrl = Url | Promise;\n\n/**\n * Options to extract domain.\n */\ntype GetDomainOptions = {\n tld?: boolean;\n};\n\n/**\n * @param {Url} url\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {ReturnUrl} Returns a URL or a promise of a URL if the PSL lib is being used\n */\nfunction getDomainFromUrl(url: Url, opts: GetDomainOptions): ReturnUrl {\n let domainInc: number = 0;\n let offsetDomain: number = 0;\n let offsetStartSlice: number = 0;\n let offsetPath: number = 0;\n let len: number = url.length;\n let i: number = 0;\n\n // Find end offset of domain\n while (len-- && ++i) {\n if (domainInc && endings.indexOf(url[i]) > -1) {\n break;\n }\n\n if (url[i] !== '.') {\n continue;\n }\n\n ++domainInc;\n\n offsetDomain = i;\n }\n\n offsetPath = i;\n\n i = offsetDomain;\n\n // Find offset before domain name.\n while (i--) {\n // Look for sub domain, protocol or basic auth\n if (starters.indexOf(url[i]) === -1) {\n continue;\n }\n\n offsetStartSlice = i + 1;\n\n break;\n }\n\n if (offsetStartSlice === 0 && offsetPath > 3) {\n return url;\n }\n\n if (offsetStartSlice > 0 && offsetStartSlice < 2) {\n return '';\n }\n\n // Very customized if statement for tlds\n if (opts.tld) {\n let offsetStart: number = 0;\n const starters: Array = ['/', '@'];\n let i: number = offsetDomain;\n\n while (i--) {\n if (starters.indexOf(url[i]) > -1) {\n offsetStart = i + 1;\n\n break;\n }\n }\n\n return import('psl')\n .then((psl) => Promise.resolve(psl.get(url.slice(offsetStart, offsetPath))))\n .catch((error) => {\n console.error(error);\n\n throw Error(\n 'You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option'\n );\n });\n }\n\n // Tried several approaches slicing a string. Can't get it any faster than this.\n return url.slice(offsetStartSlice, offsetPath);\n}\n\n/**\n * @param {Url} url https://www.google.com\"\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {Url | Promise} Return URLs or a promise of URLs if the PSL lib is being used\n */\nexport default function extractDomain(\n url: Url,\n opts: GetDomainOptions = {}\n): ReturnUrl | undefined {\n try {\n if (typeof url === 'string') {\n return getDomainFromUrl(url, opts);\n } else if (Array.isArray(url)) {\n console.error(\n 'Sorry, it is no longer possible to pass an array of URLs. Please use a string instead.',\n \"I.e. extractDomain('https://www.google.com').\"\n );\n\n return url;\n }\n } catch (err) {\n console.error(err);\n\n throw new TypeError(\n 'The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL'\n );\n }\n}\n"],"names":["extractDomain","url","opts","offsetDomain","offsetStartSlice","offsetPath","len","length","i","domainInc","endings","indexOf","starters","tld","offsetStart","then","psl","Promise","resolve","get","slice","catch","error","console","Array","isArray","err"],"mappings":"AAAA,QAAgB,CAAC,IAAK,IAAK,IAAK,OACf,CAAC,IAAK,IAAK,KAkGJ,SAAAA,EACpBC,EACAC,EAAyB,IAEzB,IACI,GAAmB,mBACf,OAvFZ,SAA0BD,EAAUC,GAChC,MAAwB,EACpBC,EAAuB,EACvBC,EAA2B,EACjBC,EAAW,EAClBC,EAAWL,EAAIM,OAClBC,EAAY,EAGhB,KAAOF,OAAWE,KACVC,GAAaC,EAAQC,QAAQV,EAAIO,KAAO,IAI7B,MAAXP,EAAIO,OAINC,EAEFN,EAAeK,GAQnB,IALAH,EAAaG,EAEbA,EAAIL,EAGGK,KAEH,IAAkC,IAA9BI,EAASD,QAAQV,EAAIO,IAAzB,CAIAJ,EAAmBI,EAAI,EAEvB,KAJC,CAOL,GAAyB,IAArBJ,GAA0BC,EAAa,EACvC,OAAOJ,EAGX,GAAIG,EAAmB,GAAKA,EAAmB,EAC3C,MAAO,GAIX,GAAIF,EAAKW,IAAK,CACV,IAAIC,EAAsB,EAC1B,MAAMF,EAA0B,CAAC,IAAK,KACtC,MAAgBT,EAEhB,KAAOK,KACH,GAAII,EAASD,QAAQV,EAAIO,KAAO,EAAG,CAC/BM,EAAcN,EAAI,EAElB,KACH,CAGL,cAAc,OACTO,KAAMC,GAAQC,QAAQC,QAAQF,EAAIG,IAAIlB,EAAImB,MAAMN,EAAaT,MAC7DgB,MAAOC,IAGJ,MAFAC,QAAQD,MAAMA,SAGV,uFADO,EAItB,CAGD,OAAUrB,EAACmB,MAAMhB,EAAkBC,EACtC,EAamCJ,EAAKC,MACtBsB,MAAMC,QAAQxB,GAMrB,OALAsB,QAAQD,MACJ,yFACA,iDAGGrB,CAQd,CANC,MAAOyB,GAGL,MAFAH,QAAQD,MAAMI,GAER,cACF,mIAEP,CACJ"} \ No newline at end of file diff --git a/dist/extract-domain.module.js b/dist/extract-domain.module.js index 4e3ed7c..4fe509a 100644 --- a/dist/extract-domain.module.js +++ b/dist/extract-domain.module.js @@ -1,2 +1,2 @@ -var r=["/",":","?","#"],e=[".","/","@"];function t(t,n){for(var i,o=0,f=0,s=0,a=t.length,u=0;a--&&++u&&!(o&&r.indexOf(t[u])>-1);)"."===t[u]&&(++o,f=u);for(i=u,u=f;u--;)if(-1!==e.indexOf(t[u])){s=u+1;break}if(0===s&&i>3)return t;if(s>0&&s<2)return"";if(n.tld){for(var l=0,c=["/","@"],p=f;p--;)if(c.indexOf(t[p])>-1){l=p+1;break}return import("psl").then(function(r){return Promise.resolve(r.get(t.slice(l,i)))}).catch(function(r){throw console.error(r),Error("You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option")})}return t.slice(s,i)}function n(r,e){if(void 0===e&&(e={}),"string"==typeof r)return t(r,e);if(Array.isArray(r)){for(var n=[],i=r.length,o=0;o-1);)"."===o[c]&&(++i,s=c);for(n=c,c=s;c--;)if(-1!==e.indexOf(o[c])){a=c+1;break}if(0===a&&n>3)return o;if(a>0&&a<2)return"";if(t.tld){for(var f=0,u=["/","@"],p=s;p--;)if(u.indexOf(o[p])>-1){f=p+1;break}return import("psl").then(function(r){return Promise.resolve(r.get(o.slice(f,n)))}).catch(function(r){throw console.error(r),Error("You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option")})}return o.slice(a,n)}(o,t);if(Array.isArray(o))return console.error("Sorry, it is no longer possible to pass an array of URLs. Please use a string instead.","I.e. extractDomain('https://www.google.com')."),o}catch(r){throw console.error(r),new TypeError("The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL")}}export{o as default}; //# sourceMappingURL=extract-domain.module.js.map diff --git a/dist/extract-domain.module.js.map b/dist/extract-domain.module.js.map index beacdc1..4e5404d 100644 --- a/dist/extract-domain.module.js.map +++ b/dist/extract-domain.module.js.map @@ -1 +1 @@ -{"version":3,"file":"extract-domain.module.js","sources":["../index.ts"],"sourcesContent":["function throwTypeError(): never {\n throw new TypeError('The given URL is not a string. Please verify your string|array.');\n}\n\nconst endings = ['/', ':', '?', '#'];\nconst starters = ['.', '/', '@'];\n\ntype Url = string;\ntype Urls = string | Array;\ntype ReturnUrls = Array | Array>;\ntype ReturnUrl = Url | Promise;\n\n/**\n * Options to extract domain.\n */\ntype GetDomainOptions = {\n tld?: boolean;\n};\n\n/**\n * @param {Url} url\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {ReturnUrl} Returns a URL or a promise of a URL if the PSL lib is being used\n */\nfunction getDomainFromUrl(url: Url, opts: GetDomainOptions): ReturnUrl {\n let domainInc: number = 0;\n let offsetDomain: number = 0;\n let offsetStartSlice: number = 0;\n let offsetPath: number = 0;\n let len: number = url.length;\n let i: number = 0;\n\n // Find end offset of domain\n while (len-- && ++i) {\n if (domainInc && endings.indexOf(url[i]) > -1) {\n break;\n }\n\n if (url[i] !== '.') {\n continue;\n }\n\n ++domainInc;\n\n offsetDomain = i;\n }\n\n offsetPath = i;\n\n i = offsetDomain;\n\n // Find offset before domain name.\n while (i--) {\n // Look for sub domain, protocol or basic auth\n if (starters.indexOf(url[i]) === -1) {\n continue;\n }\n\n offsetStartSlice = i + 1;\n\n break;\n }\n\n if (offsetStartSlice === 0 && offsetPath > 3) {\n return url;\n }\n\n if (offsetStartSlice > 0 && offsetStartSlice < 2) {\n return '';\n }\n\n // Very customized if statement for tlds\n if (opts.tld) {\n let offsetStart: number = 0;\n const starters: Array = ['/', '@'];\n let i: number = offsetDomain;\n\n while (i--) {\n if (starters.indexOf(url[i]) > -1) {\n offsetStart = i + 1;\n\n break;\n }\n }\n\n return import('psl')\n .then((psl) => Promise.resolve(psl.get(url.slice(offsetStart, offsetPath))))\n .catch((error) => {\n console.error(error);\n\n throw Error(\n 'You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option'\n );\n });\n }\n\n // Tried several approaches slicing a string. Can't get it any faster than this.\n return url.slice(offsetStartSlice, offsetPath);\n}\n\n/**\n * @param {Urls} urls [\"https://www.google.com\", \"https://www.github.com\"] or \"https://www.google.com\"\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {Urls | Promise} Return URLs or a promise of URLs if the PSL lib is being used\n */\nexport default function extractDomain(\n urls: Urls,\n opts: GetDomainOptions = {}\n): ReturnUrl | ReturnUrls | null {\n if (typeof urls === 'string') {\n return getDomainFromUrl(urls, opts);\n } else if (Array.isArray(urls)) {\n // lazy type checking (^o^)\n const extractedUrls: any = [];\n const len: number = urls.length;\n let i: number = 0;\n\n for (; i < len; i++) {\n const url = getDomainFromUrl(urls[i], opts);\n\n extractedUrls.push(url);\n }\n\n return extractedUrls;\n } else {\n throwTypeError();\n }\n}\n"],"names":["endings","starters","getDomainFromUrl","url","opts","offsetPath","domainInc","offsetDomain","offsetStartSlice","len","length","i","indexOf","tld","offsetStart","import","then","psl","Promise","resolve","get","slice","error","console","Error","extractDomain","urls","Array","isArray","extractedUrls","push","TypeError","throwTypeError"],"mappings":"AAIA,IAAMA,EAAU,CAAC,IAAK,IAAK,IAAK,KAC1BC,EAAW,CAAC,IAAK,IAAK,KAmB5B,SAASC,EAAiBC,EAAUC,GAShC,IARA,IAGIC,EAHAC,EAAoB,EACpBC,EAAuB,EACvBC,EAA2B,EAE3BC,EAAcN,EAAIO,OAClBC,EAAY,EAGTF,OAAWE,KACVL,GAAaN,EAAQY,QAAQT,EAAIQ,KAAO,IAI7B,MAAXR,EAAIQ,OAINL,EAEFC,EAAeI,GAQnB,IALAN,EAAaM,EAEbA,EAAIJ,EAGGI,KAEH,IAAkC,IAA9BV,EAASW,QAAQT,EAAIQ,IAAzB,CAIAH,EAAmBG,EAAI,EAEvB,KAJC,CAOL,GAAyB,IAArBH,GAA0BH,EAAa,EACvC,OAAOF,EAGX,GAAIK,EAAmB,GAAKA,EAAmB,EAC3C,MAAO,GAIX,GAAIJ,EAAKS,IAAK,CAKV,IAJA,IAAIC,EAAsB,EACpBb,EAA0B,CAAC,IAAK,KAClCU,EAAYJ,EAETI,KACH,GAAIV,EAASW,QAAQT,EAAIQ,KAAO,EAAG,CAC/BG,EAAcH,EAAI,EAElB,KACH,CAGL,OAAaI,OAAC,OACTC,KAAK,SAACC,UAAQC,QAAQC,QAAQF,EAAIG,IAAIjB,EAAIkB,MAAMP,EAAaT,IAAa,GAAC,MACrE,SAACiB,GAGJ,MAFAC,QAAQD,MAAMA,GAERE,MACF,uFAER,EACP,CAGD,OAAOrB,EAAIkB,MAAMb,EAAkBH,EACvC,CAOwB,SAAAoB,EACpBC,EACAtB,GAEA,YAFAA,IAAAA,EAAyB,CAAE,GAEP,iBAATsB,EACP,OAAOxB,EAAiBwB,EAAMtB,GAC3B,GAAIuB,MAAMC,QAAQF,GAAO,CAM5B,IAJA,IAAMG,EAAqB,GACrBpB,EAAciB,EAAKhB,OACrBC,EAAY,EAETA,EAAIF,EAAKE,IAAK,CACjB,IAAMR,EAAMD,EAAiBwB,EAAKf,GAAIP,GAEtCyB,EAAcC,KAAK3B,EACtB,CAED,OAAO0B,CACV,EA5HL,WACI,MAAM,IAAIE,UAAU,kEACxB,CA2HQC,EAER"} \ No newline at end of file +{"version":3,"file":"extract-domain.module.js","sources":["../index.ts"],"sourcesContent":["const endings = ['/', ':', '?', '#'];\nconst starters = ['.', '/', '@'];\n\ntype Url = string;\ntype ReturnUrl = Url | Promise;\n\n/**\n * Options to extract domain.\n */\ntype GetDomainOptions = {\n tld?: boolean;\n};\n\n/**\n * @param {Url} url\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {ReturnUrl} Returns a URL or a promise of a URL if the PSL lib is being used\n */\nfunction getDomainFromUrl(url: Url, opts: GetDomainOptions): ReturnUrl {\n let domainInc: number = 0;\n let offsetDomain: number = 0;\n let offsetStartSlice: number = 0;\n let offsetPath: number = 0;\n let len: number = url.length;\n let i: number = 0;\n\n // Find end offset of domain\n while (len-- && ++i) {\n if (domainInc && endings.indexOf(url[i]) > -1) {\n break;\n }\n\n if (url[i] !== '.') {\n continue;\n }\n\n ++domainInc;\n\n offsetDomain = i;\n }\n\n offsetPath = i;\n\n i = offsetDomain;\n\n // Find offset before domain name.\n while (i--) {\n // Look for sub domain, protocol or basic auth\n if (starters.indexOf(url[i]) === -1) {\n continue;\n }\n\n offsetStartSlice = i + 1;\n\n break;\n }\n\n if (offsetStartSlice === 0 && offsetPath > 3) {\n return url;\n }\n\n if (offsetStartSlice > 0 && offsetStartSlice < 2) {\n return '';\n }\n\n // Very customized if statement for tlds\n if (opts.tld) {\n let offsetStart: number = 0;\n const starters: Array = ['/', '@'];\n let i: number = offsetDomain;\n\n while (i--) {\n if (starters.indexOf(url[i]) > -1) {\n offsetStart = i + 1;\n\n break;\n }\n }\n\n return import('psl')\n .then((psl) => Promise.resolve(psl.get(url.slice(offsetStart, offsetPath))))\n .catch((error) => {\n console.error(error);\n\n throw Error(\n 'You must install psl library (https://www.npmjs.com/package/psl) to use `tld` option'\n );\n });\n }\n\n // Tried several approaches slicing a string. Can't get it any faster than this.\n return url.slice(offsetStartSlice, offsetPath);\n}\n\n/**\n * @param {Url} url https://www.google.com\"\n * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk`\n * @returns {Url | Promise} Return URLs or a promise of URLs if the PSL lib is being used\n */\nexport default function extractDomain(\n url: Url,\n opts: GetDomainOptions = {}\n): ReturnUrl | undefined {\n try {\n if (typeof url === 'string') {\n return getDomainFromUrl(url, opts);\n } else if (Array.isArray(url)) {\n console.error(\n 'Sorry, it is no longer possible to pass an array of URLs. Please use a string instead.',\n \"I.e. extractDomain('https://www.google.com').\"\n );\n\n return url;\n }\n } catch (err) {\n console.error(err);\n\n throw new TypeError(\n 'The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL'\n );\n }\n}\n"],"names":["starters","url","opts","domainInc","offsetDomain","offsetStartSlice","len","length","i","endings","indexOf","offsetPath","tld","offsetStart","then","psl","resolve","get","slice","error","console","Error","getDomainFromUrl","Array","isArray","err"],"mappings":"AAAA,MAAgB,CAAC,IAAK,IAAK,IAAK,KAC1BA,EAAW,CAAC,IAAK,IAAK,KAkGJ,WACpBC,EACAC,YAAAA,IAAAA,EAAyB,CAAE,GAE3B,IACI,GAAmB,iBAAfD,EACA,OAvFZ,SAA0BA,EAAUC,GAShC,IARA,MAAIC,EAAoB,EACRC,EAAW,EACPC,EAAW,EAE3BC,EAAcL,EAAIM,OACjBC,EAAW,EAGTF,OAAWE,KACVL,GAAaM,EAAQC,QAAQT,EAAIO,KAAO,IAI7B,MAAXP,EAAIO,OAINL,EAEFC,EAAeI,GAQnB,IALAG,EAAaH,EAEbA,EAAIJ,EAGGI,KAEH,IAAkC,IAA9BR,EAASU,QAAQT,EAAIO,IAAzB,CAIAH,EAAmBG,EAAI,EAEvB,KAJC,CAOL,GAAyB,IAArBH,GAA0BM,EAAa,EACvC,SAGJ,GAAIN,EAAmB,GAAKA,EAAmB,EAC3C,MAAO,GAIX,GAAIH,EAAKU,IAAK,CAKV,IAJA,MAA0B,EACpBZ,EAA0B,CAAC,IAAK,OACtBI,EAETI,KACH,GAAIR,EAASU,QAAQT,EAAIO,KAAO,EAAG,CAC/BK,EAAcL,EAAI,EAElB,KACH,CAGL,cAAc,OACTM,KAAK,SAACC,GAAD,eAAiBC,QAAQD,EAAIE,IAAIhB,EAAIiB,MAAML,EAAaF,IAAxD,GADH,MAEI,SAACQ,GAGJ,MAFAC,QAAQD,MAAMA,GAEHE,MACP,uFAEP,EACR,CAGD,SAAWH,MAAMb,EAAkBM,EACtC,CAakCW,CAACrB,EAAKC,GACtBqB,GAAAA,MAAMC,QAAQvB,GAMrB,OALAmB,QAAQD,MACJ,yFACA,kDAWX,CANC,MAAOM,GAGL,MAFAL,QAAQD,MAAMM,GAER,cACF,mIAEP,CACJ"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index 0150739..73c19ca 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -1,6 +1,4 @@ type Url = string; -type Urls = string | Array; -type ReturnUrls = Array | Array>; type ReturnUrl = Url | Promise; /** * Options to extract domain. @@ -9,9 +7,9 @@ type GetDomainOptions = { tld?: boolean; }; /** - * @param {Urls} urls ["https://www.google.com", "https://www.github.com"] or "https://www.google.com" + * @param {Url} url https://www.google.com" * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk` - * @returns {Urls | Promise} Return URLs or a promise of URLs if the PSL lib is being used + * @returns {Url | Promise} Return URLs or a promise of URLs if the PSL lib is being used */ -export default function extractDomain(urls: Urls, opts?: GetDomainOptions): ReturnUrl | ReturnUrls | null; +export default function extractDomain(url: Url, opts?: GetDomainOptions): ReturnUrl | undefined; export {}; diff --git a/index.ts b/index.ts index 0ff7182..bcebc17 100644 --- a/index.ts +++ b/index.ts @@ -1,13 +1,7 @@ -function throwTypeError(): never { - throw new TypeError('The given URL is not a string. Please verify your string|array.'); -} - const endings = ['/', ':', '?', '#']; const starters = ['.', '/', '@']; type Url = string; -type Urls = string | Array; -type ReturnUrls = Array | Array>; type ReturnUrl = Url | Promise; /** @@ -99,30 +93,30 @@ function getDomainFromUrl(url: Url, opts: GetDomainOptions): ReturnUrl { } /** - * @param {Urls} urls ["https://www.google.com", "https://www.github.com"] or "https://www.google.com" + * @param {Url} url https://www.google.com" * @param {GetDomainOptions} opts `{ tld: true }` permit to get Top Level Domain like `*.co.uk` - * @returns {Urls | Promise} Return URLs or a promise of URLs if the PSL lib is being used + * @returns {Url | Promise} Return URLs or a promise of URLs if the PSL lib is being used */ export default function extractDomain( - urls: Urls, + url: Url, opts: GetDomainOptions = {} -): ReturnUrl | ReturnUrls | null { - if (typeof urls === 'string') { - return getDomainFromUrl(urls, opts); - } else if (Array.isArray(urls)) { - // lazy type checking (^o^) - const extractedUrls: any = []; - const len: number = urls.length; - let i: number = 0; - - for (; i < len; i++) { - const url = getDomainFromUrl(urls[i], opts); - - extractedUrls.push(url); +): ReturnUrl | undefined { + try { + if (typeof url === 'string') { + return getDomainFromUrl(url, opts); + } else if (Array.isArray(url)) { + console.error( + 'Sorry, it is no longer possible to pass an array of URLs. Please use a string instead.', + "I.e. extractDomain('https://www.google.com')." + ); + + return url; } + } catch (err) { + console.error(err); - return extractedUrls; - } else { - throwTypeError(); + throw new TypeError( + 'The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL' + ); } } diff --git a/package-lock.json b/package-lock.json index 96d2419..62168ba 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "extract-domain", - "version": "4.1.4", + "version": "4.1.5", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "extract-domain", - "version": "4.1.4", + "version": "4.1.5", "license": "MIT", "devDependencies": { "@types/psl": "^1.1.0", diff --git a/package.json b/package.json index 5d87d5e..ce937b8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "extract-domain", - "version": "4.1.5", - "description": "Extract domain name from URL", + "version": "5.0.0", + "description": "Extract domain name from a URL", "type": "module", "source": "index.ts", "exports": { @@ -11,6 +11,7 @@ }, "main": "./dist/extract-domain.cjs", "module": "./dist/extract-domain.module.js", + "types": "./dist/index.d.ts", "author": "Bjarne Oeverli", "license": "MIT", "scripts": { @@ -38,7 +39,8 @@ "string", "url", "browser", - "node" + "node", + "bun" ], "devDependencies": { "@types/psl": "^1.1.0", diff --git a/tests/index.test.js b/tests/index.test.js index 43d7a9c..6cd89c3 100644 --- a/tests/index.test.js +++ b/tests/index.test.js @@ -17,6 +17,8 @@ const urls = [ 'this.is.my@email.com', 'test@something.com', 'http://www.example.co.uk/', + 'www.npmjs.com/a/b', + 'https://bjarne.oever.li/this/is/a/path.html?with=query&and=fragment#andHash', ]; const expected = [ @@ -27,8 +29,12 @@ const expected = [ 'email.com', 'something.com', 'co.uk', + 'oever.li', ]; +const typeErrorException = + 'The given string is not a valid URL. https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL'; + test('should return the domain if it already has been extracted', () => { assert.strictEqual(extractDomain('example.com'), 'example.com'); }); @@ -40,16 +46,18 @@ test('should extract given domain from url', () => { assert.strictEqual(extractDomain(urls[8]), expected[0]); assert.strictEqual(extractDomain(urls[10]), expected[4]); assert.strictEqual(extractDomain(urls[12]), expected[6]); -}); - -test('should extract given domain from an array of urls', () => { - const domains = extractDomain(urls); - - domains.map((domain) => assert(expected.indexOf(domain) > -1)); + assert.strictEqual(extractDomain(urls[13]), expected[0]); + assert.strictEqual(extractDomain(urls[14]), expected[7]); }); test('should return empty string if it is not a url', () => { - assert.strictEqual(extractDomain('/i.am/just.astring//7test'), ''); + try { + extractDomain('/i.am/just.astring//7test'); + } catch (e) { + assert.strictEqual(e.name, 'TypeError'); + + assert.strictEqual(e.message, typeErrorException); + } }); test('should throw syntax error exception if the argument is not string nor array', () => { @@ -58,10 +66,7 @@ test('should throw syntax error exception if the argument is not string nor arra } catch (e) { assert.strictEqual(e.name, 'TypeError'); - assert.strictEqual( - e.message, - 'The given URL is not a string. Please verify your string|array.' - ); + assert.strictEqual(e.message, typeErrorException); } }); @@ -71,10 +76,7 @@ test('should throw syntax error exception if the array value is not a string', ( } catch (e) { assert.strictEqual(e.name, 'TypeError'); - assert.strictEqual( - e.message, - 'The given URL is not a string. Please verify your string|array.' - ); + assert.strictEqual(e.message, typeErrorException); } });