build-url-ts
Version:
A small library that builds a URL given its components
3 lines (2 loc) • 2.82 kB
JavaScript
(function(c,p){typeof exports=="object"&&typeof module!="undefined"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(c=typeof globalThis!="undefined"?globalThis:c||self,p(c.buildUrl={}))})(this,(function(c){"use strict";function p(t){return encodeURIComponent(t).replace(/'/g,"%27").replace(/`/g,"%60")}function g(t,i,n,u=!0){const r=s=>u?p(s):encodeURIComponent(s),e=[];for(const[s,a]of Object.entries(t)){if(a===void 0)continue;const o=r(i?s.toLowerCase():s);if(!Array.isArray(a)){e.push(`${o}=${r(b(a,i))}`);continue}const l=a.filter(d=>d!==void 0);if(l.length===0)continue;if(!n){const d=l.map(h=>b(h,i)).join(",");e.push(`${o}=${r(d)}`);continue}let f=n==="order_desc"?l.length-1:0;for(const d of l){const h=r(b(d,i));switch(n){case"array":e.push(`${o}[]=${h}`);break;case"order_asc":e.push(`${o}[${f++}]=${h}`);break;case"order_desc":e.push(`${o}[${f--}]=${h}`);break;default:e.push(`${o}=${h}`);break}}}return e.length>0?`?${e.join("&")}`:""}function b(t,i){if(t==null)return"";if(typeof t=="boolean")return t.toString();if(t===0)return"0";if(typeof t=="number"&&Number.isNaN(t))return"NaN";if(!t)return"";const n=t instanceof Date?t.toString():typeof t=="object"&&!Array.isArray(t)?JSON.stringify(t):String(t).trim();return i?n.toLowerCase():n}function y(t,i,n){const u=i!=null?i:"",r=String(t).trim(),e=n?r.toLowerCase():r;if(!e)return u;if(e==="/")return u.endsWith("/")?u:`${u}/`;const s=e.endsWith("/"),a=e.split("/").filter(f=>f.length>0).join("/"),o=s&&a?`${a}/`:a,l=u.replace(/\/+$/,"");return o?`${l}/${o}`:l}function $(t,i){const n=String(t).trim();if(!n)return"";const u=`#${n}`;return i?u.toLowerCase():u}function v(t){const i={},n=t.indexOf("#"),u=n===-1?"":t.substring(n+1),r=n===-1?t:t.substring(0,n),e=r.indexOf("?");if(e===-1)return{baseUrl:r,queryParams:i,hash:u};const s=r.substring(0,e),a=r.substring(e+1);for(const o of a.split("&")){if(!o)continue;const l=o.indexOf("="),f=l===-1?o:o.substring(0,l),d=l===-1?"":o.substring(l+1);f&&(i[decodeURIComponent(f)]=d?decodeURIComponent(d):"")}return{baseUrl:s,queryParams:i,hash:u}}function m(t,i){var n,u;const r=typeof t=="string"?v(t):null,e=t!==null&&typeof t=="object"?t:i;let s=(n=r==null?void 0:r.baseUrl)!=null?n:"";const a=[];e!=null&&e.path&&a.push(e.path),e!=null&&e.paths&&a.push(...e.paths);for(const f of a)s=y(f,s,e==null?void 0:e.lowerCase);const o={...r==null?void 0:r.queryParams,...e==null?void 0:e.queryParams};Object.keys(o).length>0&&(s+=g(o,e==null?void 0:e.lowerCase,e==null?void 0:e.disableCSV,!1));const l=(e==null?void 0:e.hash)!==void 0?e.hash:(u=r==null?void 0:r.hash)!=null?u:"";return l&&(s+=$(l,e==null?void 0:e.lowerCase)),s}c.appendPath=y,c.buildHash=$,c.buildQueryString=g,c.buildUrl=m,c.default=m,Object.defineProperty(c,"__esModule",{value:!0})}));
//# sourceMappingURL=index.umd.min.js.map