UNPKG

url-normalize

Version:

Normalize URLs to a standardized form. HTTPS by default, flexible configuration, custom protocols, domain extraction, humazing URL, and punycode support. Both CJS & ESM modules available.

2 lines (1 loc) 2.48 kB
var d=Object.defineProperty;var c=(t,r)=>d(t,"name",{value:r,configurable:!0});import{toUnicode as w}from"punycode";const g={auth:!1,customProtocol:!1,defaultProtocol:"https",fragment:!0,index:!0,port:!0,protocol:!0,search:!0,sortSearch:!0,textFragment:!1,unicode:!1,www:!1},n=c(t=>{try{return t()}catch{return null}},"canFail"),l=c((t,r)=>{if(r={...g,...r},t=t.trim(),!/^[a-z0-9.+-]*:\/\//i.test(t)){if(/^[a-z0-9.+-]*:[^0-9]/i.test(t))throw new Error("Unsupported protocol");t=`${r.defaultProtocol}://${t}`}const e=new URL(t);if(!r.customProtocol&&!["http:","https:",`${r.defaultProtocol}:`].includes(e.protocol)&&!r.forceProtocol)throw new Error("Invalid protocol");if(e.hostname=e.hostname.replace(/^\.*/,""),e.hostname=e.hostname.replace(/\.*$/,""),!r.www){const a=e.hostname.split(".");a.length===3&&a[0]==="www"&&(e.hostname=a.slice(1).join("."))}if(e.hostname.split(".").filter(a=>a!=="").length<2)throw new Error("Invalid domain");if(r.auth||(e.username="",e.password=""),r.port||(e.port=""),n(()=>e.pathname=decodeURI(e.pathname)),r.index||(e.pathname=e.pathname.replace(/\/index\.[a-z0-9]+$/i,"/")),e.pathname=e.pathname.replace(/(^|[^:])\/{2,}(?!\/)/g,"$1/"),!r.search)e.search="";else{if(e.search=e.search.replace(/&$/,""),e.search=e.search.replace(/&{2,}/,"&"),e.search=e.search.replace(/%20/g,"+"),r.filterSearch){const a=new URLSearchParams(e.search);for(const[i,u]of a.entries())r.filterSearch(i,u)||a.delete(i);e.search=a.toString()}r.sortSearch&&(e.searchParams.sort(),n(()=>e.search=decodeURIComponent(e.searchParams.toString())))}r.fragment?r.textFragment||(e.hash=e.hash.replace(/#?:~:text.*?$/i,"")):e.hash="";let o=e.toString();o.endsWith("/")&&!o.endsWith("/#/")&&(o=o.slice(0,-1));let h=e.protocol;if(r.forceProtocol){const a=new RegExp(`^${e.protocol}//`,"i");o=o.replace(a,`${r.forceProtocol}://`),h=`${r.forceProtocol}:`}if(!r.protocol){const a=new RegExp(`^${h}//`,"i");o=o.replace(a,"")}if(r.unicode){const a=w(e.hostname);o=o.replace(e.hostname,a)}return o},"urlNormalizeOrFail"),f=c((t,r)=>n(()=>l(t??"",r)),"urlNormalize"),x=c(t=>(r,s)=>f(r,{...t,...s}),"createUrlNormalize"),m=c(t=>{const r=l(t);return new URL(r).hostname},"extractDomainOrFail"),P=c(t=>n(()=>m(t??"")),"extractDomain"),p=c((t,r)=>l(t,{...r,protocol:!1}),"humanizeUrlOrFail"),$=c((t,r)=>n(()=>p(t??"",r)),"humanizeUrl");export{x as createUrlNormalize,P as extractDomain,m as extractDomainOrFail,$ as humanizeUrl,p as humanizeUrlOrFail,f as urlNormalize,l as urlNormalizeOrFail};