2019-06-20 00:20:09 +02:00
|
|
|
import { LoggerInstance } from './Logger'
|
2019-03-04 13:30:34 +01:00
|
|
|
|
2019-03-11 22:46:27 +01:00
|
|
|
// Ox transformer
|
2019-03-04 13:30:34 +01:00
|
|
|
export const zeroX = (input: string) => zeroXTransformer(input, true)
|
|
|
|
export const noZeroX = (input: string) => zeroXTransformer(input, false)
|
2019-06-20 00:20:09 +02:00
|
|
|
export function zeroXTransformer(input: string = '', zeroOutput: boolean) {
|
|
|
|
const { valid, output } = inputMatch(
|
|
|
|
input,
|
|
|
|
/^(?:0x)*([a-f0-9]+)$/i,
|
|
|
|
'zeroXTransformer'
|
|
|
|
)
|
|
|
|
return (zeroOutput && valid ? '0x' : '') + output
|
2019-03-11 22:46:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// did:op: transformer
|
|
|
|
export const didPrefixed = (input: string) => didTransformer(input, true)
|
|
|
|
export const noDidPrefixed = (input: string) => didTransformer(input, false)
|
2019-06-20 00:20:09 +02:00
|
|
|
export function didTransformer(input: string = '', prefixOutput: boolean) {
|
|
|
|
const { valid, output } = inputMatch(
|
|
|
|
input,
|
|
|
|
/^(?:0x|did:op:)*([a-f0-9]{64})$/i,
|
|
|
|
'didTransformer'
|
|
|
|
)
|
|
|
|
return (prefixOutput && valid ? 'did:op:' : '') + output
|
2019-03-11 22:46:27 +01:00
|
|
|
}
|
2019-03-04 13:30:34 +01:00
|
|
|
|
2019-03-11 22:46:27 +01:00
|
|
|
// 0x + did:op: transformer
|
|
|
|
export const didZeroX = (input: string) => zeroX(didTransformer(input, false))
|
|
|
|
|
|
|
|
// Shared functions
|
2019-06-20 00:20:09 +02:00
|
|
|
function inputMatch(
|
|
|
|
input: string,
|
|
|
|
regexp: RegExp,
|
|
|
|
conversorName: string
|
|
|
|
): { valid: boolean; output: string } {
|
|
|
|
if (typeof input !== 'string') {
|
|
|
|
LoggerInstance.debug('Not input string:')
|
2019-03-19 14:27:28 +01:00
|
|
|
LoggerInstance.debug(input)
|
2019-06-20 00:20:09 +02:00
|
|
|
throw new Error(
|
|
|
|
`[${conversorName}] Expected string, input type: ${typeof input}`
|
|
|
|
)
|
2019-03-11 22:46:27 +01:00
|
|
|
}
|
2019-06-20 00:20:09 +02:00
|
|
|
const match = input.match(regexp)
|
|
|
|
if (!match) {
|
2019-03-19 14:27:28 +01:00
|
|
|
LoggerInstance.warn(`[${conversorName}] Input transformation failed.`)
|
2019-06-20 00:20:09 +02:00
|
|
|
return { valid: false, output: input }
|
2019-03-04 13:30:34 +01:00
|
|
|
}
|
2019-06-20 00:20:09 +02:00
|
|
|
return { valid: true, output: match[1] }
|
2019-03-04 13:30:34 +01:00
|
|
|
}
|