|
| 1 | +/*! |
| 2 | + * encodeurl |
| 3 | + * Copyright(c) 2016 Douglas Christopher Wilson |
| 4 | + * MIT Licensed |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") |
| 9 | + * and including invalid escape sequences. |
| 10 | + * @private |
| 11 | + */ |
| 12 | + |
| 13 | +const ENCODE_CHARS_REGEXP = |
| 14 | + /(?:[^\x21\x23-\x3B\x3D\x3F-\x5F\x61-\x7A\x7C\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g; |
| 15 | + |
| 16 | +/** |
| 17 | + * RegExp to match unmatched surrogate pair. |
| 18 | + * @private |
| 19 | + */ |
| 20 | + |
| 21 | +const UNMATCHED_SURROGATE_PAIR_REGEXP = |
| 22 | + /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g; |
| 23 | + |
| 24 | +/** |
| 25 | + * String to replace unmatched surrogate pair with. |
| 26 | + * @private |
| 27 | + */ |
| 28 | + |
| 29 | +const UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2'; |
| 30 | + |
| 31 | +/** |
| 32 | + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. |
| 33 | + * |
| 34 | + * This function will take an already-encoded URL and encode all the non-URL |
| 35 | + * code points. This function will not encode the "%" character unless it is |
| 36 | + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will |
| 37 | + * be encoded as `%25foo`). |
| 38 | + * |
| 39 | + * This encode is meant to be "safe" and does not throw errors. It will try as |
| 40 | + * hard as it can to properly encode the given URL, including replacing any raw, |
| 41 | + * unpaired surrogate pairs with the Unicode replacement character prior to |
| 42 | + * encoding. |
| 43 | + * |
| 44 | + * @param {string} url |
| 45 | + * @return {string} |
| 46 | + * @public |
| 47 | + */ |
| 48 | + |
| 49 | +export const encodeUrl = (url: string): string => |
| 50 | + String(url) |
| 51 | + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) |
| 52 | + .replace(ENCODE_CHARS_REGEXP, encodeURI); |
0 commit comments