mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1// Regex from the go implementation
2// https://github.com/bluesky-social/indigo/blob/main/atproto/syntax/handle.go#L10
3const VALIDATE_REGEX =
4 /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/
5
6export function makeValidHandle(str: string): string {
7 if (str.length > 20) {
8 str = str.slice(0, 20)
9 }
10 str = str.toLowerCase()
11 return str.replace(/^[^a-z0-9]+/g, '').replace(/[^a-z0-9-]/g, '')
12}
13
14export function createFullHandle(name: string, domain: string): string {
15 name = (name || '').replace(/[.]+$/, '')
16 domain = (domain || '').replace(/^[.]+/, '')
17 return `${name}.${domain}`
18}
19
20export function isInvalidHandle(handle: string): boolean {
21 return handle === 'handle.invalid'
22}
23
24export function sanitizeHandle(handle: string, prefix = ''): string {
25 return isInvalidHandle(handle) ? '⚠Invalid Handle' : `${prefix}${handle}`
26}
27
28export interface IsValidHandle {
29 handleChars: boolean
30 hyphenStartOrEnd: boolean
31 frontLength: boolean
32 totalLength: boolean
33 overall: boolean
34}
35
36// More checks from https://github.com/bluesky-social/atproto/blob/main/packages/pds/src/handle/index.ts#L72
37export function validateHandle(str: string, userDomain: string): IsValidHandle {
38 const fullHandle = createFullHandle(str, userDomain)
39
40 const results = {
41 handleChars:
42 !str || (VALIDATE_REGEX.test(fullHandle) && !str.includes('.')),
43 hyphenStartOrEnd: !str.startsWith('-') && !str.endsWith('-'),
44 frontLength: str.length >= 3,
45 totalLength: fullHandle.length <= 253,
46 }
47
48 return {
49 ...results,
50 overall: !Object.values(results).includes(false),
51 }
52}