Skip to content

Commit

Permalink
chore: Switch object for Map
Browse files Browse the repository at this point in the history
  • Loading branch information
ramedina86 committed Sep 5, 2024
1 parent 57a2cab commit 0e142ab
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/ui/src/core/navigation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
type ParsedHash = {
pageKey?: string;
routeVars: Record<string, string>;
routeVars: Map<string, string>; // Stored as Map to avoid injection e.g. prototype pollution
};

const hashRegex = /^((?<pageKey>[^/]*))?(\/(?<routeVars>.*))?$/;
Expand All @@ -9,22 +9,21 @@ const routeVarRegex = /^(?<key>[^=]+)=(?<value>.*)$/;
export function getParsedHash(): ParsedHash {
const docHash = document.location.hash.substring(1);
const hashMatchGroups = docHash.match(hashRegex)?.groups;

if (!hashMatchGroups) return { pageKey: undefined, routeVars: {} };

const routeVars: Record<string, string> = {};
const routeVars: Map<string, string> = new Map();
const pageKey = hashMatchGroups?.pageKey
? decodeURIComponent(hashMatchGroups.pageKey)
: undefined;

if (!hashMatchGroups) return { pageKey, routeVars };

const routeVarsSegments = hashMatchGroups.routeVars?.split("&") ?? [];
routeVarsSegments.forEach((routeVarSegment) => {
const matchGroups = routeVarSegment.match(routeVarRegex)?.groups;
if (!matchGroups) return;
const { key, value } = matchGroups;
const decodedKey = decodeURIComponent(key);
const decodedValue = decodeURIComponent(value);
routeVars[decodedKey] = decodedValue;
routeVars.set(decodedKey, decodedValue);
});

return { pageKey, routeVars };
Expand All @@ -37,9 +36,10 @@ function setHash(parsedHash: ParsedHash) {
if (pageKey) {
hash += `${encodeURIComponent(pageKey)}`;
}
if (Object.keys(routeVars).length > 0) {

if (routeVars.keys.length > 0) {
hash += "/";
hash += Object.entries(routeVars)
hash += Array.from(routeVars.entries())
.map(([key, value]) => {
// Vars set to null are excluded from the hash

Expand All @@ -63,6 +63,8 @@ export function changePageInHash(targetPageKey: string) {
export function changeRouteVarsInHash(targetRouteVars: Record<string, string>) {
const parsedHash = getParsedHash();
const routeVars = parsedHash?.routeVars ?? {};
parsedHash.routeVars = { ...routeVars, ...targetRouteVars };
parsedHash.routeVars = new Map(
Object.entries({ ...routeVars, ...targetRouteVars }),
);
setHash(parsedHash);
}
}

0 comments on commit 0e142ab

Please sign in to comment.