UNPKG

2.02 kBJavaScriptView Raw
1import { u8aToU8a } from '@polkadot/util';
2/** @internal */
3export function createDecode({ coder, ipfs }, validate) {
4 return (value, ipfsCompat) => {
5 validate(value, ipfsCompat);
6 return coder.decode(ipfs && ipfsCompat
7 ? value.substring(1)
8 : value);
9 };
10}
11/** @internal */
12export function createEncode({ coder, ipfs }) {
13 return (value, ipfsCompat) => {
14 const out = coder.encode(u8aToU8a(value));
15 return ipfs && ipfsCompat
16 ? `${ipfs}${out}`
17 : out;
18 };
19}
20/** @internal */
21export function createIs(validate) {
22 return (value, ipfsCompat) => {
23 try {
24 return validate(value, ipfsCompat);
25 }
26 catch {
27 return false;
28 }
29 };
30}
31/** @internal */
32export function createValidate({ chars, ipfs, type, withPadding }) {
33 return (value, ipfsCompat) => {
34 if (typeof value !== 'string') {
35 throw new Error(`Expected ${type} string input`);
36 }
37 else if (ipfs && ipfsCompat && !value.startsWith(ipfs)) {
38 throw new Error(`Expected ipfs-compatible ${type} to start with '${ipfs}'`);
39 }
40 for (let i = (ipfsCompat ? 1 : 0), count = value.length; i < count; i++) {
41 if (chars.includes(value[i])) {
42 // all ok, character found
43 }
44 else if (withPadding && value[i] === '=') {
45 if (i === count - 1) {
46 // last character, everything ok
47 }
48 else if (value[i + 1] === '=') {
49 // next one is also padding, sequence ok
50 }
51 else {
52 throw new Error(`Invalid ${type} padding sequence "${value[i]}${value[i + 1]}" at index ${i}`);
53 }
54 }
55 else {
56 throw new Error(`Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
57 }
58 }
59 return true;
60 };
61}