All files / utils/i18n-normalizer i18n-normalizer.js

100% Statements 252/252
100% Branches 64/64
100% Functions 10/10
100% Lines 252/252

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 2531x 1x 1x 1x 1x 1x 59x 11x 11x 59x 2x 2x 46x 46x 1x 1x 1x 1x 1x 1x 41x 41x 41x 41x 59x 59x 13x 13x 13x 46x 46x 41x 41x 1x 1x 1x 1x 1x 1x 62x 62x 1x 1x 61x 62x 23x 23x 38x 62x 37x 37x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 70x 1x 1x 1x 1x 1x 69x 69x 69x 69x 70x 41x 2x 2x 2x 39x 39x 69x 69x 69x 1x 1x 1x 1x 1x 1x 1x 138x 1x 1x 1x 1x 1x 137x 138x 41x 41x 96x 138x 4x 4x 4x 4x 4x 92x 138x 1x 1x 91x 91x 91x 91x 91x 91x 91x 62x 62x 62x 91x 91x 91x 91x 69x 69x 69x 91x 91x 138x 90x 90x 90x 90x 90x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 40x 40x 40x 40x 40x 121x 121x 121x 121x 2x 2x 2x 2x 2x 2x 119x 119x 121x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 117x 117x 121x 5x 5x 5x 117x 117x 117x 40x 40x 40x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Checks if import path is valid
 * @param {string} path - target import path
 * @returns {{ valid: true } | { valid: false, error: string }} validation result
 */
export function validateImportPath (path) {
  if (typeof path !== 'string') {
    return { valid: false, error: `expected string instead of ${typeOf(path)}` }
  }
  if (path === '') {
    return { valid: false, error: 'cannot import empty path' }
  }
  return { valid: true }
}
 
/**
 * Normalize Import Array, eliminating invalid import paths
 * @param {string[]} importArray - import list
 * @returns {{ result: string[]; errors: ErrorList }} normalized data with a list of errors found
 */
function normalizeImportArray (importArray) {
  const result = []
  const errors = []
  for (const [index, importPath] of importArray.entries()) {
    const checkResult = validateImportPath(importPath)
    if (!checkResult.valid) {
      errors.push({ path: `.[${index}]`, message: `${checkResult.error}, ignoring import` })
      continue
    }
    result.push(importPath)
  }
  return { result, errors }
}
 
/**
 * Normalize Import string, into an normalized import array
 * @param {unknown} importVal - import data
 * @returns {{ result: string[]; errors: ErrorList }} normalized data with a list of errors found
 */
function normalizesImportValue (importVal) {
  if (importVal === '') {
    return { result: [], errors: [{ path: '', message: 'cannot import empty path, ignoring import' }] }
  }
 
  if (typeof importVal === 'string') {
    return { result: [importVal], errors: [] }
  }
 
  if (Array.isArray(importVal)) {
    return normalizeImportArray(importVal)
  }
 
  return {
    result: [],
    errors: [{ path: '', message: `expected string or string array (string[]) instead of ${typeOf(importVal)}` }],
  }
}
 
/**
 * Normalize Translations, eliminating invalid entries
 * @param {Translations} [translations] - translation data
 * @returns {{ result: Translations; errors: ErrorList }} normalized data with a list of errors found
 */
export function normalizeTranslations (translations) {
  if (!isPlainObject(translations)) {
    return {
      result: {},
      errors: [{ path: '', message: `expected a plain object instead of ${typeOf(translations)}` }],
    }
  }
 
  const validEntries = []
  const errors = []
 
  for (const [key, value] of Object.entries(translations)) {
    if (typeof value !== 'string') {
      errors.push({ path: propertyPath(key), message: `expected string instead of ${typeOf(value)}` })
      continue
    }
    validEntries.push([key, value])
  }
 
  return { result: Object.fromEntries(validEntries), errors }
}
 
/**
 * Normalizes the i18n definition model data
 * @param {I18nDefinition} data - target i18n definition to be normalized
 * @returns {{ result: NormalizedI18nDefinition; errors: ErrorList }} normalized i18n definition with a list of errors found
 */
export function normalizeI18nDefinition (data) {
  if (data === '') {
    return {
      result: { import: [], translations: {} },
      errors: [{ path: '', message: 'cannot import empty path, ignoring import' }],
    }
  }
 
  if (typeof data === 'string') {
    return { result: { import: [data], translations: {} }, errors: [] }
  }
 
  if (Array.isArray(data)) {
    const importArrayResult = normalizeImportArray(data)
    const errors = importArrayResult.errors
    const result = { import: importArrayResult.result, translations: {} }
    return { result, errors }
  }
 
  if (!isPlainObject(data)) {
    return { result: { import: [], translations: {} }, errors: [{ path: '', message: 'invalid type' }] }
  }
 
  const errors = []
  const hasImport = Object.hasOwn(data, 'import')
  const hasTranslations = Object.hasOwn(data, 'translations')
 
  const importValue = (() => {
    if (!hasImport) { return [] }
    const importValueResult = normalizesImportValue(data.import)
    errors.push(...importValueResult.errors.map(({ path, message }) => ({ path: mergePath('.import', path), message })))
    return importValueResult.result
  })()
 
  const translationsValue = (() => {
    if (!hasTranslations) { return {} }
    const translationsValueResult = normalizeTranslations(data.translations)
    errors.push(...translationsValueResult.errors.map(({ path, message }) => ({ path: mergePath('.translations', path), message })))
    return translationsValueResult.result
  })()
 
  if (hasImport || hasTranslations) {
    return {
      result: { import: importValue, translations: translationsValue },
      errors,
    }
  }
 
  return {
    result: { import: [], translations: {} },
    errors: [{ path: '', message: 'invalid object, the object must have "import" or "translations" keys' }],
  }
}
 
/**
 * Normalizes the i18n definition map
 * @param {I18nDefinitionMap} data - target i18n definition map to be normalized
 * @returns {NormalizationResult} normalized i18n definition map
 */
export function normalizeI18nDefinitionMap (data) {
  const errors = []
  const warnings = []
  const normalizedEntries = []
 
  for (const [localeString, i18nDefinition] of Object.entries(data)) {
    let locale
    try {
      locale = new Intl.Locale(localeString)
    } catch {
      errors.push({
        path: propertyPath(localeString),
        message: `invalid locale "${localeString}", it will be ignored`,
      })
      continue
    }
 
    const { baseName } = locale
    if (baseName !== localeString) {
      if (data[baseName]) {
        errors.push({
          path: propertyPath(localeString),
          message: `invalid locale "${localeString}", it also conflicts with correct locale "${baseName}", it will be ignored`,
        })
        continue
      }
 
      warnings.push({
        path: propertyPath(localeString),
        message: `invalid locale "${localeString}", fixed to locale "${baseName}"`,
      })
    }
 
    const normalizedResult = normalizeI18nDefinition(i18nDefinition)
    if (normalizedResult.errors.length) {
      const propPath = propertyPath(localeString)
      errors.push(...normalizedResult.errors.map(({ path, message }) => ({ path: mergePath(propPath, path), message })))
    }
 
    normalizedEntries.push([baseName, normalizedResult.result])
  }
 
  return { result: Object.fromEntries(normalizedEntries), warnings, errors }
}
 
/**
 * @param {unknown} targetVar - target object
 * @returns {string} type of object, returns "null" instead of "object" for null value
 */
const typeOf = (targetVar) => targetVar == null ? String(targetVar) : typeof targetVar
 
/**
 * @param {unknown} value - target object
 * @returns {value is Record<string, unknown>} true if plain object, false otherwise
 */
const isPlainObject = (value) => value?.constructor === Object
 
/**
 * Transforms property name to a valid property path so it can be used to chain with other properties
 * @param {string} propName - object property key
 * @returns {string} .`propName` for simple popery names, otherwise .[`propName`]
 */
const propertyPath = (propName) => /^[a-z][a-z\d]*$/i.test(propName) ? `.${propName}` : `.[${JSON.stringify(propName)}]`
 
/**
 * Merge 2 property paths
 * @param {string} prop1 - target property path
 * @param {string} prop2 - property path to merge with target
 * @returns {string} merged property path
 */
const mergePath = (prop1, prop2) => prop1 + (prop2 === '.' || prop2.startsWith('.[') ? prop2.slice(1) : prop2)
 
/// Type definitions
 
/** @typedef {Record<string, string>} Translations */
 
/**
 * @typedef {object} NormalizedI18nDefinition
 * @property {string[]} import - Additional files to import to the definition
 * @property {Translations} translations - translation map
 */
 
/** @typedef {{[locale: string]: NormalizedI18nDefinition}} NormalizedI18nDefinitionMap */
 
/** @typedef {string | string[] | { "import"?: string[] | string, translations: Translations} | { "import": string[] | string, translations?: Translations}} I18nDefinition */
 
/** @typedef {{[locale: string]: I18nDefinition}} I18nDefinitionMap */
 
/** @typedef {NormalizationIssue[]} ErrorList */
 
/**
 * @typedef {object} NormalizationIssue
 * An issue found when normalizing i18n configurations
 * @property {string} path - configuration path where the issue is located
 * @property {string} message - the issue description
 */
 
/**
 * @typedef {object} NormalizationResult
 * @property {NormalizedI18nDefinitionMap} result - normalized value
 * @property {ErrorList} warnings - errors found but automatically fixed (e.g. locale en-UK fixed to en-GB)
 * @property {ErrorList} errors - non-fixable errors found
 */