More flexible `decodeStandardRoute`

This commit is contained in:
Tony Garnock-Jones 2024-03-28 12:36:13 +01:00
parent f105736694
commit 8ce11ddb12
1 changed files with 12 additions and 2 deletions

View File

@ -20,6 +20,7 @@ import {
decode,
fromJS,
isEmbedded,
parse,
stringify,
underlying,
Embeddable,
@ -434,10 +435,19 @@ export function unpackStandardRoute<R extends Embeddable>(route: E.StandardRoute
});
}
// We support a couple of variations here: a string containing Base64-encoded machine-oriented
// Preserves, or a string containing text-syntax Preserves.
export function decodeStandardRoute(s: string): G.Route | null {
try {
const route = E.toStandardRoute<Ref>(decode(
Bytes.fromBase64(s.replace(/[^-_+/A-Za-z0-9=]/g, ''))));
let routeValue: AnyValue;
// A valid text-syntax representation of a StandardRoute must start with
// either '[' or '<', neither of which is valid Base64.
if (s[0] === '[' || s[0] === '<') {
routeValue = parse(s);
} else {
routeValue = decode(Bytes.fromBase64(s.replace(/[^-_+/A-Za-z0-9=]/g, '')));
}
const route = E.toStandardRoute(routeValue);
return route === void 0 ? null : unpackStandardRoute(route);
} catch (e) {
console.error('Decoding standard route:', e);