import base from 'base-x' ; import * as _ from 'lodash' ; interface Codec { encode ( buffer ) : string ; decode ( s ) : Buffer ; bytesForLength ( n ) : number ; padChar ( ) : string ; } function createCharset ( s ) { const groups = s . match ( /^([Aa0]+)([\+-][^\+-]+)?([\+-][^\+-]+)?$/ ) ; if ( ! groups ) { throw new Error ( `Invalid encode parameter "${ s }"` ) ; } let chars = '' ; for ( const t of groups [ 1 ] ) { switch ( t ) { case '0' : chars += '0123456789' ; break ; case 'A' : chars += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ; break ; case 'a' : chars += 'abcdefghijklmnopqrstuvwxyz' ; break ; default : throw new Error ( `Invalid encoding type "${ t }" in "${ s }"` ) ; } } for ( let i = 2 ; i < groups . length ; i ++ ) { const g = groups [ i ] ; if ( g && g [ 0 ] === '-' ) { for ( const c of _ . tail ( g ) ) { chars = chars . split ( c ) . join ( '' ) ; } } if ( g && g [ 0 ] === '+' ) { for ( const c of _ . tail ( g ) ) { chars += c ; } } } return _ . uniq ( chars ) . join ( '' ) ; } function codec ( charset ) { const chars = createCharset ( charset ) ; const anyBase = < Codec > < any > base ( chars ) ; anyBase . bytesForLength = ( n ) => Math . ceil ( Math . log2 ( chars . length ) * n / 8 ) ; anyBase . padChar = ( ) => chars [ 0 ] ; return anyBase ; } export { Codec , createCharset , codec } ;