Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/loose-spoons-show.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte-language-server': patch
---

feat: ts 7 component codelens message localization
76 changes: 76 additions & 0 deletions packages/language-server/scripts/extractMessage.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { format } from 'prettier';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const locals = [
'',
'cs-CZ',
'de-DE',
'es-ES',
'fr-FR',
'it-IT',
'ja-JP',
'ko-KR',
'pl-PL',
'pt-BR',
'ru-RU',
'tr-TR',
'zh-CN',
'zh-TW'
];

const keeps = [
'Cannot_find_module_0_or_its_corresponding_type_declarations_2307',
'Add_import_from_0_90057',
'Update_import_from_0_90058',
'_0_references_95198',
'1_reference_95199'
];

const result: Record<string, Record<string, string>> = {};

for (const local of locals) {
const url =
local === ''
? `https://raw.githubusercontent.com/microsoft/TypeScript/refs/heads/main/tsc/internal/diagnostics/diagnosticMessages.generated.json`
: `https://raw.githubusercontent.com/microsoft/TypeScript/refs/heads/main/tsc/internal/diagnostics/loc/${local}.generated.json`;
const res = await fetch(url);
const data = await res.json();

result[local] = {};
for (const key of keeps) {
if (data[key]) {
result[local][key] = data[key];
}
}
}

const json = JSON.stringify(result, null, 2);
const text = [
'// the content is generated from TypeScript localization files',
'// original URL: https://github.com/microsoft/TypeScript/tree/main/tsc/internal/diagnostics',
'',
'export const tsLocals = ' + JSON.stringify(locals, null, 2) + ' as const;',
'export type TsLocals = (typeof tsLocals)[number];',
'export type MessageKey = ' + keeps.map((k) => `'${k}'`).join(' | ') + ';',
'export const localizedMessages: Record<TsLocals, Record<MessageKey, string>> = ' + json,
'',
'export function getFormatTemplate(locale: TsLocals, key: MessageKey): string {',
" return localizedMessages[locale]?.[key] ?? localizedMessages['']?.[key];",
'}'
].join('\n');

fs.writeFileSync(
path.resolve(__dirname, `../src/plugins/typescript-go/localization.ts`),
await format(text, {
parser: 'typescript',
useTabs: false,
printWidth: 100,
tabWidth: 4,
semi: true,
trailingComma: 'none',
singleQuote: true
})
);
39 changes: 39 additions & 0 deletions packages/language-server/src/ls-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import path from 'path';
import { FileMap } from './lib/documents/fileCollection';
import { ClientCapabilities } from 'vscode-languageserver-protocol';
import { defu } from 'defu';
import { TsLocals, tsLocals } from './plugins/typescript-go/localization';

/**
* Default config for the language server.
Expand Down Expand Up @@ -214,6 +215,7 @@ export interface TSUserConfig {

interface TsJsSharedConfig {
hover?: { maximumLength?: number };
locale?: string | undefined;
}

/**
Expand Down Expand Up @@ -350,6 +352,8 @@ export class LSConfigManager {
private htmlConfig: HTMLConfig | undefined;
private isTrusted = true;
private clientCapabilities: ClientCapabilities | undefined;
private clientLocale: string | undefined;
private tsLocale: TsLocals = '';

constructor() {
this._updateTsUserPreferences('javascript', {});
Expand Down Expand Up @@ -460,10 +464,41 @@ export class LSConfigManager {
this.rawTsUserConfig[lang] = config[lang];
}
});
this.updateTsLocale(config['js/ts']?.locale);
this.notifyListeners();
this.resolvedAutoImportExcludeCache.clear();
}

private updateTsLocale(localeConfig: string | undefined): void {
let locale =
localeConfig === 'auto' ? this.clientLocale : localeConfig || this.clientLocale;

if (!locale || locale === 'en') {
this.tsLocale = '';
return;
}
const parsed = new Intl.Locale(locale);
// ignore script subtag
const normalized = parsed.language + '-' + parsed.region;
if (tsLocals.includes(normalized as TsLocals)) {
this.tsLocale = normalized as TsLocals;
return;
}

const withoutRegion = parsed.language + '-';
const fallback = tsLocals.find((loc) => loc.startsWith(withoutRegion));
if (fallback) {
this.tsLocale = fallback as TsLocals;
return;
}

this.tsLocale = '';
}

getTsLocale(): TsLocals {
return this.tsLocale;
}

/**
* Whether or not the current workspace can be trusted.
* If not, certain operations should be disabled.
Expand Down Expand Up @@ -747,6 +782,10 @@ export class LSConfigManager {
this.notifyListeners();
}

setClientLocale(clientLocale: string | undefined) {
this.clientLocale = clientLocale;
}

getClientCapabilities() {
return this.clientCapabilities;
}
Expand Down
11 changes: 11 additions & 0 deletions packages/language-server/src/plugins/typescript-go/TsApiService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Logger } from '../../logger';
import { LSConfigManager, TSUserConfig } from '../../ls-config';
import { getFormatTemplate, MessageKey } from './localization';
import type { tsApiAsync, tsAst } from './types';

interface TsModules {
Expand Down Expand Up @@ -101,6 +102,16 @@ export class TsApiService {
await this.tsApi.close();
}

localeMessage(key: MessageKey, ...args: Array<string | number>): string {
const locale = this.configManager.getTsLocale();
const template = getFormatTemplate(locale, key);
let result = template;
for (let i = 0; i < args.length; i++) {
result = result.replace(`{${i}}`, args[i].toString());
}
return result;
}

getUserPreferences(sourceFile: tsAst.SourceFile): TSUserConfig {
return this.configManager.getClientTsUserConfig(
sourceFile.scriptKind == this.astModule.ScriptKind.TS ? 'typescript' : 'javascript'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,13 @@ export class TsGoCodeLensProvider implements CodeLensProvider {
cancellationToken
)) ?? [];

const title =
locations.length === 1
? this.tsApiService.localeMessage('1_reference_95199')
: this.tsApiService.localeMessage('_0_references_95198', locations.length);

codeLensToResolve.command = {
title: locations.length === 1 ? '1 reference' : `${locations.length} references`,
title,
command: '',
arguments: [textDocument.uri, codeLensToResolve.range.start, locations]
};
Expand Down
144 changes: 144 additions & 0 deletions packages/language-server/src/plugins/typescript-go/localization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// the content is generated from TypeScript localization files
// original URL: https://github.com/microsoft/TypeScript/tree/main/tsc/internal/diagnostics

export const tsLocals = [
'',
'cs-CZ',
'de-DE',
'es-ES',
'fr-FR',
'it-IT',
'ja-JP',
'ko-KR',
'pl-PL',
'pt-BR',
'ru-RU',
'tr-TR',
'zh-CN',
'zh-TW'
] as const;
export type TsLocals = (typeof tsLocals)[number];
export type MessageKey =
| 'Cannot_find_module_0_or_its_corresponding_type_declarations_2307'
| 'Add_import_from_0_90057'
| 'Update_import_from_0_90058'
| '_0_references_95198'
| '1_reference_95199';
export const localizedMessages: Record<TsLocals, Record<MessageKey, string>> = {
'': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"Cannot find module '{0}' or its corresponding type declarations.",
Add_import_from_0_90057: 'Add import from "{0}"',
Update_import_from_0_90058: 'Update import from "{0}"',
_0_references_95198: '{0} references',
'1_reference_95199': '1 reference'
},
'cs-CZ': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
'Nepovedlo se najít modul {0} nebo jeho odpovídající deklarace typů.',
Add_import_from_0_90057: 'Přidat import z {0}',
Update_import_from_0_90058: 'Aktualizovat import z: {0}',
_0_references_95198: 'Počet odkazů: {0}',
'1_reference_95199': 'jeden odkaz'
},
'de-DE': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
'Das Modul "{0}" oder die zugehörigen Typdeklarationen wurden nicht gefunden.',
Add_import_from_0_90057: 'Import aus "{0}" hinzufügen',
Update_import_from_0_90058: 'Import von "{0}" aktualisieren',
_0_references_95198: '{0} Verweise',
'1_reference_95199': '1 Verweis'
},
'es-ES': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
'No se encuentra el módulo "{0}" ni sus declaraciones de tipos correspondientes.',
Add_import_from_0_90057: 'Agregar importación desde “{0}”',
Update_import_from_0_90058: 'Actualizar importación desde “{0}”',
_0_references_95198: '{0} referencias',
'1_reference_95199': '1 referencia'
},
'fr-FR': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"Impossible de localiser le module '{0}' ou les déclarations de type correspondantes.",
Add_import_from_0_90057: 'Ajouter l\'importation de "{0}"',
Update_import_from_0_90058: 'Mettre à jour l’importation à partir de "{0}"',
_0_references_95198: '{0} références',
'1_reference_95199': '1 référence'
},
'it-IT': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"Non è possibile trovare il modulo '{0}' o le relative dichiarazioni di tipo corrispondenti.",
Add_import_from_0_90057: 'Aggiungere l\'importazione da "{0}"',
Update_import_from_0_90058: 'Aggiornare l\'importazione da "{0}"',
_0_references_95198: '{0} riferimenti',
'1_reference_95199': '1 riferimento'
},
'ja-JP': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"モジュール '{0}' またはそれに対応する型宣言が見つかりません。",
Add_import_from_0_90057: '"{0}" からのインポートの追加',
Update_import_from_0_90058: '"{0}" からのインポートの更新',
_0_references_95198: '{0} 個の参照',
'1_reference_95199': '1 件の参照'
},
'ko-KR': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"'{0}' 모듈 또는 해당 형식 선언을 찾을 수 없습니다.",
Add_import_from_0_90057: '"{0}"에서 가져오기 추가',
Update_import_from_0_90058: '"{0}"에서 가져오기 업데이트',
_0_references_95198: '참조 {0}개',
'1_reference_95199': '참조 1개'
},
'pl-PL': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
'Nie można odnaleźć modułu „{0}” lub odpowiadających mu deklaracji typów.',
Add_import_from_0_90057: 'Dodaj import z „{0}”',
Update_import_from_0_90058: 'Aktualizuj import z „{0}”',
_0_references_95198: 'Odwołania: {0}',
'1_reference_95199': '1 odwołanie'
},
'pt-BR': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"Não é possível localizar o módulo '{0}' ou suas declarações de tipo correspondentes.",
Add_import_from_0_90057: 'Adicionar importação de "{0}"',
Update_import_from_0_90058: 'Atualizar importação de "{0}"',
_0_references_95198: '{0} referências',
'1_reference_95199': '1 referência'
},
'ru-RU': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
'Не удается найти модуль "{0}" или связанные с ним объявления типов.',
Add_import_from_0_90057: 'Добавить импорт из "{0}"',
Update_import_from_0_90058: 'Обновить импорт из "{0}"',
_0_references_95198: 'Ссылок: {0}',
'1_reference_95199': '1 ссылка'
},
'tr-TR': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"'{0}' modülü veya karşılık gelen tür bildirimleri bulunamıyor.",
Add_import_from_0_90057: '"{0}" kaynağından içeri aktarma ekle',
Update_import_from_0_90058: '"{0}" kaynağından içeri aktarmayı güncelleştir',
_0_references_95198: '{0} başvuru',
'1_reference_95199': '1 başvuru'
},
'zh-CN': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
'找不到模块“{0}”或其相应的类型声明。',
Add_import_from_0_90057: '从“{0}”添加导入',
Update_import_from_0_90058: '从“{0}”更新导入',
_0_references_95198: '{0} 个引用',
'1_reference_95199': '1 个引用'
},
'zh-TW': {
Cannot_find_module_0_or_its_corresponding_type_declarations_2307:
"找不到模組 '{0}' 或其對應的型別宣告。",
Add_import_from_0_90057: '從 "{0}" 新增匯入',
Update_import_from_0_90058: '從 "{0}" 更新匯入',
_0_references_95198: '{0} 個參考',
'1_reference_95199': '1 個參考'
}
};

export function getFormatTemplate(locale: TsLocals, key: MessageKey): string {
return localizedMessages[locale]?.[key] ?? localizedMessages['']?.[key];
}
1 change: 1 addition & 0 deletions packages/language-server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export function startServer(options?: LSOptions) {
(evt.initializationOptions?.configuration?.svelte ||
evt.initializationOptions?.config)?.['language-server']?.debug
);
configManager.setClientLocale(evt.locale);
// Backwards-compatible way of setting initialization options (first `||` is the old style)
configManager.update(
evt.initializationOptions?.configuration?.svelte?.plugin ||
Expand Down