-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlocaleTools.ts
More file actions
560 lines (475 loc) · 17.4 KB
/
localeTools.ts
File metadata and controls
560 lines (475 loc) · 17.4 KB
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import { CrowdinLocale } from './generated/constants';
import {
enSimpleNoArgs,
enSimpleWithArgs,
enPlurals,
translationsSimpleNoArgs,
translationsSimpleWithArgs,
translationsPlurals,
type PluralForms,
type TokenPluralWithArgs,
type TokenSimpleNoArgs,
type TokenSimpleWithArgs,
type TokensPluralAndArgs,
type TokensSimpleAndArgs,
} from './generated/locales';
import { devSimpleNoArgs, type TokenDevNoArgs } from './devStrings';
// NOTE: this forces a plural string to use the "1" variant
export const PLURAL_COUNT_ONE = 1;
// NOTE: this forces a plural string to use the "other" variant
export const PLURAL_COUNT_OTHER = 99;
// Get a simple string without args for the given locale, falling back to English.
export function getSimpleStringNoArgs(token: TokenSimpleNoArgs, locale: CrowdinLocale): string {
if (locale === 'en') {
return enSimpleNoArgs[token];
}
return translationsSimpleNoArgs[locale]?.[token] ?? enSimpleNoArgs[token];
}
// Get a simple string with args for the given locale, falling back to English.
function getSimpleStringWithArgs(token: TokenSimpleWithArgs, locale: CrowdinLocale): string {
if (locale === 'en') {
return enSimpleWithArgs[token];
}
return translationsSimpleWithArgs[locale]?.[token] ?? enSimpleWithArgs[token];
}
// Get plural forms for the given locale, falling back to English.
function getPluralStringForms(token: TokenPluralWithArgs, locale: CrowdinLocale): PluralForms {
if (locale === 'en') {
return enPlurals[token];
}
return translationsPlurals[locale]?.[token] ?? enPlurals[token];
}
// Note: those two functions are actually duplicates of Errors.toString.
// We should maybe make that a module that we reuse?
function withClause(error: unknown) {
if (error && typeof error === 'object' && 'cause' in error) {
return `\nCaused by: ${String(error.cause)}`;
}
return '';
}
function stringifyError(error: unknown, msgOnly = false): string {
if (msgOnly) {
if (error && typeof error === 'object' && 'message' in error) {
return String(error.message);
}
return String(error);
}
if (error instanceof Error && error.stack) {
return error.stack + withClause(error);
}
if (error && typeof error === 'object' && 'message' in error) {
return String(error.message) + withClause(error);
}
return String(error) + withClause(error);
}
/**
* Duplicated from lodash, as we want the files under ts/localization to be self contained.
*/
function omit<T extends object, K extends keyof T>(obj: T, keys: Array<K>): Omit<T, K> {
const entries = Object.entries(obj) as Array<[K, T[K]]>;
const filteredEntries = entries.filter(([key]) => !keys.includes(key));
return Object.fromEntries(filteredEntries) as unknown as Omit<T, K>;
}
// eslint-disable-next-line no-console
const SubLogger = { info: console.log };
export function setLogger(logger: (msg: string) => void) {
SubLogger.info = logger;
}
/**
* The tokens that always have an arg
*/
type MergedTokenWithArgs = TokenPluralWithArgs | TokenSimpleWithArgs;
/**
* Those are all of the tokens we can use in the localizer, with or without args, plurals or not.
*/
export type MergedLocalizerTokens = MergedTokenWithArgs | TokenSimpleNoArgs | TokenDevNoArgs;
let localeInUse: CrowdinLocale = 'en';
/**
* Simpler than lodash. Duplicated to avoid having to import lodash in the file.
* Because we share it with QA, but also to have a self contained localized tool that we can copy/paste
*/
function isEmptyObject(obj: unknown) {
if (!obj) {
return true;
}
if (typeof obj !== 'object') {
return false;
}
return Object.keys(obj).length === 0;
}
// Note: not using isUnitTest as we will eventually move the whole folder to its own
// package
function isRunningInMocha(): boolean {
return typeof (global as any).it === 'function';
}
export function setLocaleInUse(crowdinLocale: CrowdinLocale) {
localeInUse = crowdinLocale;
}
function log(message: string) {
if (isRunningInMocha()) {
return;
}
SubLogger.info(message);
}
export function isSimpleTokenNoArgs(token: string): token is TokenSimpleNoArgs {
return token in enSimpleNoArgs;
}
export function isSimpleTokenWithArgs(token: string): token is TokenSimpleWithArgs {
return token in enSimpleWithArgs;
}
export function isPluralToken(token: string): token is TokenPluralWithArgs {
return token in enPlurals;
}
export function isDevTokenNoArgs(token: string): token is TokenDevNoArgs {
return token in devSimpleNoArgs;
}
export function isTokenWithArgs(token: string): token is MergedTokenWithArgs {
return isSimpleTokenWithArgs(token) || isPluralToken(token);
}
// those are still a string of the type "string" | "number" and not the typescript types themselves
type AllTokensWithArgs = TokensSimpleAndArgs & TokensPluralAndArgs;
type ArgsFromTokenStr<T extends MergedTokenWithArgs> = T extends keyof AllTokensWithArgs
? AllTokensWithArgs[T]
: never;
export type ArgsFromToken<T extends MergedLocalizerTokens> = T extends MergedTokenWithArgs
? ArgsFromTokenStr<T>
: undefined;
type ArgsFromTokenWithIcon<T extends MergedLocalizerTokens> = ArgsFromToken<T> & {
icon: string;
};
export function isArgsFromTokenWithIcon<T extends MergedLocalizerTokens>(
args: ArgsFromToken<T> | undefined
): args is ArgsFromTokenWithIcon<T> {
return !!args && !isEmptyObject(args) && 'icon' in args;
}
type WithToken<T extends MergedLocalizerTokens> = { token: T };
/** The arguments for retrieving a localized message */
export type GetMessageArgs<T extends MergedLocalizerTokens> = T extends MergedLocalizerTokens
? T extends MergedTokenWithArgs
? WithToken<T> & ArgsFromToken<T>
: WithToken<T>
: never;
export type TrArgs = GetMessageArgs<MergedLocalizerTokens>;
export type WithTrArgs = { trArgs: TrArgs };
export function tStrippedWithObj<T extends MergedLocalizerTokens>(opts: GetMessageArgs<T>): string {
const builder = new LocalizedStringBuilder<T>(opts.token as T).stripIt();
const args = messageArgsToArgsOnly(opts);
if (args) {
builder.withArgs(args);
}
return builder.toString();
}
/**
* Sanitizes the args to be used in the i18n function
* @param args The args to sanitize
* @param identifier The identifier to use for the args. Use this if you want to de-sanitize the args later.
* @returns The sanitized args
*/
export function sanitizeArgs(
args: Record<string, number | string>,
identifier?: string
): Record<string, number | string> {
return Object.fromEntries(
Object.entries(args).map(([key, value]) => [
key,
typeof value === 'string' ? sanitizeHtmlTags(value, identifier) : value,
])
);
}
/**
* Formats a localized message string with arguments and returns the formatted string.
* @param rawMessage - The raw message string to format. After using @see {@link getRawMessage} to get the raw string.
* @param args - An optional record of substitution variables and their replacement values. This
* is required if the string has dynamic variables.
*
* @returns The formatted message string.
*
* @deprecated
*
*/
export function formatMessageWithArgs<T extends MergedLocalizerTokens>(
rawMessage: string,
args?: ArgsFromToken<T>
): T | string {
/** Find and replace the dynamic variables in a localized string and substitute the variables with the provided values */
return rawMessage.replace(/\{(\w+)\}/g, (match: any, arg: string) => {
const matchedArg = args ? (args as Record<string, any>)[arg] : undefined;
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return matchedArg?.toString() ?? match;
});
}
/**
* Retrieves a localized message string, without substituting any variables. This resolves any plural forms using the given args
* @param token - The token identifying the message to retrieve.
* @param args - An optional record of substitution variables and their replacement values. This is required if the string has dynamic variables.
*
* @returns The localized message string with substitutions applied.
*
* NOTE: This is intended to be used to get the raw string then format it with {@link formatMessageWithArgs}
*/
export function getRawMessage<T extends MergedLocalizerTokens>(
crowdinLocale: CrowdinLocale,
details: GetMessageArgs<T>
): T | string {
const { token } = details;
const args = messageArgsToArgsOnly(details);
try {
if (isDevTokenNoArgs(token)) {
return devSimpleNoArgs[token];
}
if (isSimpleTokenNoArgs(token)) {
return getSimpleStringNoArgs(token, crowdinLocale);
}
if (isSimpleTokenWithArgs(token)) {
return getSimpleStringWithArgs(token, crowdinLocale);
}
if (!isPluralToken(token)) {
throw new Error('invalid token, neither simple nor plural');
}
const localePluralsObject = getPluralStringForms(token, crowdinLocale);
if (!localePluralsObject || isEmptyObject(localePluralsObject)) {
log(`Attempted to get translation for nonexistent key: '${token}'`);
return token;
}
const num = args && 'count' in args ? args.count : 0;
const cardinalRule = new Intl.PluralRules(crowdinLocale).select(num);
const pluralString = getStringForCardinalRule({
crowdinLocale,
cardinalRule,
token,
});
if (!pluralString) {
log(`Plural string not found for cardinal '${cardinalRule}': '${pluralString}'`);
return token;
}
return pluralString.replaceAll('#', `${num}`);
} catch (error) {
log(stringifyError(error, true));
return token;
}
}
function getStringForCardinalRule({
token,
crowdinLocale,
cardinalRule,
}: {
token: TokenPluralWithArgs;
crowdinLocale: CrowdinLocale;
cardinalRule: Intl.LDMLPluralRule;
}): string | undefined {
const pluralForms = getPluralStringForms(token, crowdinLocale);
// cardinalRule is one of 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'
// which matches our PluralForm type
return pluralForms[cardinalRule as keyof typeof pluralForms];
}
/**
* Replaces all html tag identifiers with their escaped equivalents
* @param str The string to sanitize
* @param identifier The identifier to use for the args. Use this if you want to de-sanitize the args later.
* @returns The sanitized string
*/
function sanitizeHtmlTags(str: string, identifier: string = ''): string {
if (identifier && /[a-zA-Z0-9></\\\-\s]+/g.test(identifier)) {
throw new Error('Identifier is not valid');
}
return str
.replace(/&/g, `${identifier}&${identifier}`)
.replace(/</g, `${identifier}<${identifier}`)
.replace(/>/g, `${identifier}>${identifier}`);
}
/**
* Replaces all sanitized html tags with their real equivalents
* @param str The string to de-sanitize
* @param identifier The identifier used when the args were sanitized
* @returns The de-sanitized string
*/
function deSanitizeHtmlTags(str: string, identifier: string): string {
if (!identifier || /[a-zA-Z0-9></\\\-\s]+/g.test(identifier)) {
throw new Error('Identifier is not valid');
}
return str
.replace(new RegExp(`${identifier}&${identifier}`, 'g'), '&')
.replace(new RegExp(`${identifier}<${identifier}`, 'g'), '<')
.replace(new RegExp(`${identifier}>${identifier}`, 'g'), '>');
}
const pluralKey = 'count' as const;
export class LocalizedStringBuilder<T extends MergedLocalizerTokens> extends String {
private readonly token: T;
private args?: ArgsFromToken<T>;
private isStripped = false;
private isEnglishForced = false;
private readonly renderStringAsToken: boolean;
constructor(token: T, renderStringAsToken?: boolean) {
super(token);
this.token = token;
this.renderStringAsToken = renderStringAsToken || false;
}
public toString(): string {
try {
if (this.renderStringAsToken) {
return this.token;
}
const rawString = this.getRawString();
const str = this.formatStringWithArgs(rawString);
if (this.isStripped) {
return this.postProcessStrippedString(str);
}
return str;
} catch (error) {
log(stringifyError(error, true));
return this.token;
}
}
withArgs(args: ArgsFromToken<T>): Omit<this, 'withArgs'> {
this.args = args;
return this;
}
forceEnglish(): Omit<this, 'forceEnglish'> {
this.isEnglishForced = true;
return this;
}
stripIt(): Omit<this, 'stripIt'> {
const sanitizedArgs = this.args ? sanitizeArgs(this.args, '\u200B') : undefined;
if (sanitizedArgs) {
this.args = sanitizedArgs as ArgsFromToken<T>;
}
this.isStripped = true;
return this;
}
private postProcessStrippedString(str: string): string {
if (typeof process.env.TEST_WORKER_INDEX === 'string' && process.env.TEST_WORKER_INDEX.length) {
// Special case for when running in playwright (those files are reused for session-appium & session-playwright as is).
// When that's the case, we need to replace `<br/>` and `<br/><br/>` with a single space.
// " <br/><br/>" and "<br/>" both become a single space
return str.replace(/\s*(<br\s*\/?>[\s]*)+/gi, ' ').replace(/<[^>]*>/g, '');
}
const strippedString = str.replaceAll(/<[^>]*>/g, '');
return deSanitizeHtmlTags(strippedString, '\u200B');
}
private localeToTarget(): CrowdinLocale {
return this.isEnglishForced ? 'en' : localeInUse;
}
private getRawString(): string {
try {
if (this.renderStringAsToken) {
return this.token;
}
if (isDevTokenNoArgs(this.token)) {
return devSimpleNoArgs[this.token];
}
if (isSimpleTokenNoArgs(this.token)) {
return getSimpleStringNoArgs(this.token, this.localeToTarget());
}
if (isSimpleTokenWithArgs(this.token)) {
return getSimpleStringWithArgs(this.token, this.localeToTarget());
}
if (!isPluralToken(this.token)) {
throw new Error(`invalid token provided: ${this.token}`);
}
return this.resolvePluralString();
} catch (error) {
log(stringifyError(error, true));
return this.token;
}
}
private resolvePluralString(): string {
let num: number | string | undefined;
if (this.args && pluralKey in this.args) {
num = this.args[pluralKey];
}
if (num === undefined) {
log(
`Attempted to get plural count for missing argument '${pluralKey} for token '${this.token}'`
);
num = 0;
}
if (typeof num !== 'number') {
log(
`Attempted to get plural count for argument '${pluralKey}' which is not a number for token '${this.token}'`
);
num = parseInt(num, 10);
if (Number.isNaN(num)) {
log(
`Attempted to get parsed plural count for argument '${pluralKey}' which is not a number for token '${this.token}'`
);
num = 0;
}
}
const localeToTarget = this.localeToTarget();
const cardinalRule = new Intl.PluralRules(localeToTarget).select(num);
if (!isPluralToken(this.token)) {
throw new Error('resolvePluralString can only be called with a plural string');
}
let pluralString = getStringForCardinalRule({
cardinalRule,
crowdinLocale: localeToTarget,
token: this.token,
});
if (!pluralString) {
log(
`Plural string not found for cardinal '${cardinalRule}': '${this.token}' Falling back to 'other' cardinal`
);
pluralString = getStringForCardinalRule({
cardinalRule: 'other',
crowdinLocale: localeToTarget,
token: this.token,
});
if (!pluralString) {
log(`Plural string not found for fallback cardinal 'other': '${this.token}'`);
return this.token;
}
}
return pluralString;
}
private formatStringWithArgs(str: string): string {
/** Find and replace the dynamic variables in a localized string and substitute the variables with the provided values */
return str.replace(/\{(\w+)\}/g, (match, arg: string) => {
const matchedArg =
this.args && arg in this.args
? (this.args as Record<string, unknown>)[arg]?.toString()
: undefined;
if (arg === pluralKey && typeof matchedArg === 'number' && Number.isFinite(matchedArg)) {
return new Intl.NumberFormat(this.localeToTarget()).format(matchedArg);
}
return matchedArg?.toString() ?? match;
});
}
}
export function tr<T extends MergedLocalizerTokens>(
token: T,
...args: ArgsFromToken<T> extends undefined ? [] : [args: ArgsFromToken<T>]
): string {
const builder = new LocalizedStringBuilder<T>(token);
if (args.length) {
builder.withArgs(args[0]);
}
return builder.toString();
}
type EnglishStringNoArgs = typeof enSimpleNoArgs;
export function tEnglish<T extends MergedLocalizerTokens>(
token: T,
...args: ArgsFromToken<T> extends undefined ? [] : [args: ArgsFromToken<T>]
): T extends TokenSimpleNoArgs ? EnglishStringNoArgs[T] : string {
const builder = new LocalizedStringBuilder<T>(token).forceEnglish();
if (args.length) {
builder.withArgs(args[0]);
}
return builder.toString() as T extends TokenSimpleNoArgs ? EnglishStringNoArgs[T] : string;
}
export function tStripped<T extends MergedLocalizerTokens>(
token: T,
...args: ArgsFromToken<T> extends undefined ? [] : [args: ArgsFromToken<T>]
): string {
const builder = new LocalizedStringBuilder<T>(token).stripIt();
if (args.length) {
builder.withArgs(args[0]);
}
return builder.toString();
}
export type LocalizerHtmlTag = 'div' | 'span';
export function messageArgsToArgsOnly<T extends MergedLocalizerTokens>(
details: GetMessageArgs<T>
): ArgsFromToken<T> {
const pl = omit(details, ['token']) as unknown as ArgsFromToken<T>;
return pl;
}