import { InlangTextApi } from './inlangTextApi' ; import type { InlangProjectConfig , InlangTranslateArgs , Locale , Translations , } from './types' ; example export class Inlang { #projectConfig : InlangProjectConfig ; /**
     * The locale of the with which the object has been created.
     */ locale : Locale ; /**
     * The record contains all translations for a given locale.
     *
     * If something went wrong during the loading of the translations,
     * the variable will not be null.
     */ #translations : Record < string , Record < string , string | undefined > | undefined > ; /**
     * The text api to use.
     */ #textApi : typeof InlangTextApi ; /**
     * Contains the missingTranslations that have been tracked already
     * in this session i.e. no need to make a new POST request.
     *
     * Is a record to avoid traversing an array. The boolean value
     * is just a placeholder if a key has been tracked.
     */ #trackedMissingTranslations : Record < string , boolean | undefined > = { } ; visibleForTesting constructor ( args ) { this . #projectConfig = args . projectConfig ; this . locale = args . locale ; this . #translations = args . translations ; this . #textApi = args . textApi ?? InlangTextApi ; } async #postMissingTranslation ( trimmedText ) { try { if ( this . #trackedMissingTranslations [ trimmedText ] !== undefined ) { return ; } const response = await fetch ( 'https://app.inlang.dev/api/missingTranslation' , { method : 'POST' , headers : { 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { projectId : this . #projectConfig . projectId , key : trimmedText , } ) , } ) ; if ( response . status === 404 ) { console . error ( `Inlang ERROR: The project ${ this . #projectConfig . projectId } does not exist.` ) ; } this . #trackedMissingTranslations [ trimmedText ] = true ; } catch { } } translate ( text , args ? ) { const trimmed = text . replace ( /(?:\n(?:\s*))+/g , ' ' ) . trim ( ) ; if ( this . #projectConfig . locales . every ( ( locale ) => this . #translations [ trimmed ] ?. [ locale ] !== undefined ) === false ) { this . #postMissingTranslation ( trimmed ) ; } return new this . #textApi ( trimmed , { translation : this . #translations [ trimmed ] ?. [ this . locale ] , locale : this . locale , } ) . variables ( args ?. vars ) . toString ( ) ; } }