| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import type * as vscode from 'vscode'; |
| 9 | |
| 10 | import fs from 'node:fs'; |
| 11 | import path from 'node:path'; |
| 12 | import {tryJsonParse} from 'shared/utils'; |
| 13 | |
| 14 | // VS Code requires a restart if you change the configured language, |
| 15 | // thus we can globally load this value on startup. |
| 16 | const nlsConfig = tryJsonParse(process.env.VSCODE_NLS_CONFIG as string) as |
| 17 | | {locale: string} |
| 18 | | undefined; |
| 19 | export const locale = validateLocale(nlsConfig?.locale) ?? 'en'; |
| 20 | |
| 21 | /** The locale will be inserted into the HTML of the webview as a JS variable, |
| 22 | * so it's important that what we get from the environment variable |
| 23 | * really is just a string locale. */ |
| 24 | function validateLocale(l: string | undefined): string | undefined { |
| 25 | if (l == null) { |
| 26 | return undefined; |
| 27 | } |
| 28 | return /^[a-zA-Z_]+$/.test(l) ? l : undefined; |
| 29 | } |
| 30 | |
| 31 | let translations: {[key: string]: string} | undefined = undefined; |
| 32 | |
| 33 | /** |
| 34 | * Load translations for configured language from disk. |
| 35 | * Should be called in extension's activate() method before |
| 36 | * any calls to `t()`. |
| 37 | */ |
| 38 | export async function ensureTranslationsLoaded( |
| 39 | extensionContext: vscode.ExtensionContext, |
| 40 | ): Promise<void> { |
| 41 | try { |
| 42 | const translationsData = await fs.promises.readFile( |
| 43 | path.join( |
| 44 | extensionContext.extensionPath, |
| 45 | locale === 'en' ? 'package.nls.json' : `package.nls.${locale}.json`, |
| 46 | ), |
| 47 | 'utf-8', |
| 48 | ); |
| 49 | translations = JSON.parse(translationsData); |
| 50 | } catch (err) { |
| 51 | // eslint-disable-next-line no-console |
| 52 | console.error(`failed to load translation data for locale ${locale}: ${err}`); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Internationalize (i18n-ize) a string from a given key. |
| 58 | * This implementation is specifically for the vscode extension. |
| 59 | * The webview has its own i18n system which can hook into the |
| 60 | * VS Code configured language. |
| 61 | * This function is used for UI-visible text from the extension host. |
| 62 | * The translations live in package.nls.*.json files, |
| 63 | * which includes translations for values within package.json, |
| 64 | * such as command names. These nls files are included in the |
| 65 | * distributed extension VSIX, but are not bundled directly into the JS when bundling. |
| 66 | */ |
| 67 | export function t(key: string): string { |
| 68 | return translations?.[key] ?? key; |
| 69 | } |
| 70 | |