addons/vscode/extension/i18n.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import type * as vscode from 'vscode';
b69ab319
b69ab3110import fs from 'node:fs';
b69ab3111import path from 'node:path';
b69ab3112import {tryJsonParse} from 'shared/utils';
b69ab3113
b69ab3114// VS Code requires a restart if you change the configured language,
b69ab3115// thus we can globally load this value on startup.
b69ab3116const nlsConfig = tryJsonParse(process.env.VSCODE_NLS_CONFIG as string) as
b69ab3117 | {locale: string}
b69ab3118 | undefined;
b69ab3119export const locale = validateLocale(nlsConfig?.locale) ?? 'en';
b69ab3120
b69ab3121/** The locale will be inserted into the HTML of the webview as a JS variable,
b69ab3122 * so it's important that what we get from the environment variable
b69ab3123 * really is just a string locale. */
b69ab3124function validateLocale(l: string | undefined): string | undefined {
b69ab3125 if (l == null) {
b69ab3126 return undefined;
b69ab3127 }
b69ab3128 return /^[a-zA-Z_]+$/.test(l) ? l : undefined;
b69ab3129}
b69ab3130
b69ab3131let translations: {[key: string]: string} | undefined = undefined;
b69ab3132
b69ab3133/**
b69ab3134 * Load translations for configured language from disk.
b69ab3135 * Should be called in extension's activate() method before
b69ab3136 * any calls to `t()`.
b69ab3137 */
b69ab3138export async function ensureTranslationsLoaded(
b69ab3139 extensionContext: vscode.ExtensionContext,
b69ab3140): Promise<void> {
b69ab3141 try {
b69ab3142 const translationsData = await fs.promises.readFile(
b69ab3143 path.join(
b69ab3144 extensionContext.extensionPath,
b69ab3145 locale === 'en' ? 'package.nls.json' : `package.nls.${locale}.json`,
b69ab3146 ),
b69ab3147 'utf-8',
b69ab3148 );
b69ab3149 translations = JSON.parse(translationsData);
b69ab3150 } catch (err) {
b69ab3151 // eslint-disable-next-line no-console
b69ab3152 console.error(`failed to load translation data for locale ${locale}: ${err}`);
b69ab3153 }
b69ab3154}
b69ab3155
b69ab3156/**
b69ab3157 * Internationalize (i18n-ize) a string from a given key.
b69ab3158 * This implementation is specifically for the vscode extension.
b69ab3159 * The webview has its own i18n system which can hook into the
b69ab3160 * VS Code configured language.
b69ab3161 * This function is used for UI-visible text from the extension host.
b69ab3162 * The translations live in package.nls.*.json files,
b69ab3163 * which includes translations for values within package.json,
b69ab3164 * such as command names. These nls files are included in the
b69ab3165 * distributed extension VSIX, but are not bundled directly into the JS when bundling.
b69ab3166 */
b69ab3167export function t(key: string): string {
b69ab3168 return translations?.[key] ?? key;
b69ab3169}