File size: 7,624 Bytes
edaa6b9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | //#region src/utils/url.ts
const splitPath = (path) => {
const paths = path.split("/");
if (paths[0] === "") paths.shift();
return paths;
};
const splitRoutingPath = (routePath) => {
const { groups, path } = extractGroupsFromPath(routePath);
const paths = splitPath(path);
return replaceGroupMarks(paths, groups);
};
const extractGroupsFromPath = (path) => {
const groups = [];
path = path.replace(/\{[^}]+\}/g, (match, index) => {
const mark = `@${index}`;
groups.push([mark, match]);
return mark;
});
return {
groups,
path
};
};
const replaceGroupMarks = (paths, groups) => {
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i];
for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
paths[j] = paths[j].replace(mark, groups[i][1]);
break;
}
}
return paths;
};
const patternCache = {};
const getPattern = (label, next) => {
if (label === "*") return "*";
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
if (match) {
const cacheKey = `${label}#${next}`;
if (!patternCache[cacheKey]) {
if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
cacheKey,
match[1],
new RegExp(`^${match[2]}(?=/${next})`)
] : [
label,
match[1],
new RegExp(`^${match[2]}$`)
];
else patternCache[cacheKey] = [
label,
match[1],
true
];
}
return patternCache[cacheKey];
}
return null;
};
const tryDecode = (str, decoder) => {
try {
return decoder(str);
} catch {
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
try {
return decoder(match);
} catch {
return match;
}
});
}
};
/**
* Try to apply decodeURI() to given string.
* If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.
* @param str The string to decode.
* @returns The decoded string that sometimes contains undecodable percent encoding.
* @example
* tryDecodeURI('Hello%20World') // 'Hello World'
* tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'
*/
const tryDecodeURI = (str) => tryDecode(str, decodeURI);
const decodeURIWithPreservedPercent = (value) => decodeURI(value.includes("%25") ? value.replace(/%25/g, "%2525") : value);
const getPath = (request) => {
const url = request.url;
const start = url.indexOf("/", url.indexOf(":") + 4);
let i = start;
for (; i < url.length; i++) {
const charCode = url.charCodeAt(i);
if (charCode === 37) {
const queryIndex = url.indexOf("?", i);
const hashIndex = url.indexOf("#", i);
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
const path = url.slice(start, end);
const decoded = tryDecode(path, decodeURIWithPreservedPercent);
if (/%(?![0-9A-Fa-f]{2})/.test(path)) {
const rewritten = new URL("http://localhost");
rewritten.pathname = decoded.replace(/[\\\t\n\r]/g, encodeURIComponent);
if (tryDecode(rewritten.pathname, decodeURIWithPreservedPercent) !== decoded) return tryDecode(path.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"), decodeURIWithPreservedPercent);
}
return decoded;
} else if (charCode === 63 || charCode === 35) break;
}
return url.slice(start, i);
};
/**
* @deprecated
* Use the `URL` API instead.
*/
const getQueryStrings = (url) => {
const queryIndex = url.indexOf("?", 8);
if (queryIndex === -1) return "";
const hashIndex = url.indexOf("#", 8);
return hashIndex === -1 ? url.slice(queryIndex) : queryIndex < hashIndex ? url.slice(queryIndex, hashIndex) : "";
};
const getPathNoStrict = (request) => {
const result = getPath(request);
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
};
/**
* Merge paths.
* @param {string[]} ...paths - The paths to merge.
* @returns {string} The merged path.
* @example
* mergePath('/api', '/users') // '/api/users'
* mergePath('/api/', '/users') // '/api/users'
* mergePath('/api', '/') // '/api'
* mergePath('/api/', '/') // '/api/'
*/
const mergePath = (base, sub, ...rest) => {
if (rest.length) sub = mergePath(sub, ...rest);
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
};
const checkOptionalParameter = (path) => {
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) return null;
const segments = path.split("/");
const results = [];
let basePath = "";
segments.forEach((segment) => {
if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
else if (/\:/.test(segment)) {
if (segment.charCodeAt(segment.length - 1) === 63) {
if (results.length === 0 && basePath === "") results.push("/");
else results.push(basePath);
const optionalSegment = segment.slice(0, -1);
basePath += "/" + optionalSegment;
results.push(basePath);
} else basePath += "/" + segment;
}
});
return results.filter((v, i, a) => a.indexOf(v) === i);
};
const tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
const _decodeURI = (value) => {
if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
return tryDecodeURIComponent(value);
};
const _getQueryParam = (url, key, multiple) => {
const hashIndex = url.indexOf("#", 8);
if (hashIndex !== -1) url = url.slice(0, hashIndex);
let encoded;
if (!multiple && key && !/[%+&=]/.test(key)) {
const queryIndex = url.indexOf("?", 8);
let keyIndex = queryIndex;
if (keyIndex === -1) return;
if (!url.startsWith(key, keyIndex + 1)) keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
while (keyIndex !== -1) {
const trailingKeyCode = url.charCodeAt(keyIndex + key.length + 1);
if (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {
if (keyIndex > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex))) break;
if (trailingKeyCode === 61) {
const valueIndex = keyIndex + key.length + 2;
const endIndex = url.indexOf("&", valueIndex);
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
}
return "";
}
keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
}
encoded = /[%+]/.test(url);
if (!encoded) return;
}
const results = Object.create(null);
encoded ??= /[%+]/.test(url);
let keyIndex = url.indexOf("?", 8);
while (keyIndex !== -1) {
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
let valueIndex = url.indexOf("=", keyIndex);
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
if (encoded) name = _decodeURI(name);
keyIndex = nextKeyIndex;
if (name === "") continue;
let value;
if (valueIndex === -1) value = "";
else {
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
if (encoded) value = _decodeURI(value);
}
if (multiple) {
if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
results[name].push(value);
} else results[name] ??= value;
}
return key ? results[key] : results;
};
const getQueryParam = _getQueryParam;
const getQueryParams = (url, key) => {
return _getQueryParam(url, key, true);
};
const decodeURIComponent_ = decodeURIComponent;
//#endregion
export { checkOptionalParameter, decodeURIComponent_, getPath, getPathNoStrict, getPattern, getQueryParam, getQueryParams, getQueryStrings, mergePath, splitPath, splitRoutingPath, tryDecode, tryDecodeURI, tryDecodeURIComponent };
|