Checks locales are real in resolveCanonicalLocales
This commit is contained in:
parent
cc6ff0b554
commit
b965e1f9a5
2 changed files with 36 additions and 9 deletions
22
ts/test-node/util/resolveCanonicalLocales_test.ts
Normal file
22
ts/test-node/util/resolveCanonicalLocales_test.ts
Normal file
|
@ -0,0 +1,22 @@
|
|||
// Copyright 2024 Signal Messenger, LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { resolveCanonicalLocales } from '../../util/resolveCanonicalLocales';
|
||||
|
||||
describe('resolveCanonicalLocales', () => {
|
||||
it('returns an array of canonical locales', () => {
|
||||
assert.deepEqual(
|
||||
resolveCanonicalLocales(['EN', 'EN-US', 'EN-GB', 'FR', 'FR-FR']),
|
||||
['en', 'en-US', 'en-GB', 'fr', 'fr-FR']
|
||||
);
|
||||
});
|
||||
|
||||
it('removes invalid locales', () => {
|
||||
assert.deepEqual(resolveCanonicalLocales(['!@#$', 'POSIX', 'en']), ['en']);
|
||||
});
|
||||
|
||||
it('defaults to en if no valid locales are provided', () => {
|
||||
assert.deepEqual(resolveCanonicalLocales(['!@#$']), ['en']);
|
||||
});
|
||||
});
|
|
@ -2,13 +2,18 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
export function resolveCanonicalLocales(locales: Array<string>): Array<string> {
|
||||
return Intl.getCanonicalLocales(
|
||||
locales.flatMap(locale => {
|
||||
try {
|
||||
return Intl.getCanonicalLocales(locale);
|
||||
} catch {
|
||||
return 'en';
|
||||
}
|
||||
})
|
||||
);
|
||||
const validLocales = locales.filter(locale => {
|
||||
try {
|
||||
// Test if the locale is valid
|
||||
new Intl.Locale(locale).maximize();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
const canonical = Intl.getCanonicalLocales(validLocales);
|
||||
if (canonical.length === 0) {
|
||||
return ['en'];
|
||||
}
|
||||
return canonical;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue