aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/i18n/RepositoryBasedI18nBackend.ts
blob: 5b667d557038b18873468e0f54719c9e8525f7e6 (plain) (blame)
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
/*
 * Copyright (C)  2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import type {
  BackendModule,
  InitOptions,
  ReadCallback,
  Services,
} from 'i18next';
import { debounce } from 'lodash-es';

import getLogger from '../utils/getLogger.js';

import type LocatlizationRepository from './LocalizationRepository.js';

const MISSING_ENTRIES_DEBOUNCE_TIME_MS = 1000;

const log = getLogger('RepositoryBasedI18nBackend');

/**
 * I18next backend for loading translations from a file.
 *
 * Loosely based on [i18next-fs-backend](https://github.com/i18next/i18next-fs-backend),
 * but we shrink bundle size by omitting JSON5 or YAML translation handling.
 * Direct file IO is replaced by the `LocalizationRepository`,
 * which handles platform-specific concerns.
 */
export default class RepositoryBasedI18nBackend
  implements BackendModule<unknown>
{
  type = 'backend' as const;

  private writeQueue: Map<string, Map<string, Map<string, string>>> = new Map();

  private keySeparator: string | false = '.';

  private readonly flushWriteQueueImmediately = () => {
    const savedWriteQueue = this.writeQueue;
    this.writeQueue = new Map();
    savedWriteQueue.forEach((languagesMap, namespace) => {
      languagesMap.forEach((keysMap, language) => {
        this.flushChanges(language, namespace, keysMap).catch((error) => {
          log.error(
            'Cannot write missing',
            language,
            'translations for namespace',
            namespace,
            error,
          );
        });
      });
    });
  };

  private readonly flushWriteQueue = debounce(
    this.flushWriteQueueImmediately,
    MISSING_ENTRIES_DEBOUNCE_TIME_MS,
  );

  constructor(
    private readonly repository: LocatlizationRepository,
    private readonly devMode = false,
  ) {}

  init(
    _services: Services,
    _backendOptions: unknown,
    { keySeparator }: InitOptions,
  ) {
    if (keySeparator !== undefined) {
      this.keySeparator = keySeparator;
    }
  }

  read(language: string, namespace: string, callback: ReadCallback): void {
    const readAsync = async () => {
      const translations = await this.repository.getResourceContents(
        language,
        namespace,
      );
      // eslint-disable-next-line unicorn/no-null -- `i18next` API requires `null`.
      setImmediate(() => callback(null, translations));
    };

    readAsync().catch((error) => {
      log.error(
        'Error while loading',
        language,
        'translations for namespace',
        namespace,
        error,
      );
      const callbackError =
        error instanceof Error
          ? error
          : new Error(`Unknown error: ${JSON.stringify(error)}`);
      /*
        eslint-disable-next-line promise/no-callback-in-promise, unicorn/no-null --
        Converting from promise based API to a callback. `i18next` API requires `null`.
      */
      setImmediate(() => callback(callbackError, null));
    });
  }

  create(
    languages: string[],
    namespace: string,
    key: string,
    fallbackValue: string,
  ): void {
    if (!this.devMode) {
      throw new Error(
        'Refusing to write missing translations in production mode',
      );
    }
    let languagesMapOrUndefined = this.writeQueue.get(namespace);
    if (languagesMapOrUndefined === undefined) {
      languagesMapOrUndefined = new Map();
      this.writeQueue.set(namespace, languagesMapOrUndefined);
    }
    const languagesMap = languagesMapOrUndefined;
    languages.forEach((language) => {
      let keysMap = languagesMap.get(language);
      if (keysMap === undefined) {
        keysMap = new Map();
        languagesMap.set(language, keysMap);
      }
      keysMap.set(key, fallbackValue);
    });
    this.flushWriteQueue();
  }

  /**
   * Flushes new translations to the missing translations file.
   *
   * Will always fails if `devMode` is `false`.
   * If no changes are made to the translations, the file won't be rewritten.
   *
   * @param language The language to add translations for.
   * @param namespace The namespace to add translations for.
   * @param entries The translations to add.
   * @returns A promise that resolves when changes were flushed successfully.
   */
  private async flushChanges(
    language: string,
    namespace: string,
    entries: Map<string, string>,
  ): Promise<void> {
    if (!this.devMode) {
      throw new Error(
        'Refusing to write missing translations in production mode',
      );
    }
    const resourceContents = await this.repository.getMissingResourceContents(
      language,
      namespace,
    );
    const translations =
      typeof resourceContents === 'object' ? resourceContents : {};
    let changed = false;
    entries.forEach((value, key) => {
      const splitKey = this.keySeparator ? key.split(this.keySeparator) : [key];
      let obj = translations;
      /*
        eslint-disable @typescript-eslint/no-unsafe-assignment,
        security/detect-object-injection --
        We need to modify raw objects, because this is the storage format for i18next.
        To mitigate the prototype injection security risk,
        we make sure to only ever run this in development mode.
      */
      for (let i = 0; i < splitKey.length - 1; i += 1) {
        let nextObj = obj[splitKey[i]];
        if (typeof nextObj !== 'object') {
          nextObj = {};
          obj[splitKey[i]] = nextObj;
        }
        obj = nextObj;
      }
      const lastKey = splitKey[splitKey.length - 1];
      if (obj[lastKey] !== value) {
        obj[lastKey] = value;
        changed = true;
      }
      /*
        eslint-enable @typescript-eslint/no-unsafe-assignment,
        security/detect-object-injection
      */
    });
    if (!changed) {
      return;
    }
    await this.repository.setMissingResourceContents(
      language,
      namespace,
      translations,
    );
    log.debug(
      'Wrote',
      entries.size,
      'missing',
      language,
      'translations for namespace',
      namespace,
    );
  }
}