Checks locales are real in resolveCanonicalLocales

This commit is contained in:
Jamie Kyle 2024-07-29 12:55:59 -07:00 committed by GitHub
parent cc6ff0b554
commit b965e1f9a5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 36 additions and 9 deletions

View 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']);
});
});

View file

@ -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;
}