-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrictMnemonic.ts
More file actions
92 lines (82 loc) · 1.84 KB
/
Copy pathstrictMnemonic.ts
File metadata and controls
92 lines (82 loc) · 1.84 KB
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
import { ErrorCode } from "../errors/errorCodes.js";
export type StrictMnemonicParseSuccess = {
ok: true;
words: string[];
normalized_mnemonic: string;
};
export type StrictMnemonicParseFailure = {
ok: false;
error_code: ErrorCode.ERR_INVALID_MNEMONIC_FORMAT;
};
export type StrictMnemonicParseResult =
| StrictMnemonicParseSuccess
| StrictMnemonicParseFailure;
const isNfkd = (text: string): boolean => text.normalize("NFKD") === text;
const isLowercaseAsciiWord = (word: string): boolean => /^[a-z]+$/.test(word);
const parseWordsFromString = (text: string): string[] | null => {
if (text.length === 0) {
return null;
}
if (!isNfkd(text)) {
return null;
}
const words = text.split(" ");
if (words.some((word) => word.length === 0)) {
return null;
}
if (words.join(" ") !== text) {
return null;
}
if (!words.every(isLowercaseAsciiWord)) {
return null;
}
return words;
};
const parseWordsFromList = (value: unknown[]): string[] | null => {
if (value.length === 0) {
return null;
}
const words: string[] = [];
for (const item of value) {
if (typeof item !== "string") {
return null;
}
if (item.length === 0) {
return null;
}
if (/\s/u.test(item)) {
return null;
}
if (!isLowercaseAsciiWord(item)) {
return null;
}
words.push(item);
}
const normalized = words.join(" ");
const stringWords = parseWordsFromString(normalized);
if (!stringWords) {
return null;
}
return words;
};
export const parseMnemonicWordsStrict = (
input: string | string[],
): StrictMnemonicParseResult => {
const words =
typeof input === "string"
? parseWordsFromString(input)
: Array.isArray(input)
? parseWordsFromList(input)
: null;
if (!words) {
return {
ok: false,
error_code: ErrorCode.ERR_INVALID_MNEMONIC_FORMAT,
};
}
return {
ok: true,
words,
normalized_mnemonic: words.join(" "),
};
};