1 import { stripLeadingAndTrailingSlash, stripLeadingSlash } from '../helpers/string';
2 import { PUBLIC_PATH } from '../webpack.constants';
3 import { getValidatedLocalID } from './fork/validation';
5 export const getLocalIDPath = (u?: number) => (u === undefined ? undefined : `u/${u}`);
7 export const getLocalIDFromPathname = (pathname: string) => {
8 const maybeLocalID = pathname.match(/^\/?u\/([^/]+)\/?/)?.[1];
9 return getValidatedLocalID(maybeLocalID);
12 export const getBasename = (localID?: number) => {
13 const publicPathBase = stripLeadingAndTrailingSlash(PUBLIC_PATH);
14 if (localID === undefined) {
15 return publicPathBase ? `/${publicPathBase}` : undefined;
17 const localIDPathBase = getLocalIDPath(localID);
18 const joined = [publicPathBase, localIDPathBase].filter(Boolean).join('/');
19 return joined ? `/${joined}` : undefined;
22 export const stripLocalBasenameFromPathname = (pathname: string): string => {
23 const strippedPathname = stripLeadingSlash(pathname);
25 if (strippedPathname === 'u') {
29 const userPrefix = 'u/';
30 if (strippedPathname.startsWith(userPrefix)) {
31 // Strip out the 'u/' part
32 let value = stripLeadingSlash(strippedPathname.slice(userPrefix.length));
34 const localID = getLocalIDFromPathname(`${userPrefix}${value}`);
35 // If there is a valid local id, also strip out that
36 if (localID !== undefined) {
37 value = value.slice(`${localID}`.length);
40 // Keep stripping /u prefix if it exists
41 return stripLocalBasenameFromPathname(value);
44 return `/${strippedPathname}`;