import { FluentBundle , FluentResource } from "@fluent/bundle/compat" ; import fs from "fs" ; import path from "path" ; import * as functions from "coral-framework/lib/i18n/functions" ; const commonPrefixes = [ "ui" , "common" , "framework" ] ; function decorateErrorWhenMissing ( bundle ) { const originalHasMessage = bundle . hasMessage ; const originalGetMessage = bundle . getMessage ; const missing = [ ] ; bundle . hasMessage = ( id ) => { const result = originalHasMessage . apply ( bundle , [ id ] ) ; if ( ! result ) { const msg = `${ bundle . locales } translation for key "${ id }" not found` ; console . error ( msg ) ; missing . push ( id ) ; } return true ; } ; bundle . getMessage = ( id ) => { if ( missing . includes ( id ) ) { return `Missing translation "${ id }"` ; } return originalGetMessage . apply ( bundle , [ id ] ) ; } ; return bundle ; } function createFluentBundle ( target , pathToLocale ) { const bundle = new FluentBundle ( "en-US" , { functions , useIsolating : false } ) ; const files = fs . readdirSync ( pathToLocale ) ; const prefixes = commonPrefixes . concat ( target ) ; files . forEach ( ( f ) => { prefixes . forEach ( ( prefix ) => { if ( f . startsWith ( prefix ) ) { bundle . addResource ( new FluentResource ( require ( path . resolve ( pathToLocale , f ) ) ) ) ; } } ) ; } ) ; return decorateErrorWhenMissing ( bundle ) ; } export default createFluentBundle ;