import { MissingVariableError , UnknownVariableError } from './errors' ; import { Locale , PluralRules , SingleTranslation } from './types' ; export class InlangTextApi { #input : string ; #locale : Locale ; #translation : SingleTranslation | undefined ; #variableKeys : string [ ] ; #variables : Record < string , string | number | InlangTextApi > = { } ; #output : string ; constructor ( text , args ) { this . #input = text ; this . #translation = args . translation ; this . #locale = args . locale ; this . #variableKeys = text . match ( /{.*?}/g ) ?. map ( ( e ) => e . slice ( 1 , e . length - 1 ) ) ?? [ ] ; this . #output = args . translation ?? text ; } /**
     * Interpolates this.#variables into #this.output.
     *
     * Interpolation has to happen at the end of the `pipeline` and is therefore
     * not happening directly in `.variables()`.
     */ static #interpolate ( input , variables ) { let result = input ; for ( const variable in variables ) { result = result . replace ( `{${ variable }}` , variables [ variable ] . toString ( ) ) ; } return result ; } param variables returns throws throws variables ( this , variables ) { if ( variables === undefined ) { return this ; } const missingVariables = this . #variableKeys . filter ( ( key ) => variables [ key ] === undefined ) ; const unknownVariables = Object . keys ( variables ) . filter ( ( key ) => this . #variableKeys . includes ( key ) === false ) ; if ( missingVariables . length > 0 ) { throw new MissingVariableError ( this . #input , { specificVariable : missingVariables . toString ( ) , } ) ; } if ( unknownVariables . length > 0 ) { throw new UnknownVariableError ( this . #input , { specificVariable : unknownVariables . toString ( ) , } ) ; } this . #variables = variables ; return this ; } deprecated plurals ( num , plurals ) { if ( num === 0 ) { this . #output = plurals . zero ?? this . #output ; return this ; } const rule = new Intl . PluralRules ( this . #locale ) . select ( num ) ; switch ( rule ) { case 'zero' : this . #output = plurals . zero ?? this . #output ; break ; case 'one' : this . #output = plurals . one ?? this . #output ; break ; case 'two' : this . #output = plurals . two ?? this . #output ; break ; case 'few' : this . #output = plurals . few ?? this . #output ; break ; case 'many' : this . #output = plurals . many ?? this . #output ; break ; } return this ; } returns toString ( ) { this . #output = InlangTextApi . #interpolate ( this . #output , this . #variables ) ; return this . #output ; } }