| 49 | } |
| 50 | |
| 51 | function normalize (strArray) { |
| 52 | const resultArray = []; |
| 53 | if (strArray.length === 0) { return ''; } |
| 54 | |
| 55 | if (typeof strArray[0] !== 'string') { |
| 56 | throw new TypeError('Url must be a string. Received ' + strArray[0]); |
| 57 | } |
| 58 | |
| 59 | // If the first part is a plain protocol, we combine it with the next part. |
| 60 | if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) { |
| 61 | strArray[0] = strArray.shift() + strArray[0]; |
| 62 | } |
| 63 | |
| 64 | // There must be two or three slashes in the file protocol, two slashes in anything else. |
| 65 | if (strArray[0].match(/^file:\/\/\//)) { |
| 66 | strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1:///'); |
| 67 | } else { |
| 68 | strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1://'); |
| 69 | } |
| 70 | |
| 71 | for (let i = 0; i < strArray.length; i++) { |
| 72 | let component = strArray[i]; |
| 73 | |
| 74 | if (typeof component !== 'string') { |
| 75 | throw new TypeError('Url must be a string. Received ' + component); |
| 76 | } |
| 77 | |
| 78 | if (component === '') { continue; } |
| 79 | |
| 80 | if (i > 0) { |
| 81 | // Removing the starting slashes for each component but the first. |
| 82 | component = component.replace(/^[\/]+/, ''); |
| 83 | } |
| 84 | if (i < strArray.length - 1) { |
| 85 | // Removing the ending slashes for each component but the last. |
| 86 | component = component.replace(/[\/]+$/, ''); |
| 87 | } else { |
| 88 | // For the last component we will combine multiple slashes to a single one. |
| 89 | component = component.replace(/[\/]+$/, '/'); |
| 90 | } |
| 91 | |
| 92 | resultArray.push(component); |
| 93 | |
| 94 | } |
| 95 | |
| 96 | let str = resultArray.join('/'); |
| 97 | // Each input component is now separated by a single slash except the possible first plain protocol part. |
| 98 | |
| 99 | // remove trailing slash before parameters or hash |
| 100 | str = str.replace(/\/(\?|&|#[^!])/g, '$1'); |
| 101 | |
| 102 | // replace ? in parameters with & |
| 103 | const parts = str.split('?'); |
| 104 | str = parts.shift() + (parts.length > 0 ? '?': '') + parts.join('&'); |
| 105 | |
| 106 | return str; |
| 107 | } |
| 108 | |