UNPKG

@btc-vision/walletconnect

Version:

The OP_NET Wallet Connect library helps your dApp connect to any compatible wallet.

74 lines (73 loc) 2.53 kB
import { patternMap, patternRegExp } from './patterns'; const RE_EXTRACT_ERROR = new RegExp('^(.*?):\\s*(?:([^:]+):)?\\s*(.*?)\\s+at\\s(\\S+\\s\\()?\\S+\\d+:\\d+\\)?', 'm'); const _translation = (err, locale) => { switch (locale) { case 'en': return err['en'] || ''; case 'en-us': return err['en-US'] || ''; case 'fr': return err['fr'] || ''; case 'fr-ca': return err['fr-CA'] || ''; default: return ''; } }; const _errors = (err, locales) => { if (typeof err === 'string') { return err; } else { for (const locale of locales) { const translation = _translation(err, locale); if (translation) return translation; } return err['en']; } }; const _normalizeLocales = (locales) => { const _locales = locales.map((l) => l.toLowerCase().trim()); for (const locale of _locales) { const language = locale.split('-')[0]; if (!_locales.includes(language)) { _locales.push(language); } } return _locales; }; export const _e = (err, locales = ['en']) => { const [, , error] = _match_e(err.toString(), locales); return error; }; export const _match_e = (err, locales = ['en']) => { const normalizedLocales = _normalizeLocales(locales); const matches = RE_EXTRACT_ERROR.exec(err); const packageName = matches ? matches[2] : ''; let msg = matches ? matches[3] : err; const lookup = `${packageName}: ${msg}`.trim(); const lookupLower = lookup.toLowerCase(); for (const [orig, pattern, translation] of patternRegExp) { const placeHolders = pattern.exec(lookup); if (placeHolders) { msg = _errors(translation, normalizedLocales) || msg; for (let i = 0; i < placeHolders.length; i++) { const regex = new RegExp(`\\$${i}`, 'g'); msg = msg.replace(regex, placeHolders[i] ?? ''); } return [orig, pattern.source, msg]; } } for (const [orig, pattern, translation] of patternMap) { if (lookupLower == pattern) { return [orig, pattern, _errors(translation, normalizedLocales) || msg]; } } for (const [orig, pattern, translation] of patternMap) { if (lookupLower.includes(pattern)) { return [orig, pattern, _errors(translation, normalizedLocales) || msg]; } } return ['', '', msg]; };