diff --git a/.kiritanconfig b/.kiritanconfig index cb45554..17fd2ea 100644 --- a/.kiritanconfig +++ b/.kiritanconfig @@ -31,4 +31,10 @@ export default { naming: { template: "extensions/vim/{base}.{locale}.{ext}" }, }, ], + // Dogfooding: the CLI's own display strings (packages/kiritan/src/cli/messages.i18n.ts) are a runtime.sources resource too, so `kiritan check`/`kiritan typegen` catch a missing en/ja pair the same way any other project's own resources would. + runtime: { + sources: [ + { glob: "packages/kiritan/src/cli/*.i18n.ts", strategy: "colocated" }, + ], + }, }; diff --git a/base/DESIGN.base.md b/base/DESIGN.base.md index 96b4bd0..ede861c 100644 --- a/base/DESIGN.base.md +++ b/base/DESIGN.base.md @@ -1146,26 +1146,30 @@ Adds an item to `kiritan check` (chapter 8) that detects **cross-locale key mism ::: :::kiritan{locale=en} -The CLI's skeleton uses [citty](https://github.com/unjs/citty) (subcommand definitions, help output, and typed args aren't hand-rolled). +The CLI's skeleton uses [yargs](https://github.com/yargs/yargs) (subcommand definitions, help output, and typed args aren't hand-rolled). `kiritan` previously used [citty](https://github.com/unjs/citty) for this, but citty has no hook for translating its own `--help` output or argument-parsing errors ("Missing required argument", "Unknown argument", etc.) — they're hardcoded English strings baked into the library itself. yargs ships full bundled translations for all of that boilerplate (`.locale("ja")` switches "Commands:"/"Options:"/"Missing required argument: %s"/etc. to their Japanese equivalents), which is what actually made localizing the CLI's own `--help` and error output possible, not just its own `console.log` lines. ::: :::kiritan{locale=ja} -CLI の骨組みは [citty](https://github.com/unjs/citty) を使う(サブコマンド定義・ヘルプ表示・型付き引数を自前実装しない)。 +CLI の骨組みは [yargs](https://github.com/yargs/yargs) を使う(サブコマンド定義・ヘルプ表示・型付き引数を自前実装しない)。`kiritan` は以前 [citty](https://github.com/unjs/citty) を使っていたが、citty には自身の`--help`出力や引数解析エラー(`Missing required argument`、`Unknown argument` 等)を翻訳するフックが無く、ライブラリ自身にハードコードされた英語の文字列だった。yargsはこうした定型文言すべてに対する翻訳をバンドルで持っており(`.locale("ja")`で`Commands:`/`Options:`/`Missing required argument: %s`等が日本語に切り替わる)、これによってCLI自身の`console.log`だけでなく`--help`とエラー出力まで実際に多言語化できるようになった。 ::: ``` -kiritan init [--force] # Scaffolds .kiritanconfig / base/README.base.md / a .gitignore entry for local.kiritanconfig -kiritan build [--mode] [--config] [--locale] # Runs the full pipeline (every strategy) -kiritan extract [--mode] [--config] [--locale] # catalog-strategy sources only. Creates/updates catalogs -kiritan translate [--mode] [--config] [--locale] # Fills missing/stale via translate.middlewares (every strategy) -kiritan typegen [--mode] [--config] # Generates a .d.ts from the runtime.sources aggregation (chapter 9.6) -kiritan check [--mode] [--config] [--locale] [--json] # For CI (or editor tooling with --json). Exits non-zero on missing/stale/unreviewed/i18n-key-mismatch +kiritan init [--lang] [--force] # Scaffolds .kiritanconfig / base/README.base.md / a .gitignore entry for local.kiritanconfig +kiritan build [--lang] [--mode] [--config] [--locale] # Runs the full pipeline (every strategy) +kiritan extract [--lang] [--mode] [--config] [--locale] # catalog-strategy sources only. Creates/updates catalogs +kiritan translate [--lang] [--mode] [--config] [--locale] # Fills missing/stale via translate.middlewares (every strategy) +kiritan typegen [--lang] [--mode] [--config] # Generates a .d.ts from the runtime.sources aggregation (chapter 9.6) +kiritan check [--lang] [--mode] [--config] [--locale] [--json] # For CI (or editor tooling with --json). Exits non-zero on missing/stale/unreviewed/i18n-key-mismatch ``` :::kiritan{locale=en} `kiritan init` leaves every file it would write alone if it already exists (`--force` overwrites) — safe to run again in a project that already has some of the three set up. `build`/`check`/`translate`/`extract` all accept `--locale ` to restrict a run to one locale instead of every locale in `locales.list`; `kiritan typegen` doesn't, since it always aggregates every locale into one runtime module. + +`--lang ` picks the CLI's own display language — every command/option description, `--help` output, and the CLI's own plain-text success/no-op lines (not `--json` output, which stays machine-readable regardless) — as opposed to `--locale`, which picks which *document* locale a run acts on. Without `--lang`, it falls back to `KIRITAN_LANG`, then the usual POSIX locale env vars (`LC_ALL`, `LC_MESSAGES`, `LANG`), then `en`; an explicit but unsupported `--lang` (e.g. `--lang fr`) is reported back as a normal invalid-choice error rather than silently falling back. The CLI's own strings live in `packages/kiritan/src/cli/messages.i18n.ts` — a `colocated`-strategy `runtime.sources` resource in this repo's own `.kiritanconfig`, so `kiritan check`/`kiritan typegen` catch a missing en/ja pair here the same way they would for any other project's own resources. A `CheckIssue.detail` or a thrown `Error.message` from a pipeline function (`packages/kiritan/src/pipeline/*.ts`) is never translated, though — those are library-level strings used by both the CLI and the programmatic API, and stay in English the same way any Node library's own exceptions would, regardless of `--lang`. ::: :::kiritan{locale=ja} `kiritan init` は書き込み先のファイルが既に存在する場合はそのまま残す(`--force` で上書き) — 3つのうち一部だけ既に用意されているプロジェクトでも再実行して安全。`build`/`check`/`translate`/`extract` はいずれも `--locale ` を受け付け、実行対象を `locales.list` 全体ではなく1ロケールに絞れる。`kiritan typegen` だけは対応しない — 常に全ロケールを1つのランタイムモジュールに集約するコマンドのため。 + +`--lang ` はCLI自身の表示言語を選ぶ — 各コマンド/オプションの説明文、`--help`出力、CLI自身が出す成功/何もしなかった旨のプレーンテキスト行(`--json`出力は機械可読のまま変わらない)が対象で、どの*ドキュメント*ロケールに対して実行するかを選ぶ`--locale`とは別物。`--lang`を指定しない場合は`KIRITAN_LANG`、次に通常のPOSIXロケール環境変数(`LC_ALL`、`LC_MESSAGES`、`LANG`)、最後に`en`にフォールバックする。明示的だが未対応の`--lang`(例: `--lang fr`)は黙ってフォールバックするのではなく、通常の不正な選択肢エラーとして報告される。CLI自身の文字列は`packages/kiritan/src/cli/messages.i18n.ts`に置かれており、このリポジトリ自身の`.kiritanconfig`における`colocated`戦略の`runtime.sources`リソースになっている — そのため`kiritan check`/`kiritan typegen`は、他のプロジェクト自身のリソースと同じようにここでのen/ja対の欠落も検出する。パイプライン関数(`packages/kiritan/src/pipeline/*.ts`)由来の`CheckIssue.detail`やスローされる`Error.message`は翻訳されない — これらはCLIとプログラムAPIの両方が使うライブラリレベルの文字列であり、`--lang`に関わらずNodeのライブラリ自身の例外と同じく英語のままとなる。 ::: ```ts diff --git a/docs/DESIGN.ja.md b/docs/DESIGN.ja.md index 34d019e..dcb6277 100644 --- a/docs/DESIGN.ja.md +++ b/docs/DESIGN.ja.md @@ -599,19 +599,21 @@ export function Button() { ## 10. CLI / プログラム API -CLI の骨組みは [citty](https://github.com/unjs/citty) を使う(サブコマンド定義・ヘルプ表示・型付き引数を自前実装しない)。 +CLI の骨組みは [yargs](https://github.com/yargs/yargs) を使う(サブコマンド定義・ヘルプ表示・型付き引数を自前実装しない)。`kiritan` は以前 [citty](https://github.com/unjs/citty) を使っていたが、citty には自身の`--help`出力や引数解析エラー(`Missing required argument`、`Unknown argument` 等)を翻訳するフックが無く、ライブラリ自身にハードコードされた英語の文字列だった。yargsはこうした定型文言すべてに対する翻訳をバンドルで持っており(`.locale("ja")`で`Commands:`/`Options:`/`Missing required argument: %s`等が日本語に切り替わる)、これによってCLI自身の`console.log`だけでなく`--help`とエラー出力まで実際に多言語化できるようになった。 ``` -kiritan init [--force] # Scaffolds .kiritanconfig / base/README.base.md / a .gitignore entry for local.kiritanconfig -kiritan build [--mode] [--config] [--locale] # Runs the full pipeline (every strategy) -kiritan extract [--mode] [--config] [--locale] # catalog-strategy sources only. Creates/updates catalogs -kiritan translate [--mode] [--config] [--locale] # Fills missing/stale via translate.middlewares (every strategy) -kiritan typegen [--mode] [--config] # Generates a .d.ts from the runtime.sources aggregation (chapter 9.6) -kiritan check [--mode] [--config] [--locale] [--json] # For CI (or editor tooling with --json). Exits non-zero on missing/stale/unreviewed/i18n-key-mismatch +kiritan init [--lang] [--force] # Scaffolds .kiritanconfig / base/README.base.md / a .gitignore entry for local.kiritanconfig +kiritan build [--lang] [--mode] [--config] [--locale] # Runs the full pipeline (every strategy) +kiritan extract [--lang] [--mode] [--config] [--locale] # catalog-strategy sources only. Creates/updates catalogs +kiritan translate [--lang] [--mode] [--config] [--locale] # Fills missing/stale via translate.middlewares (every strategy) +kiritan typegen [--lang] [--mode] [--config] # Generates a .d.ts from the runtime.sources aggregation (chapter 9.6) +kiritan check [--lang] [--mode] [--config] [--locale] [--json] # For CI (or editor tooling with --json). Exits non-zero on missing/stale/unreviewed/i18n-key-mismatch ``` `kiritan init` は書き込み先のファイルが既に存在する場合はそのまま残す(`--force` で上書き) — 3つのうち一部だけ既に用意されているプロジェクトでも再実行して安全。`build`/`check`/`translate`/`extract` はいずれも `--locale ` を受け付け、実行対象を `locales.list` 全体ではなく1ロケールに絞れる。`kiritan typegen` だけは対応しない — 常に全ロケールを1つのランタイムモジュールに集約するコマンドのため。 +`--lang ` はCLI自身の表示言語を選ぶ — 各コマンド/オプションの説明文、`--help`出力、CLI自身が出す成功/何もしなかった旨のプレーンテキスト行(`--json`出力は機械可読のまま変わらない)が対象で、どの*ドキュメント*ロケールに対して実行するかを選ぶ`--locale`とは別物。`--lang`を指定しない場合は`KIRITAN_LANG`、次に通常のPOSIXロケール環境変数(`LC_ALL`、`LC_MESSAGES`、`LANG`)、最後に`en`にフォールバックする。明示的だが未対応の`--lang`(例: `--lang fr`)は黙ってフォールバックするのではなく、通常の不正な選択肢エラーとして報告される。CLI自身の文字列は`packages/kiritan/src/cli/messages.i18n.ts`に置かれており、このリポジトリ自身の`.kiritanconfig`における`colocated`戦略の`runtime.sources`リソースになっている — そのため`kiritan check`/`kiritan typegen`は、他のプロジェクト自身のリソースと同じようにここでのen/ja対の欠落も検出する。パイプライン関数(`packages/kiritan/src/pipeline/*.ts`)由来の`CheckIssue.detail`やスローされる`Error.message`は翻訳されない — これらはCLIとプログラムAPIの両方が使うライブラリレベルの文字列であり、`--lang`に関わらずNodeのライブラリ自身の例外と同じく英語のままとなる。 + ```ts export { defineConfig, build } from 'kiritan'; export type { KiritanConfig, TranslationStore, Renderer, TranslateMiddleware, BatchTranslateMiddleware } from 'kiritan'; diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 4380f10..bc252d2 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -599,19 +599,21 @@ Adds an item to `kiritan check` (chapter 8) that detects **cross-locale key mism ## 10. CLI / programmatic API -The CLI's skeleton uses [citty](https://github.com/unjs/citty) (subcommand definitions, help output, and typed args aren't hand-rolled). +The CLI's skeleton uses [yargs](https://github.com/yargs/yargs) (subcommand definitions, help output, and typed args aren't hand-rolled). `kiritan` previously used [citty](https://github.com/unjs/citty) for this, but citty has no hook for translating its own `--help` output or argument-parsing errors ("Missing required argument", "Unknown argument", etc.) — they're hardcoded English strings baked into the library itself. yargs ships full bundled translations for all of that boilerplate (`.locale("ja")` switches "Commands:"/"Options:"/"Missing required argument: %s"/etc. to their Japanese equivalents), which is what actually made localizing the CLI's own `--help` and error output possible, not just its own `console.log` lines. ``` -kiritan init [--force] # Scaffolds .kiritanconfig / base/README.base.md / a .gitignore entry for local.kiritanconfig -kiritan build [--mode] [--config] [--locale] # Runs the full pipeline (every strategy) -kiritan extract [--mode] [--config] [--locale] # catalog-strategy sources only. Creates/updates catalogs -kiritan translate [--mode] [--config] [--locale] # Fills missing/stale via translate.middlewares (every strategy) -kiritan typegen [--mode] [--config] # Generates a .d.ts from the runtime.sources aggregation (chapter 9.6) -kiritan check [--mode] [--config] [--locale] [--json] # For CI (or editor tooling with --json). Exits non-zero on missing/stale/unreviewed/i18n-key-mismatch +kiritan init [--lang] [--force] # Scaffolds .kiritanconfig / base/README.base.md / a .gitignore entry for local.kiritanconfig +kiritan build [--lang] [--mode] [--config] [--locale] # Runs the full pipeline (every strategy) +kiritan extract [--lang] [--mode] [--config] [--locale] # catalog-strategy sources only. Creates/updates catalogs +kiritan translate [--lang] [--mode] [--config] [--locale] # Fills missing/stale via translate.middlewares (every strategy) +kiritan typegen [--lang] [--mode] [--config] # Generates a .d.ts from the runtime.sources aggregation (chapter 9.6) +kiritan check [--lang] [--mode] [--config] [--locale] [--json] # For CI (or editor tooling with --json). Exits non-zero on missing/stale/unreviewed/i18n-key-mismatch ``` `kiritan init` leaves every file it would write alone if it already exists (`--force` overwrites) — safe to run again in a project that already has some of the three set up. `build`/`check`/`translate`/`extract` all accept `--locale ` to restrict a run to one locale instead of every locale in `locales.list`; `kiritan typegen` doesn't, since it always aggregates every locale into one runtime module. +`--lang ` picks the CLI's own display language — every command/option description, `--help` output, and the CLI's own plain-text success/no-op lines (not `--json` output, which stays machine-readable regardless) — as opposed to `--locale`, which picks which *document* locale a run acts on. Without `--lang`, it falls back to `KIRITAN_LANG`, then the usual POSIX locale env vars (`LC_ALL`, `LC_MESSAGES`, `LANG`), then `en`; an explicit but unsupported `--lang` (e.g. `--lang fr`) is reported back as a normal invalid-choice error rather than silently falling back. The CLI's own strings live in `packages/kiritan/src/cli/messages.i18n.ts` — a `colocated`-strategy `runtime.sources` resource in this repo's own `.kiritanconfig`, so `kiritan check`/`kiritan typegen` catch a missing en/ja pair here the same way they would for any other project's own resources. A `CheckIssue.detail` or a thrown `Error.message` from a pipeline function (`packages/kiritan/src/pipeline/*.ts`) is never translated, though — those are library-level strings used by both the CLI and the programmatic API, and stay in English the same way any Node library's own exceptions would, regardless of `--lang`. + ```ts export { defineConfig, build } from 'kiritan'; export type { KiritanConfig, TranslationStore, Renderer, TranslateMiddleware, BatchTranslateMiddleware } from 'kiritan'; diff --git a/package-lock.json b/package-lock.json index e0ab427..6bc0509 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1313,6 +1313,23 @@ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", "license": "MIT" }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.70.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz", @@ -2307,7 +2324,6 @@ "version": "6.3.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz", "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -2753,12 +2769,43 @@ "license": "ISC", "optional": true }, - "node_modules/citty": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", - "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", "license": "MIT" }, + "node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/cockatiel": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/cockatiel/-/cockatiel-3.2.1.tgz", @@ -3267,6 +3314,15 @@ "node": ">= 0.4" } }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -3707,6 +3763,27 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", + "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -7001,7 +7078,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.2.2" @@ -7960,6 +8036,58 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -8008,6 +8136,15 @@ "node": ">=4.0" } }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", @@ -8015,6 +8152,48 @@ "dev": true, "license": "ISC" }, + "node_modules/yargs": { + "version": "18.1.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.1.0.tgz", + "integrity": "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==", + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.2.tgz", + "integrity": "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/yauzl": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz", @@ -8125,17 +8304,20 @@ "license": "WTFPL", "dependencies": { "@kiritan/runtime": "^0.2.0", - "citty": "^0.2.2", "jiti": "^2.4.2", "remark-directive": "^4.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "tinyglobby": "^0.2.17", - "unified": "^11.0.5" + "unified": "^11.0.5", + "yargs": "^18.1.0" }, "bin": { "kiritan": "dist/cli.mjs" }, + "devDependencies": { + "@types/yargs": "^17.0.35" + }, "engines": { "node": ">=22.7.0" } diff --git a/packages/kiritan/README.ja.md b/packages/kiritan/README.ja.md index 20b826b..86298a9 100644 --- a/packages/kiritan/README.ja.md +++ b/packages/kiritan/README.ja.md @@ -82,6 +82,8 @@ await build(config); `kiritan init` 以外のコマンドはすべて `--mode ` と `--config ` を受け付け、適用する設定レイヤーを調整できる — `init` 実行前はまだ重ねる設定自体が無い。`build`/`check`/`translate`/`extract` は `--locale ` にも対応し、実行対象を `locales.list` 全体ではなく1ロケールに絞れる。`kiritan typegen` だけは対応しない — 常に全ロケールを1つのランタイムモジュールに集約するコマンドのため。 +すべてのコマンドは `--lang ` にも対応しており、CLI自身の表示言語(コマンド/オプションの説明文、`--help`出力、CLI自身が出すプレーンテキストの出力行 — `--json`は機械可読のまま変わらない)を選べる。どの*ドキュメント*ロケールに対して実行するかを選ぶ`--locale`とは無関係。`--lang`を指定しない場合は`KIRITAN_LANG`/`LC_ALL`/`LC_MESSAGES`/`LANG`環境変数、最後に`en`にフォールバックする。 + ## 動作環境 - Node.js >= 22.7 diff --git a/packages/kiritan/README.md b/packages/kiritan/README.md index e5e15d9..59bfd7a 100644 --- a/packages/kiritan/README.md +++ b/packages/kiritan/README.md @@ -82,6 +82,8 @@ await build(config); Every command except `kiritan init` accepts `--mode ` and `--config ` to adjust which config layers are applied — there's no config to layer yet before `init` has run. `build`/`check`/`translate`/`extract` also accept `--locale ` to restrict a run to one locale instead of every locale in `locales.list`; `kiritan typegen` doesn't, since it always aggregates every locale into one runtime module. +Every command also accepts `--lang `, picking the CLI's own display language — command/option descriptions, `--help` output, and the CLI's own plain-text output lines (not `--json`, which stays machine-readable regardless). This is unrelated to `--locale`, which picks which *document* locale a run acts on. Without `--lang`, it falls back to the `KIRITAN_LANG`/`LC_ALL`/`LC_MESSAGES`/`LANG` environment variables, then `en`. + ## Requirements - Node.js >= 22.7 diff --git a/packages/kiritan/base/README.base.md b/packages/kiritan/base/README.base.md index 30bcc78..4eeb4f6 100644 --- a/packages/kiritan/base/README.base.md +++ b/packages/kiritan/base/README.base.md @@ -114,6 +114,8 @@ await build(config); | `kiritan typegen` | Merges `runtime.sources` into one namespaced `ResourceModule` and writes its type declaration ([docs/DESIGN.md](https://github.com/otnc/kiritan/blob/main/docs/DESIGN.md) chapter 9.6) | Every command except `kiritan init` accepts `--mode ` and `--config ` to adjust which config layers are applied — there's no config to layer yet before `init` has run. `build`/`check`/`translate`/`extract` also accept `--locale ` to restrict a run to one locale instead of every locale in `locales.list`; `kiritan typegen` doesn't, since it always aggregates every locale into one runtime module. + +Every command also accepts `--lang `, picking the CLI's own display language — command/option descriptions, `--help` output, and the CLI's own plain-text output lines (not `--json`, which stays machine-readable regardless). This is unrelated to `--locale`, which picks which *document* locale a run acts on. Without `--lang`, it falls back to the `KIRITAN_LANG`/`LC_ALL`/`LC_MESSAGES`/`LANG` environment variables, then `en`. ::: :::kiritan{locale=ja} ## コマンド @@ -128,6 +130,8 @@ Every command except `kiritan init` accepts `--mode ` and `--config | `kiritan typegen` | `runtime.sources` を1つの名前空間付き `ResourceModule` に集約し、型定義を書き出す([docs/DESIGN.md](https://github.com/otnc/kiritan/blob/main/docs/DESIGN.md) 9.6章) | `kiritan init` 以外のコマンドはすべて `--mode ` と `--config ` を受け付け、適用する設定レイヤーを調整できる — `init` 実行前はまだ重ねる設定自体が無い。`build`/`check`/`translate`/`extract` は `--locale ` にも対応し、実行対象を `locales.list` 全体ではなく1ロケールに絞れる。`kiritan typegen` だけは対応しない — 常に全ロケールを1つのランタイムモジュールに集約するコマンドのため。 + +すべてのコマンドは `--lang ` にも対応しており、CLI自身の表示言語(コマンド/オプションの説明文、`--help`出力、CLI自身が出すプレーンテキストの出力行 — `--json`は機械可読のまま変わらない)を選べる。どの*ドキュメント*ロケールに対して実行するかを選ぶ`--locale`とは無関係。`--lang`を指定しない場合は`KIRITAN_LANG`/`LC_ALL`/`LC_MESSAGES`/`LANG`環境変数、最後に`en`にフォールバックする。 ::: :::kiritan{locale=en} diff --git a/packages/kiritan/package.json b/packages/kiritan/package.json index 6cc8d4d..5e46b3a 100644 --- a/packages/kiritan/package.json +++ b/packages/kiritan/package.json @@ -58,12 +58,15 @@ }, "dependencies": { "@kiritan/runtime": "^0.2.0", - "citty": "^0.2.2", "jiti": "^2.4.2", "remark-directive": "^4.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "tinyglobby": "^0.2.17", - "unified": "^11.0.5" + "unified": "^11.0.5", + "yargs": "^18.1.0" + }, + "devDependencies": { + "@types/yargs": "^17.0.35" } } diff --git a/packages/kiritan/src/cli.ts b/packages/kiritan/src/cli.ts index 1f2c220..6b743be 100644 --- a/packages/kiritan/src/cli.ts +++ b/packages/kiritan/src/cli.ts @@ -1,5 +1,10 @@ #!/usr/bin/env node -import { runMain } from "citty"; -import { main } from "./cli/index.js"; +import { hideBin } from "yargs/helpers"; +import { createCli, resolveCliLanguage } from "./cli/index.js"; -runMain(main); +// Not a top-level `await` — the unused `dist/cli.cjs` stub (see tsdown.config.ts) still has to build, and top-level await isn't valid CJS. +void (async () => { + const argv = hideBin(process.argv); + const lang = resolveCliLanguage(argv, process.env); + await createCli(lang).parseAsync(argv); +})(); diff --git a/packages/kiritan/src/cli/index.test.ts b/packages/kiritan/src/cli/index.test.ts new file mode 100644 index 0000000..404e2c6 --- /dev/null +++ b/packages/kiritan/src/cli/index.test.ts @@ -0,0 +1,124 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + afterEach, + beforeEach, + describe, + expect, + it, + vi, + type MockInstance, +} from "vitest"; +import { createCli } from "./index.js"; + +let cwd: string; +let originalCwd: string; +let logSpy: MockInstance; + +beforeEach(async () => { + cwd = await mkdtemp(join(tmpdir(), "kiritan-cli-")); + originalCwd = process.cwd(); + process.chdir(cwd); + logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); +}); + +afterEach(async () => { + process.chdir(originalCwd); + logSpy.mockRestore(); + await rm(cwd, { recursive: true, force: true }); +}); + +function logged(): string[] { + return logSpy.mock.calls.map((call) => String(call[0])); +} + +describe("createCli (init)", () => { + it("prints translated created/skipped lines depending on --lang", async () => { + await createCli("en", { exitProcess: false }).parseAsync(["init"]); + expect(logged()).toEqual([ + "created .kiritanconfig", + "created base/README.base.md", + "created .gitignore", + ]); + + logSpy.mockClear(); + await createCli("ja", { exitProcess: false }).parseAsync(["init"]); + expect(logged()).toEqual([ + ".kiritanconfig をスキップしました(既に存在します)", + "base/README.base.md をスキップしました(既に存在します)", + ".gitignore をスキップしました(既に存在します)", + ]); + }); +}); + +describe("createCli (build/check)", () => { + it("builds and checks a scaffolded project, with translated wrapper text only", async () => { + await writeFile( + join(cwd, ".kiritanconfig"), + [ + "export default {", + ' locales: { default: "en", list: ["en", "ja"] },', + ' sources: [{ glob: "README.base.md", strategy: "inline" }],', + ' naming: { template: "{base}.{locale}.{ext}" },', + "};", + ].join("\n"), + "utf8" + ); + await writeFile( + join(cwd, "README.base.md"), + [ + ":::kiritan{locale=en}", + "English.", + ":::", + ":::kiritan{locale=ja}", + "日本語。", + ":::", + ].join("\n"), + "utf8" + ); + + await createCli("ja", { exitProcess: false }).parseAsync(["build"]); + expect(logged().sort()).toEqual( + ["README.md を書き込みました", "README.ja.md を書き込みました"].sort() + ); + + logSpy.mockClear(); + await createCli("ja", { exitProcess: false }).parseAsync(["check"]); + expect(logged()).toEqual(["kiritan check: 問題は見つかりませんでした"]); + }); + + it("keeps --json output as plain machine-readable JSON regardless of --lang", async () => { + await writeFile( + join(cwd, ".kiritanconfig"), + [ + "export default {", + ' locales: { default: "en", list: ["en", "ja"] },', + ' sources: [{ glob: "README.base.md", strategy: "inline" }],', + "};", + ].join("\n"), + "utf8" + ); + await writeFile( + join(cwd, "README.base.md"), + [":::kiritan{locale=en}", "hello", ":::"].join("\n"), + "utf8" + ); + + await createCli("ja", { exitProcess: false }).parseAsync([ + "check", + "--json", + ]); + expect(logged()).toHaveLength(1); + const parsed = JSON.parse(logged()[0]!); + expect(parsed.issues).toEqual([ + { + kind: "missing", + source: "README.base.md", + locale: "ja", + detail: "no :::kiritan{locale=ja} block", + }, + ]); + expect(parsed.failed).toBe(true); + }); +}); diff --git a/packages/kiritan/src/cli/index.ts b/packages/kiritan/src/cli/index.ts index 6f3cf84..2a906fd 100644 --- a/packages/kiritan/src/cli/index.ts +++ b/packages/kiritan/src/cli/index.ts @@ -1,4 +1,5 @@ -import { defineCommand } from "citty"; +import { createT, type T } from "@kiritan/runtime"; +import yargs, { type Argv } from "yargs"; import { resolveConfig } from "../config/index.js"; import { build } from "../pipeline/build.js"; import { check, resolveInterpolationVariableNames } from "../pipeline/check.js"; @@ -6,187 +7,196 @@ import { extract } from "../pipeline/extract.js"; import { init } from "../pipeline/init.js"; import { translate } from "../pipeline/translate.js"; import { typegen } from "../pipeline/typegen.js"; +import messages from "./messages.i18n.js"; +import { SUPPORTED_LANGUAGES, type CliLanguage } from "./locale.js"; -const configArgs = { - mode: { - type: "string", - description: "Config mode layer to apply (.kiritanconfig)", - }, - config: { - type: "string", - description: "Extra config file layered on top of the cascade", - }, -} as const; +export { resolveCliLanguage } from "./locale.js"; +export type { CliLanguage } from "./locale.js"; -const localeArg = { - locale: { - type: "string", - description: - "Restrict to this locale instead of every locale in locales.list", - }, -} as const; +interface ConfigArgs { + mode?: string; + config?: string; +} -const buildCommand = defineCommand({ - meta: { - name: "build", - description: "Build localized documents from every configured source", - }, - args: { ...configArgs, ...localeArg }, - async run({ args }) { - const config = await resolveConfig({ - mode: args.mode, - overlays: args.config ? [args.config] : undefined, - }); - const result = await build(config, { locale: args.locale }); - for (const path of result.written) { - console.log(`wrote ${path}`); - } - }, -}); +async function resolveConfigFromArgs(args: ConfigArgs) { + return resolveConfig({ + mode: args.mode, + overlays: args.config ? [args.config] : undefined, + }); +} -const checkCommand = defineCommand({ - meta: { - name: "check", - description: - "Check for missing/stale/machine-translated content (CI-friendly)", - }, - args: { - ...configArgs, - ...localeArg, - json: { - type: "boolean", - description: - "Print machine-readable JSON instead (for editor tooling) — includes interpolationVariableNames and delimiters alongside the usual issues/failed", - }, - }, - async run({ args }) { - const config = await resolveConfig({ - mode: args.mode, - overlays: args.config ? [args.config] : undefined, - }); - const result = await check(config, { locale: args.locale }); +type Translate = T["t"]; - if (args.json) { - console.log( - JSON.stringify({ - ...result, - interpolationVariableNames: resolveInterpolationVariableNames(config), - delimiters: config.interpolation?.delimiters ?? ["%{", "}"], - }) - ); - if (result.failed) process.exitCode = 1; - return; - } +/** Every command except `init` shares these two — layered onto a command's own options via `{ ...configOptions(t) }`. */ +function configOptions(t: Translate) { + return { + mode: { type: "string", describe: t("option.mode") }, + config: { type: "string", describe: t("option.config") }, + } as const; +} - for (const issue of result.issues) { - console.log( - `[${issue.kind}] ${issue.source} (${issue.locale}): ${issue.detail}` - ); - } - if (result.issues.length === 0) { - console.log("kiritan check: no issues found"); - } - if (result.failed) { - process.exitCode = 1; - } - }, -}); +/** `build`/`check`/`translate`/`extract` share this; `typegen` doesn't, since it always aggregates every locale into one runtime module. */ +function localeOption(t: Translate) { + return { + locale: { type: "string", describe: t("option.locale") }, + } as const; +} -const translateCommand = defineCommand({ - meta: { - name: "translate", - description: "Fill in missing/stale translations via translate.middlewares", - }, - args: { ...configArgs, ...localeArg }, - async run({ args }) { - const config = await resolveConfig({ - mode: args.mode, - overlays: args.config ? [args.config] : undefined, - }); - const result = await translate(config, { locale: args.locale }); - for (const entry of result.translated) { - console.log(`[${entry.locale}] ${entry.source}: ${entry.detail}`); - } - if (result.translated.length === 0) { - console.log("kiritan translate: nothing to do"); - } - }, -}); +export interface CreateCliOptions { + /** Default: true. Set to false in tests so an error or --help doesn't call process.exit(). */ + exitProcess?: boolean; +} -const extractCommand = defineCommand({ - meta: { - name: "extract", - description: "Scaffold catalog files with any new ids from the base file", - }, - args: { ...configArgs, ...localeArg }, - async run({ args }) { - const config = await resolveConfig({ - mode: args.mode, - overlays: args.config ? [args.config] : undefined, - }); - const result = await extract(config, { locale: args.locale }); - for (const change of result.changes) { - console.log(`[${change.locale}] ${change.source}: ${change.detail}`); - } - if (result.changes.length === 0) { - console.log("kiritan extract: nothing to do"); - } - }, -}); +/** + * Builds the yargs CLI, already fully translated for `lang` — command/option descriptions have to be resolved strings by the time they reach `.command()`/`.options()`, so the display language must be known before this is called (see `resolveCliLanguage`). `yargs.locale(lang)` separately covers everything yargs renders on its own (USAGE/Options/Commands labels, "Missing required argument", "Unknown argument", etc.) via its own bundled locale files — this only has to supply the strings that are actually ours. + */ +export function createCli( + lang: CliLanguage, + options: CreateCliOptions = {} +): Argv { + const { t } = createT(messages, { locale: lang, fallbackLocale: "en" }); -const typegenCommand = defineCommand({ - meta: { - name: "typegen", - description: "Generate types for an aggregated runtime.sources t() call", - }, - args: configArgs, - async run({ args }) { - const config = await resolveConfig({ - mode: args.mode, - overlays: args.config ? [args.config] : undefined, - }); - const result = await typegen(config); - console.log( - `wrote ${result.dataPath} and ${result.typesPath} (${result.keyCount} keys)` - ); - }, -}); + return yargs() + .locale(lang) + .scriptName("kiritan") + .exitProcess(options.exitProcess ?? true) + .option("lang", { + type: "string", + choices: SUPPORTED_LANGUAGES, + describe: t("option.lang"), + }) + .command( + "init", + t("command.init.describe"), + (y) => + y.options({ + force: { type: "boolean", describe: t("option.force") }, + }), + async (args) => { + const result = await init({ force: args.force }); + for (const path of result.created) { + console.log(t("output.init.created", { path })); + } + for (const path of result.skipped) { + console.log(t("output.init.skipped", { path })); + } + } + ) + .command( + "build", + t("command.build.describe"), + (y) => y.options({ ...configOptions(t), ...localeOption(t) }), + async (args) => { + const config = await resolveConfigFromArgs(args); + const result = await build(config, { locale: args.locale }); + for (const path of result.written) { + console.log(t("output.wrote", { path })); + } + } + ) + .command( + "check", + t("command.check.describe"), + (y) => + y.options({ + ...configOptions(t), + ...localeOption(t), + json: { type: "boolean", describe: t("option.json") }, + }), + async (args) => { + const config = await resolveConfigFromArgs(args); + const result = await check(config, { locale: args.locale }); -const initCommand = defineCommand({ - meta: { - name: "init", - description: - "Scaffold .kiritanconfig, base/README.base.md, and a .gitignore entry for local.kiritanconfig", - }, - args: { - force: { - type: "boolean", - description: "Overwrite files that already exist", - }, - }, - async run({ args }) { - const result = await init({ force: args.force }); - for (const path of result.created) { - console.log(`created ${path}`); - } - for (const path of result.skipped) { - console.log(`skipped ${path} (already exists)`); - } - }, -}); + if (args.json) { + console.log( + JSON.stringify({ + ...result, + interpolationVariableNames: + resolveInterpolationVariableNames(config), + delimiters: config.interpolation?.delimiters ?? ["%{", "}"], + }) + ); + if (result.failed) process.exitCode = 1; + return; + } -export const main = defineCommand({ - meta: { - name: "kiritan", - description: - "In addition to standard scopes, an internationalization (i18n) utility for Markdown and other plain text documents", - }, - subCommands: { - init: initCommand, - build: buildCommand, - check: checkCommand, - translate: translateCommand, - extract: extractCommand, - typegen: typegenCommand, - }, -}); + for (const issue of result.issues) { + console.log( + t("output.check.issue", { + kind: issue.kind, + source: issue.source, + locale: issue.locale, + detail: issue.detail, + }) + ); + } + if (result.issues.length === 0) { + console.log(t("output.check.noIssues")); + } + if (result.failed) { + process.exitCode = 1; + } + } + ) + .command( + "translate", + t("command.translate.describe"), + (y) => y.options({ ...configOptions(t), ...localeOption(t) }), + async (args) => { + const config = await resolveConfigFromArgs(args); + const result = await translate(config, { locale: args.locale }); + for (const entry of result.translated) { + console.log( + t("output.translate.entry", { + locale: entry.locale, + source: entry.source, + detail: entry.detail, + }) + ); + } + if (result.translated.length === 0) { + console.log(t("output.translate.none")); + } + } + ) + .command( + "extract", + t("command.extract.describe"), + (y) => y.options({ ...configOptions(t), ...localeOption(t) }), + async (args) => { + const config = await resolveConfigFromArgs(args); + const result = await extract(config, { locale: args.locale }); + for (const change of result.changes) { + console.log( + t("output.extract.entry", { + locale: change.locale, + source: change.source, + detail: change.detail, + }) + ); + } + if (result.changes.length === 0) { + console.log(t("output.extract.none")); + } + } + ) + .command( + "typegen", + t("command.typegen.describe"), + (y) => y.options(configOptions(t)), + async (args) => { + const config = await resolveConfigFromArgs(args); + const result = await typegen(config); + console.log( + t("output.typegen.wrote", { + dataPath: result.dataPath, + typesPath: result.typesPath, + keyCount: result.keyCount, + }) + ); + } + ) + .demandCommand(1) + .strict() + .help(); +} diff --git a/packages/kiritan/src/cli/locale.test.ts b/packages/kiritan/src/cli/locale.test.ts new file mode 100644 index 0000000..77226af --- /dev/null +++ b/packages/kiritan/src/cli/locale.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; +import { resolveCliLanguage } from "./locale.js"; + +describe("resolveCliLanguage", () => { + it("defaults to en with no --lang and no relevant env vars", () => { + expect(resolveCliLanguage([], {})).toBe("en"); + }); + + it("reads an explicit --lang ", () => { + expect(resolveCliLanguage(["build", "--lang", "ja"], {})).toBe("ja"); + }); + + it("reads an explicit --lang=", () => { + expect(resolveCliLanguage(["build", "--lang=ja"], {})).toBe("ja"); + }); + + it("falls back to en for an explicit but unsupported --lang, ignoring env vars", () => { + expect(resolveCliLanguage(["--lang", "fr"], { LANG: "ja_JP.UTF-8" })).toBe( + "en" + ); + }); + + it("falls back to KIRITAN_LANG when no --lang flag is given", () => { + expect(resolveCliLanguage([], { KIRITAN_LANG: "ja" })).toBe("ja"); + }); + + it("falls back to LC_ALL, then LC_MESSAGES, then LANG, in that order", () => { + expect( + resolveCliLanguage([], { + LC_ALL: "ja_JP.UTF-8", + LC_MESSAGES: "en_US.UTF-8", + LANG: "en_US.UTF-8", + }) + ).toBe("ja"); + expect( + resolveCliLanguage([], { + LC_MESSAGES: "ja_JP.UTF-8", + LANG: "en_US.UTF-8", + }) + ).toBe("ja"); + expect(resolveCliLanguage([], { LANG: "ja_JP.UTF-8" })).toBe("ja"); + }); + + it("parses the language subtag out of a full POSIX locale string", () => { + expect(resolveCliLanguage([], { LANG: "ja_JP.UTF-8" })).toBe("ja"); + expect(resolveCliLanguage([], { LANG: "en_US.UTF-8" })).toBe("en"); + }); + + it("falls back to en for an unsupported env var value", () => { + expect(resolveCliLanguage([], { LANG: "fr_FR.UTF-8" })).toBe("en"); + }); +}); diff --git a/packages/kiritan/src/cli/locale.ts b/packages/kiritan/src/cli/locale.ts new file mode 100644 index 0000000..d4bc47f --- /dev/null +++ b/packages/kiritan/src/cli/locale.ts @@ -0,0 +1,39 @@ +const SUPPORTED_LANGUAGES = ["en", "ja"] as const; + +export type CliLanguage = (typeof SUPPORTED_LANGUAGES)[number]; + +function normalize(candidate: string | undefined): CliLanguage | undefined { + if (!candidate) return undefined; + const tag = candidate.split(/[_.]/)[0]?.toLowerCase(); + return SUPPORTED_LANGUAGES.find((language) => language === tag); +} + +/** The raw `--lang`/`--lang=` value from argv, or `undefined` if the flag wasn't passed at all — distinct from an unsupported value, which still returns that raw string here so the caller can tell "not given" apart from "given, but not en/ja". */ +function explicitLangArg(argv: string[]): string | undefined { + const index = argv.indexOf("--lang"); + if (index !== -1) return argv[index + 1]; + const inline = argv.find((arg) => arg.startsWith("--lang=")); + return inline?.slice("--lang=".length); +} + +/** + * Picks the CLI's own display language (as opposed to `--locale`, which picks which *document* locale a build/check/translate/extract run acts on): an explicit `--lang`, then the usual POSIX locale env vars, then "en". Read directly from argv/env rather than through the arg parser itself, since the language has to be known *before* yargs builds its command tree — the descriptions passed into it are already-resolved translated strings, not lazy callbacks. + * An explicit but unsupported `--lang` (e.g. `--lang fr`) falls through to "en" here rather than to the env vars, so the command tree is at least buildable — yargs's own `choices` validation on the `--lang` option is what actually reports the bad value back to the user. + */ +export function resolveCliLanguage( + argv: string[], + env: NodeJS.ProcessEnv +): CliLanguage { + const explicit = explicitLangArg(argv); + if (explicit !== undefined) return normalize(explicit) ?? "en"; + + return ( + normalize(env.KIRITAN_LANG) ?? + normalize(env.LC_ALL) ?? + normalize(env.LC_MESSAGES) ?? + normalize(env.LANG) ?? + "en" + ); +} + +export { SUPPORTED_LANGUAGES }; diff --git a/packages/kiritan/src/cli/messages.i18n.ts b/packages/kiritan/src/cli/messages.i18n.ts new file mode 100644 index 0000000..1451b87 --- /dev/null +++ b/packages/kiritan/src/cli/messages.i18n.ts @@ -0,0 +1,100 @@ +/** + * Every string the CLI itself owns and prints directly (command/option descriptions, and the plain-text success/no-op lines each command logs) — as opposed to strings a pipeline function (`packages/kiritan/src/pipeline/*.ts`) generates itself, like a `CheckIssue.detail`, which stay in English regardless of `--lang`, the same way a library's thrown `Error.message` would. This file is itself a `colocated`-strategy runtime resource (see the root `.kiritanconfig`), so `kiritan check`/`kiritan typegen` cover it against the same i18n-key-mismatch rules any other project's own resources get (docs/DESIGN.md chapter 9.7). + */ +export default { + description: { + en: "In addition to standard scopes, an internationalization (i18n) utility for Markdown and other plain text documents", + ja: "通常の範囲に加え、マークダウンやその他平文ドキュメントのための国際化(i18n)ユーティリティ", + }, + + "option.lang": { + en: "CLI display language", + ja: "CLIの表示言語", + }, + "option.mode": { + en: "Config mode layer to apply (.kiritanconfig)", + ja: "適用する設定モードレイヤー(.kiritanconfig)", + }, + "option.config": { + en: "Extra config file layered on top of the cascade", + ja: "カスケードに重ねる追加の設定ファイル", + }, + "option.locale": { + en: "Restrict to this locale instead of every locale in locales.list", + ja: "locales.list 全体ではなくこのロケールに絞る", + }, + "option.force": { + en: "Overwrite files that already exist", + ja: "既存のファイルを上書きする", + }, + "option.json": { + en: "Print machine-readable JSON instead (for editor tooling) — includes interpolationVariableNames and delimiters alongside the usual issues/failed", + ja: "人間向けではなく機械可読なJSONを出力する(エディタツール向け) — 通常の issues/failed に加え interpolationVariableNames と delimiters も含む", + }, + + "command.init.describe": { + en: "Scaffold .kiritanconfig, base/README.base.md, and a .gitignore entry for local.kiritanconfig", + ja: ".kiritanconfig・base/README.base.md・local.kiritanconfig の .gitignore への追記を生成する", + }, + "command.build.describe": { + en: "Build localized documents from every configured source", + ja: "設定済みの全ソースからローカライズされたドキュメントをビルドする", + }, + "command.check.describe": { + en: "Check for missing/stale/machine-translated content (CI-friendly)", + ja: "missing/stale/機械翻訳のコンテンツを確認する(CI向け)", + }, + "command.translate.describe": { + en: "Fill in missing/stale translations via translate.middlewares", + ja: "translate.middlewares でmissing/staleな訳文を埋める", + }, + "command.extract.describe": { + en: "Scaffold catalog files with any new ids from the base file", + ja: "baseファイルの新規idでcatalogファイルをスキャフォールドする", + }, + "command.typegen.describe": { + en: "Generate types for an aggregated runtime.sources t() call", + ja: "runtime.sources を集約した t() 呼び出し向けの型を生成する", + }, + + "output.wrote": { + en: "wrote %{path}", + ja: "%{path} を書き込みました", + }, + "output.init.created": { + en: "created %{path}", + ja: "%{path} を作成しました", + }, + "output.init.skipped": { + en: "skipped %{path} (already exists)", + ja: "%{path} をスキップしました(既に存在します)", + }, + "output.check.issue": { + en: "[%{kind}] %{source} (%{locale}): %{detail}", + ja: "[%{kind}] %{source} (%{locale}): %{detail}", + }, + "output.check.noIssues": { + en: "kiritan check: no issues found", + ja: "kiritan check: 問題は見つかりませんでした", + }, + "output.translate.entry": { + en: "[%{locale}] %{source}: %{detail}", + ja: "[%{locale}] %{source}: %{detail}", + }, + "output.translate.none": { + en: "kiritan translate: nothing to do", + ja: "kiritan translate: 何もすることがありません", + }, + "output.extract.entry": { + en: "[%{locale}] %{source}: %{detail}", + ja: "[%{locale}] %{source}: %{detail}", + }, + "output.extract.none": { + en: "kiritan extract: nothing to do", + ja: "kiritan extract: 何もすることがありません", + }, + "output.typegen.wrote": { + en: "wrote %{dataPath} and %{typesPath} (%{keyCount} keys)", + ja: "%{dataPath} と %{typesPath} を書き込みました(%{keyCount} 件のキー)", + }, +}; diff --git a/packages/kiritan/tsdown.config.ts b/packages/kiritan/tsdown.config.ts index ca837f2..a60308f 100644 --- a/packages/kiritan/tsdown.config.ts +++ b/packages/kiritan/tsdown.config.ts @@ -12,9 +12,17 @@ const EXTERNAL_DUAL_FORMAT_DEPENDENCIES = new Set([ "tinyglobby", ]); +/** + * `yargs`'s own `.locale("ja")` support (used for the CLI's own `--help`/error-message translation) reads its bundled locale JSON files at runtime from a path resolved relative to yargs's own installed package directory, not via a static `import` a bundler could follow — bundling it into dist/ would silently break that lookup, since the JSON files wouldn't be sitting next to the bundled code anymore. Unlike the dual-format packages above, `yargs` (18+) is ESM-only, so an externalized `require("yargs")` in the unused `dist/cli.cjs` stub would throw if anyone actually ran it — harmless, since nothing does (see the `entry`/`format` comment below); the real `bin` entry, `dist/cli.mjs`, only ever loads it via `import`. + */ +const EXTERNAL_RUNTIME_ASSET_DEPENDENCIES = new Set(["yargs"]); + function isExternal(id: string): boolean { if (builtinModules.includes(id.replace(/^node:/, ""))) return true; - for (const name of EXTERNAL_DUAL_FORMAT_DEPENDENCIES) { + for (const name of [ + ...EXTERNAL_DUAL_FORMAT_DEPENDENCIES, + ...EXTERNAL_RUNTIME_ASSET_DEPENDENCIES, + ]) { if (id === name || id.startsWith(`${name}/`)) return true; } return false;