プラグインは、外部ファイル形式 (JSON、i18next、XLIFF) とinlangの内部データモデルとの間の変換を担います。.inlang はローカライゼーション用の標準オープンフォーマットで、外部の翻訳ファイルは互換性を保つためのファイルです。プラグインが行うのはインポートとエクスポートのみで、.inlang プロジェクトに直接書き込むことはありません。
┌─────────────────┐ ┌─────────┐ ┌──────────────────┐
│ .inlang file │◄─────►│ Plugins │◄─────►│ Translation files│
│ │ │ │ │ (JSON, XLIFF) │
└─────────────────┘ └─────────┘ └──────────────────┘
プラグインインターフェース
type InlangPlugin<ExternalSettings = unknown> = {
key: string;
settingsSchema?: TObject;
toBeImportedFiles?: (args) => Promise<Array<{ path; locale; metadata? }>>;
importFiles?: (args) => Promise<{ bundles; messages; variants }>;
exportFiles?: (args) => Promise<Array<ExportFile>>;
meta?: Record<string, Record<string, unknown>>;
};
最小構成の例
import type { InlangPlugin } from "@inlang/sdk";
export const plugin: InlangPlugin = {
key: "plugin.my.json",
toBeImportedFiles: async ({ settings }) => {
return settings.locales.map((locale) => ({
path: `./messages/${locale}.json`,
locale,
}));
},
importFiles: async ({ files, settings }) => {
const bundles = [];
const messages = [];
const variants = [];
for (const file of files) {
const json = JSON.parse(new TextDecoder().decode(file.content));
for (const [key, value] of Object.entries(json)) {
bundles.push({ id: key, declarations: [] });
messages.push({
bundleId: key,
locale: file.locale,
selectors: [],
});
variants.push({
messageBundleId: key,
messageLocale: file.locale,
matches: [],
pattern: [{ type: "text", value: value as string }],
});
}
}
return { bundles, messages, variants };
},
exportFiles: async ({ bundles, messages, variants, settings }) => {
const files: Record<string, Record<string, string>> = {};
for (const message of messages) {
const variant = variants.find((v) => v.messageId === message.id);
const text = variant?.pattern
.filter((p) => p.type === "text")
.map((p) => p.value)
.join("");
if (!files[message.locale]) files[message.locale] = {};
files[message.locale][message.bundleId] = text ?? "";
}
return Object.entries(files).map(([locale, content]) => ({
locale,
name: `${locale}.json`,
content: new TextEncoder().encode(JSON.stringify(content, null, 2)),
}));
},
};
メソッド
toBeImportedFiles
ファイルシステムからインポートするファイルを特定します。
toBeImportedFiles: async ({ settings }) => {
return [
{ path: "./messages/en.json", locale: "en" },
{ path: "./messages/de.json", locale: "de" },
];
};
パラメータ:
settings— プラグイン固有の設定を含むプロジェクト設定
戻り値: ファイルディスクリプタの配列:
path— ファイルのパスlocale— このファイルに含まれるロケールmetadata— 任意。importFilesに渡されます
importFiles
ファイルの内容をパースし、inlangのデータモデルに変換します。
importFiles: async ({ files, settings }) => {
return {
bundles: [...],
messages: [...],
variants: [...],
};
}
パラメータ:
files— インポートするファイルの配列:locale— ロケールcontent— バイナリ形式のファイル内容 (Uint8Array)toBeImportedFilesMetadata—toBeImportedFilesから取得したメタデータ
settings— プロジェクト設定
戻り値:
bundles—BundleImportの配列messages—MessageImportの配列variants—VariantImportの配列
exportFiles
inlangのデータモデルをファイルに書き戻します。
exportFiles: async ({ bundles, messages, variants, settings }) => {
return [
{
locale: "en",
name: "en.json",
content: new TextEncoder().encode(JSON.stringify(data)),
},
];
};
パラメータ:
bundles— すべてのバンドルmessages— すべてのメッセージvariants— すべてのバリアントsettings— プロジェクト設定files(任意) — エクスポートで上書きされるファイルの現在の内容:{ path, locale, content, metadata? }。path、locale、metadataはtoBeImportedFilesが返した値です (独自のimportFilesでファイルをインポートする場合は、metadataをtoBeImportedFilesMetadataとして渡します) 。渡されるのは実在するファイルのみです。これに対応していないホスト (SDK < 4) や、新規ファイルのエクスポートでは何も渡されません。pathPatternが配列の場合、1つのロケールに既存ファイルが複数あることがあります。
変更のないエントリはそのまま残す。 プロジェクトを保存するたびに git 上の翻訳ファイルが書き換わらないよう、エクスポートでは変更されたメッセージのバイトだけを変更してください。エクスポートするファイルの置き換え対象が files に含まれている場合は、メッセージに変更のないエントリのテキスト、ファイル内のキーの順序、フォーマット (インデント、末尾の改行、改行コード) を維持し、変更・追加・削除されたエントリだけを書き込みます。メッセージはテキストではなく、インポート結果で比較してください。ファイルが、プラグインの書き出す形式とは異なる表現 (レガシーな形式や別のエスケープ方式など) を使っていることがあるためです。既存ファイルがない場合は、ファイル全体を書き込みます。
既存ファイルのフォーマットを維持したエクスポートファイルには verbatim: true を設定します。これにより、saveProjectToDirectory はそのファイルをバイト単位でそのまま書き込みます。設定しない場合、saveProjectToDirectory はエクスポートされた JSON を既存ファイルに合わせて再インデントします (改行コードは LF になります) 。
JSON プラグインでは @inlang/sdk/json-formatting の keepUnchangedJsonEntries を利用できます。この関数は完全なエクスポートのファイルと、プラグイン自身の importFiles および exportFiles を受け取り、既存ファイルのエントリのうち、プラグインが新しいデータに対して同じ値を書き出すものをすべて維持します:
import { keepUnchangedJsonEntries } from "@inlang/sdk/json-formatting";
exportFiles: async (args) =>
keepUnchangedJsonEntries({
exported: await exportWholeFiles(args),
files: args.files,
settings: args.settings,
importFiles,
exportFiles: exportWholeFiles,
}),
以前のファイルを再利用したファイルには verbatim が設定されます。
戻り値: 書き込むファイルの配列:
locale— ロケールname— ファイル名 (例:"en.json")content— バイナリコンテンツ (Uint8Array)metadata(任意) — ライター向けの情報。例:名前空間付きのpathPatternの場合は{ namespace }verbatim(任意) —contentが既存ファイルのフォーマットを保持しており、バイト単位でそのまま書き込む必要がある場合はtrue
設定スキーマ
プラグインの設定は TypeBox で定義します:
import { Type } from "@sinclair/typebox";
export const PluginSettings = Type.Object({
pathPattern: Type.String({
pattern: ".*\\{locale\\}.*\\.json$",
description: "Path to translation files",
examples: ["./messages/{locale}.json"],
}),
sort: Type.Optional(Type.Union([Type.Literal("asc"), Type.Literal("desc")])),
});
次に、プラグインからこれを参照します。
export const plugin: InlangPlugin<{
"plugin.my.json": typeof PluginSettings;
}> = {
key: "plugin.my.json",
settingsSchema: PluginSettings,
// ...
};
ユーザーは settings.json でプラグインを設定します。
{
"baseLocale": "en",
"locales": ["en", "de"],
"modules": ["./plugins/my-plugin.js"],
"plugin.my.json": {
"pathPattern": "./messages/{locale}.json",
"sort": "asc"
}
}
型のインポート
BundleImport
type BundleImport = {
id: string;
declarations: Declaration[];
};
MessageImport
type MessageImport = {
id?: string; // 省略時は自動生成
bundleId: string;
locale: string;
selectors: VariableReference[];
};
VariantImport
バリアントは、ID またはバンドル/ロケールでメッセージを参照できます。
ほとんどの importFiles() 実装では、messageBundleId と messageLocale を組み合わせて使用してください。こうすると、SDK がインポート時にメッセージ ID を生成または再利用できます。
messageId を使うのは、プラグイン側で安定したメッセージ ID を意図的に管理し、対応するメッセージ ID を messages で返す場合に限ってください。
// メッセージIDで指定
type VariantImport = {
id?: string;
messageId: string;
matches: Match[];
pattern: Pattern;
};
// バンドル/ロケールで指定
type VariantImport = {
messageBundleId: string;
messageLocale: string;
matches: Match[];
pattern: Pattern;
};
Meta
meta を使うと、プラグイン固有の API を他のツールに公開できます。
export const plugin: InlangPlugin = {
key: "plugin.my.json",
meta: {
"app.inlang.ideExtension": {
documentSelectors: [{ language: "json" }],
},
},
};