@first-ch/tools-mcp 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -73,6 +73,7 @@ This server is also registered in the [MCP Registry](https://registry.modelconte
73
73
  | `robotstxt_generate` | Assembles a robots.txt from crawl rules, sitemap declarations and a preset for AI crawlers — the same logic as the browser tool at tools.first-ch.com/robots-txt/. `ai.preset` decides how 24 known AI crawlers are treated in one move: `training` (the default: refuse the ones that collect training data — GPTBot, ClaudeBot, Google-Extended, Bytespider, CCBot and the rest — while allowing AI search and on-demand fetchers such as OAI-SearchBot, Claude-SearchBot, PerplexityBot and ChatGPT-User), `allow`, `block`, `none` (leave AI crawlers out) or `custom` with `ai.overrides` naming them one by one. **A crawler obeys exactly one matching group**, so writing a group for GPTBot stops the `User-agent: *` rules from ever reaching it; by default the shared disallow paths are copied into the AI groups to close that gap (`ai.inherit: false` turns it off). Paths get a leading slash added and full URLs reduced to their path, and `warnings` reports spaces inside a path, non-ASCII paths that need percent-encoding, wildcards that not every crawler supports, a `Crawl-delay` Googlebot will ignore, a missing sitemap, a User-agent listed twice and a site blocked in full. `listCrawlers: true` returns just the crawler list (name, vendor, purpose) without generating anything | `siteUrl?`, `disallow?`, `allow?`, `userAgents?` (default `*`), `crawlDelay?`, `blockCrawlers?`, `sitemaps?`, `ai?` (`preset?`, `overrides?`, `inherit?`), `groups?`, `comments?` (default true), `allowStyle?` (`disallow-empty` default / `allow-slash`), `listCrawlers?`, `lang?` (`ja` default / `en`), `outputPath?` |
74
74
  | `case_convert` | Converts identifiers between eleven cases — camelCase, PascalCase, snake_case, CONSTANT_CASE, kebab-case, Train-Case, dot.case, Title Case, Sentence case, lower case and UPPER CASE — the same logic as the browser tool at tools.first-ch.com/case/. Built for the mechanical jobs at the boundary between layers: renaming variables in bulk, moving between `snake_case` database columns and `camelCase` JSON keys, tidying CSV headers. `scope` sets the unit of work: `lines` (the default, one item per line), `items` (every comma or tab separated field of a line, for CSV header rows) or `whole`. **Leading and trailing spaces, indentation, line endings (LF/CRLF) and the separators are preserved**, so only the names change. A run of capitals is broken only before a capital followed by a lower-case letter (`XMLHttpRequest` → `XML` / `Http` / `Request`), and digits stay attached to the word before them (`sha256Hash` → `sha256` / `Hash`; `splitDigits` splits them). Acronyms fold to `parseXmlData` by default and stay capitalised with `keepAcronyms`, except the first word of a camelCase name, which is always lower-cased (`URLParser` → `urlParser`). Characters with no letter case (Japanese, for example) pass through rather than being transliterated. `notes` reports **names that collide after conversion** (`first name` and `first_name` both become `first_name`, which is how a column silently disappears on import), results starting with a digit that cannot be identifiers, and items containing acronyms; `items[].detected` names the case each input was written in. `allFormats` expands every item into all eleven cases, `listFormats` returns just the list of cases with what each is used for | `text?` or `path?`, `outputPath?`, `format?` (`camel` default), `scope?` (`lines` default / `items` / `whole`), `splitDigits?`, `keepAcronyms?`, `allFormats?`, `listFormats?`, `lang?` (`ja` default / `en`) |
75
75
  | `csv_convert` | Converts CSV/TSV into a JSON array and back — the same logic as the browser tool at tools.first-ch.com/csv-json/. For moving data you already have between a spreadsheet and an API: turning an exported table into JSON a request body can carry, or an API response into something Excel opens. With `direction` omitted it guesses `json2csv` when the input starts with `[` or `{` and `csv2json` otherwise. The delimiter is detected by looking at the first 20 lines for the character that appears the same number of times on every line, and can be pinned with `delimiter`. **Column names such as `stock.qty` are read and written as nested objects, and `tags.0` / `tags.1` (`tags[0]` means the same) become an array** — the reverse direction flattens by the same rule, so a round trip through CSV restores the original structure (`nest: false` writes nested values into a single cell as JSON text). **Type inference is decided by round trip — a value becomes a number only when converting it back to text is character-for-character identical** — so `0123`, `+1`, `1.50` and integers beyond 2^53 (`12345678901234567890`) stay strings and postcodes, phone numbers, invoice numbers and version strings survive. Reading follows RFC 4180: quoted cells, `""` escapes, line breaks inside cells, CRLF and a BOM are all handled, and the output side offers `bom` and `newline` for Excel. On the JSON side it accepts an array, a single object, an object wrapping an array such as `{"data":[…]}`, and JSON Lines. **A JSON syntax error comes back as an `ok: false` result with a line, a column and an excerpt rather than an exception**, so the reply itself says where to fix it. `notes` also reports rows whose column count does not match the header, duplicate header names (kept as `name_2`), empty headers (named `column4`), values that would lose digits, cells starting with `=`, `+`, `-` or `@` that a spreadsheet may execute as a formula (CSV injection), and objects with a different set of keys | `text?` or `path?`, `outputPath?`, `direction?` (`auto` default / `csv2json` / `json2csv`), `delimiter?` (`auto` default / `comma` / `tab` / `semicolon` / `pipe`), `header?`, `nest?`, `types?`, `trim?`, `emptyNull?`, `indent?` (`2` default / 0–8 / `tab`), `newline?` (`lf` default / `crlf`), `quoteAll?`, `bom?`, `lang?` (`ja` default / `en`) |
76
+ | `zenkaku_convert` | Converts letters and digits, katakana, symbols and spaces between their full-width and half-width forms **with a direction chosen per kind**, and cleans up the whitespace in the same pass — the same logic as the browser tool at tools.first-ch.com/zenkaku/. For normalising Japanese copy supplied by a client, cleaning a file before an import, and tidying form input. Each of `alnum` / `kana` / `symbol` / `space` takes `keep`, `han` (half-width) or `zen` (full-width); the defaults are the form most Japanese copy is set in — letters, digits, symbols and spaces half-width, katakana full-width (the same as `preset: 'ja'`). `preset` offers `ja`, `csv` (`ja` plus the whitespace and invisible-character cleanup), `han` and `zen`, and any per-kind option overrides it. **Half-width katakana is not one character per glyph**, so converting to full-width composes a following voiced mark (`ガ` → `ガ`, `パ` → `パ`, `ヴ` → `ヴ`) and converting the other way splits it into two. Japanese punctuation, brackets, the middle dot and the prolonged sound mark (`。 、 「 」 ・ ー`) live inside the half-width katakana block (U+FF61–U+FF9F) and are **treated as katakana** (`kana: 'han'` turns `「テスト」。` into `「テスト」。`; use `keep` to leave the punctuation full-width). Spaces cover U+3000 ⇄ U+0020 and fold NBSP and the Latin space family to the half-width side. The cleanup is `collapseSpaces` (a run of spaces becomes its first character), `trimLines`, `blankLines` (`keep` / `collapse` / `remove`), `removeInvisible` (zero-width, BOM, control codes) and `composeMarks` (NFC, for copy that writes `ガ` as `カ` plus a combining U+3099). **Line endings (LF/CRLF), tabs, hiragana and kanji are never rewritten.** `notes` reports what is left — half-width katakana, ideographic spaces, invisible characters, combining marks — plus the wave dash `〜` (U+301C) versus the fullwidth tilde `~` (U+FF5E) and platform-dependent characters (`① ㈱ Ⅲ`), which are **reported and never rewritten** because which way they should go depends on the destination. **This is deliberately not NFKC**: `①` never becomes `1`, and only the kinds you selected are touched. `inspect: true` converts nothing and returns just the audit | `text?` or `path?`, `outputPath?`, `preset?` (`ja` / `csv` / `han` / `zen`), `alnum?`, `kana?`, `symbol?`, `space?` (each `keep` / `han` / `zen`), `collapseSpaces?`, `trimLines?`, `blankLines?` (`keep` default / `collapse` / `remove`), `removeInvisible?`, `composeMarks?`, `inspect?`, `lang?` (`ja` default / `en`) |
76
77
 
77
78
  See [`server.mjs`](./server.mjs) for the exact Zod input schemas.
78
79
 
@@ -188,6 +189,7 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
188
189
  | `robotstxt_generate` | クロールの許可/禁止ルール・サイトマップ宣言・AIクローラーの許可プリセットから robots.txt を組み立てる。tools.first-ch.com/robots-txt/ と同一の仕様。`ai.preset` で24種のAIクローラーの扱いをまとめて決められる: `training`(既定=GPTBot・ClaudeBot・Google-Extended・Bytespider・CCBot など**学習用データを集めるクローラーだけを拒否**し、OAI-SearchBot・Claude-SearchBot・PerplexityBot・ChatGPT-User などAI検索と都度取得は許可)/ `allow` / `block` / `none`(AIクローラーを書かない)/ `custom`(`ai.overrides` で1件ずつ指定)。**クローラーは自分に一致するグループを1つだけ読む**ため、GPTBot 用のグループを作った時点で `User-agent: *` の禁止ルールはそのクローラーへ届かなくなる。既定では共通の禁止パスをAI側のグループへ書き写してこの取りこぼしを防ぐ(`ai.inherit: false` で止められる)。パスは先頭の `/` を補い、絶対URLからはパス部分だけを取り出す。`warnings` では空白を含むパス・パーセントエンコードしていない日本語のパス・対応していないクローラーのあるワイルドカード・Googlebotが読まない `Crawl-delay`・サイトマップの宣言漏れ・同じUser-agentの重複・サイト全体の拒否を指摘する。`listCrawlers: true` を渡すと生成せずAIクローラーの一覧(名前・提供元・目的)だけを返す | `siteUrl?`、`disallow?`、`allow?`、`userAgents?`(既定 `*`)、`crawlDelay?`、`blockCrawlers?`、`sitemaps?`、`ai?`(`preset?` / `overrides?` / `inherit?`)、`groups?`、`comments?`(既定 true)、`allowStyle?`(既定 `disallow-empty` / `allow-slash`)、`listCrawlers?`、`lang?`(既定 `ja` / `en`)、`outputPath?` |
189
190
  | `case_convert` | 識別子を camelCase / PascalCase / snake_case / CONSTANT_CASE / kebab-case・Train-Case・dot.case・Title Case・Sentence case・lower case・UPPER CASE の11形式へ相互変換する。tools.first-ch.com/case/ と同一ロジック。変数名の一括リネーム、`snake_case` のDB列名と `camelCase` のJSONキーの読み替え、CSVヘッダーの整形といった、層の境目で発生する定型処理のための道具。`scope` で処理の単位を選ぶ: `lines`(既定=1行1件)/ `items`(行内のカンマ・タブ区切りで1件ずつ=CSVヘッダー)/ `whole`(全体で1件)。**前後の空白・インデント・改行コード(LF/CRLF)・区切り記号はそのまま残す**ので、名前だけが置き換わる。大文字の連なりは直後に「大文字+小文字」が続くときだけ手前で切り(`XMLHttpRequest` → `XML` / `Http` / `Request`)、数字は既定で直前の語へ付く(`sha256Hash` → `sha256` / `Hash`。`splitDigits` で分けられる)。頭字語は既定で `parseXmlData` へ畳み、`keepAcronyms` で `parseXMLData` のまま残す(camelCase の先頭語はどちらでも小文字=`URLParser` → `urlParser`)。大文字小文字を持たない文字(日本語など)はそのまま出力し、ローマ字化はしない。`notes` では**変換後に同じ名前へ衝突する項目**(`first name` と `first_name` はどちらも `first_name`=インポート時に片方が黙って消える事故の元)・数字で始まって識別子にできない結果・頭字語を含む項目を指摘し、`items[].detected` では各入力がどの形式で書かれていたかを返す。`allFormats` で各項目を11形式すべてへ展開、`listFormats` で形式の一覧と使いどころだけを返す | `text?` または `path?`、`outputPath?`、`format?`(既定 `camel`)、`scope?`(既定 `lines` / `items` / `whole`)、`splitDigits?`、`keepAcronyms?`、`allFormats?`、`listFormats?`、`lang?`(既定 `ja` / `en`) |
190
191
  | `csv_convert` | CSV/TSVとJSON配列を相互変換する。tools.first-ch.com/csv-json/ と同一ロジック。表計算ソフトから書き出した表をAPIに渡せるJSONにする、逆にAPIの応答をExcelで開ける表にする、という**手持ちのデータを形式だけ移し替える**ための道具。`direction` を省くと、入力の先頭が `[` か `{` なら `json2csv`、そうでなければ `csv2json` と推定する。区切り文字は先頭20行で「どの記号が各行に同じ個数だけ現れるか」を見て自動判定し、`delimiter` で固定もできる。**`stock.qty` のような列名は入れ子のオブジェクトとして読み書きし、`tags.0` / `tags.1`(`tags[0]` も同義)は配列になる**。逆向きも同じ規則で平らにするので、CSVへ出してJSONへ戻すと元の構造に復元される(`nest: false` なら入れ子はJSONの文字列としてセル1つに入る)。**型の読み替えは「一度数値にして文字列へ戻したとき元の表記と1文字も違わないか」で決める**ため、`0123`・`+1`・`1.50`・2の53乗を超えるID(`12345678901234567890`)は文字列のまま残り、郵便番号・電話番号・伝票番号・バージョン番号が壊れない。読み取りは RFC 4180 準拠で、引用符・`""` エスケープ・セル内改行・CRLF・BOM に対応する(書き出し側は Excel 向けに `bom` と `newline` を選べる)。JSONは配列・単体のオブジェクト・`{"data":[…]}` のように配列を包んだもの・1行1件のJSON Lines を受け取れる。**JSONの構文エラーは例外にせず、行・桁と前後の抜粋を持つ `ok: false` の結果として返す**ので、応答そのものが直しどころになる。`notes` では、列数が見出しと合わない行・重複した列名(`name_2` として残す)・空の見出し(`column4` を割り当てる)・桁落ちする数値・`=` `+` `-` `@` で始まり表計算ソフトが数式として実行しうるセル(CSVインジェクション)・キーの並びが揃わないオブジェクトを指摘する | `text?` または `path?`、`outputPath?`、`direction?`(既定 `auto` / `csv2json` / `json2csv`)、`delimiter?`(既定 `auto` / `comma` / `tab` / `semicolon` / `pipe`)、`header?`、`nest?`、`types?`、`trim?`、`emptyNull?`、`indent?`(既定 `2` / 0〜8 / `tab`)、`newline?`(既定 `lf` / `crlf`)、`quoteAll?`、`bom?`、`lang?`(既定 `ja` / `en`) |
192
+ | `zenkaku_convert` | 英数字・カタカナ・記号・スペースを**文字種ごとに向きを選んで**全角⇄半角へ変換し、あわせて空白まわりを掃除する。tools.first-ch.com/zenkaku/ と同一ロジック。顧客支給原稿の表記統一、CSV取り込み前の正規化、フォーム入力値の掃除のための道具。`alnum` / `kana` / `symbol` / `space` にそれぞれ `keep`(そのまま)/ `han`(半角へ)/ `zen`(全角へ)を渡す。既定は日本語の原稿で最も多い「英数字・記号・スペースは半角、カタカナは全角」(`preset: 'ja'` と同じ)。`preset` は `ja` / `csv`(`ja` に空白の掃除と見えない文字の除去を足したもの)/ `han` / `zen` で、個別指定が優先される。**半角カタカナは1文字ではない**ため、半角→全角では次が濁点なら1文字へ合成し(`ガ`→`ガ`・`パ`→`パ`・`ヴ`→`ヴ`)、全角→半角では2文字へ分解する。句読点・カギ括弧・中黒・長音(`。 、 「 」 ・ ー`)は半角カタカナのブロック(U+FF61〜U+FF9F)に同居しているので**カタカナと同じ文字種**として扱う(`kana: 'han'` は `「テスト」。` を `「テスト」。` にする。句読点を全角で残すなら `keep`)。スペースは U+3000 ⇄ U+0020 に加え、NBSP や欧文の各種スペースも半角側へ寄せる。掃除は `collapseSpaces`(連続する空白を先頭の1文字へ)・`trimLines`・`blankLines`(`keep` / `collapse` / `remove`)・`removeInvisible`(ゼロ幅・BOM・制御文字)・`composeMarks`(NFC。`ガ` が `カ`+結合文字 U+3099 で書かれた原稿向け)。**改行コード(LF/CRLF)とタブ、ひらがな・漢字は書き換えない。** `notes` では出力に残った半角カナ・全角スペース・見えない文字・結合文字の濁点に加え、波ダッシュ `〜`(U+301C)/全角チルダ `~`(U+FF5E)と環境依存文字(`① ㈱ Ⅲ`)を指摘する(後の2つはどちらへ寄せるべきかが届け先で変わるため**指摘のみで自動変換しない**)。**NFKC正規化とは別物**で、`①` が `1` になることはなく、選んだ文字種しか触らない。`inspect: true` なら変換せず点検結果だけを返す | `text?` または `path?`、`outputPath?`、`preset?`(`ja` / `csv` / `han` / `zen`)、`alnum?`、`kana?`、`symbol?`、`space?`(いずれも `keep` / `han` / `zen`)、`collapseSpaces?`、`trimLines?`、`blankLines?`(既定 `keep` / `collapse` / `remove`)、`removeInvisible?`、`composeMarks?`、`inspect?`、`lang?`(既定 `ja` / `en`) |
191
193
 
192
194
  正確な入力スキーマ(Zod定義)は [`server.mjs`](./server.mjs) を参照してください。
193
195
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@first-ch/tools-mcp",
3
- "version": "0.27.0",
4
- "description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換・robots.txtの生成(AIクローラーの許可プリセット付き)・文字列のケース変換(camelCase/snake_case/kebab-case など11形式)・CSV/TSVとJSON配列の相互変換(区切りの自動判定・a.b 列と入れ子の相互展開))をMCPツールとして提供するサーバー",
3
+ "version": "0.28.0",
4
+ "description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換・robots.txtの生成(AIクローラーの許可プリセット付き)・文字列のケース変換(camelCase/snake_case/kebab-case など11形式)・CSV/TSVとJSON配列の相互変換(区切りの自動判定・a.b 列と入れ子の相互展開)・全角⇄半角の変換とテキストの掃除(文字種ごとの向き指定・半角カナの合成/分解・空白と空行の整理))をMCPツールとして提供するサーバー",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "firstch-tools-mcp": "server.mjs"
@@ -148,7 +148,14 @@
148
148
  "kebab-case",
149
149
  "pascalcase",
150
150
  "identifier",
151
- "rename"
151
+ "rename",
152
+ "zenkaku",
153
+ "hankaku",
154
+ "full-width",
155
+ "half-width",
156
+ "japanese",
157
+ "normalize",
158
+ "text-cleaner"
152
159
  ],
153
160
  "author": "First CH LLC (https://first-ch.com)",
154
161
  "homepage": "https://tools.first-ch.com",
@@ -192,6 +199,7 @@
192
199
  "robots-txt.mjs",
193
200
  "case-convert.mjs",
194
201
  "csv-json.mjs",
202
+ "zenkaku.mjs",
195
203
  "vendor/",
196
204
  "README.md",
197
205
  "LICENSE"
package/server.mjs CHANGED
@@ -29,6 +29,7 @@ import { qrGenerateTool } from './qr.mjs';
29
29
  import { unixtimeConvert } from './unixtime.mjs';
30
30
  import { robotsTxtGenerate } from './robots-txt.mjs';
31
31
  import { caseConvertTool } from './case-convert.mjs';
32
+ import { zenkakuConvertTool } from './zenkaku.mjs';
32
33
  import { csvConvertTool } from './csv-json.mjs';
33
34
 
34
35
  const { version } = createRequire(import.meta.url)('./package.json');
@@ -1291,4 +1292,56 @@ server.registerTool(
1291
1292
  },
1292
1293
  );
1293
1294
 
1295
+ server.registerTool(
1296
+ 'zenkaku_convert',
1297
+ {
1298
+ title: '全角⇄半角の変換とテキストの掃除',
1299
+ description:
1300
+ '英数字・カタカナ・記号・スペースを**文字種ごとに**全角⇄半角へ変換し、あわせて空白まわりを掃除する' +
1301
+ '(tools.first-ch.com/zenkaku/ と同一ロジック)。顧客支給原稿の表記統一、CSV取り込み前の正規化、フォーム入力値の掃除に使う。' +
1302
+ 'alnum / kana / symbol / space をそれぞれ keep(そのまま)/ han(半角へ)/ zen(全角へ)で指定する。' +
1303
+ '既定は日本語の原稿で最も多い「英数字・記号・スペースは半角、カタカナは全角」(preset="ja" と同じ)。' +
1304
+ 'preset は ja / csv(jaに空白の掃除と見えない文字の除去を足したもの)/ han(すべて半角)/ zen(すべて全角)で、個別指定が優先される。' +
1305
+ '**半角カタカナは1文字ではない**ため、半角→全角では次が濁点なら1文字へ合成し(ガ→ガ・パ→パ・ヴ→ヴ)、全角→半角では2文字へ分解する。' +
1306
+ '句読点・カギ括弧・中黒・長音(。 、 「 」 ・ ー)は半角カタカナのブロック(U+FF61〜U+FF9F)に同居しているので**カタカナと同じ文字種**として扱う' +
1307
+ '(kana="han" は「テスト」。を 「テスト」。 にする。句読点を全角で残したいなら kana="keep")。' +
1308
+ 'スペースは全角スペース(U+3000)⇄半角スペースで、NBSP(U+00A0)や欧文の各種スペースも半角側へ寄せる。' +
1309
+ '掃除は collapseSpaces(連続する空白を先頭の1文字へ)/ trimLines(行頭行末の空白)/ blankLines(keep・collapse・remove)/ ' +
1310
+ 'removeInvisible(ゼロ幅・BOM・制御文字)/ composeMarks(結合した濁点をNFCで合成)。' +
1311
+ '**改行コード(LF/CRLF)とタブ、ひらがな・漢字は書き換えない**。' +
1312
+ '出力に残った半角カナ・全角スペース・見えない文字・結合文字の濁点と、波ダッシュ〜(U+301C)/全角チルダ~(U+FF5E)・環境依存文字(① ㈱ Ⅲ)を notes で指摘する' +
1313
+ '(後の2つはどちらへ寄せるべきかが届け先で変わるため、指摘のみで自動変換しない)。' +
1314
+ '**NFKC正規化とは別物**で、①→1 や ㈱→(株) のような潰し方はせず、選んだ文字種しか触らない。' +
1315
+ 'inspect=true なら変換せず、半角カナ・全角スペース・見えない文字が入っていないかの点検だけを返す。' +
1316
+ 'outputPath を渡すとそのパスへ書き出す。完全ローカル処理・ネットワーク送信なし。',
1317
+ inputSchema: {
1318
+ text: z.string().optional().describe('変換するテキスト(path と排他。複数行可)'),
1319
+ path: z.string().optional().describe('変換するファイルの絶対パス(UTF-8として読む。text と排他)'),
1320
+ outputPath: z.string().optional().describe('結果を書き出す絶対パス(指定すると本文は返さない)'),
1321
+ preset: z
1322
+ .enum(['ja', 'csv', 'han', 'zen'])
1323
+ .optional()
1324
+ .describe("よく使う組み合わせ(ja=日本語の標準 / csv=取込前の正規化 / han=すべて半角 / zen=すべて全角。個別指定が優先)"),
1325
+ alnum: z.enum(['keep', 'han', 'zen']).optional().describe("英数字の向き(既定 'han')"),
1326
+ kana: z.enum(['keep', 'han', 'zen']).optional().describe("カタカナ・句読点・カギ括弧・中黒・長音の向き(既定 'zen')"),
1327
+ symbol: z.enum(['keep', 'han', 'zen']).optional().describe("記号の向き(既定 'han')"),
1328
+ space: z.enum(['keep', 'han', 'zen']).optional().describe("スペースの向き(既定 'han'。NBSPなども対象)"),
1329
+ collapseSpaces: z.boolean().optional().describe('連続する空白を先頭の1文字にまとめる(既定 false)'),
1330
+ trimLines: z.boolean().optional().describe('行頭・行末の空白を削る(既定 false)'),
1331
+ blankLines: z
1332
+ .enum(['keep', 'collapse', 'remove'])
1333
+ .optional()
1334
+ .describe("空行の扱い(既定 'keep'/'collapse'=連続する空行を1つに/'remove'=すべて削除)"),
1335
+ removeInvisible: z.boolean().optional().describe('見えない文字(ゼロ幅・BOM・制御文字)を削除する(既定 false)'),
1336
+ composeMarks: z.boolean().optional().describe('結合した濁点・半濁点をNFCで1文字へ合成する(既定 false)'),
1337
+ inspect: z.boolean().optional().describe('変換せず、何が入っているかの点検結果だけを返す(既定 false)'),
1338
+ lang: z.enum(['ja', 'en']).optional().describe("指摘事項の言語(既定 'ja')"),
1339
+ },
1340
+ },
1341
+ async (opts) => {
1342
+ await logUsage('zenkaku_convert');
1343
+ return asText(await zenkakuConvertTool(opts));
1344
+ },
1345
+ );
1346
+
1294
1347
  await server.connect(new StdioServerTransport());
package/zenkaku.mjs ADDED
@@ -0,0 +1,462 @@
1
+ // 全角⇄半角の変換とテキストの掃除(tools.first-ch.com/zenkaku/ と同一ロジック)
2
+ //
3
+ // 「変換コア」ブロックは site 側の site/zenkaku/app.js と同一の実装。
4
+ // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
+ // 使っているのは String/RegExp/Map だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
+ import { readFile, writeFile } from 'node:fs/promises';
7
+ import { basename } from 'node:path';
8
+
9
+ /* ==================== ここから変換コア(site / MCP で同一) ==================== */
10
+
11
+ // 変換の対象にできる文字種と、各文字種で選べる向き
12
+ export const ZK_TARGETS = ['alnum', 'kana', 'symbol', 'space'];
13
+ export const ZK_DIRECTIONS = ['keep', 'han', 'zen'];
14
+ export const ZK_BLANK = ['keep', 'collapse', 'remove'];
15
+
16
+ // 半角カタカナブロック(U+FF61〜U+FF9F)と、対応する全角。添字どうしが対応する
17
+ export const KANA_HAN = '。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚';
18
+ export const KANA_ZEN = '。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜';
19
+
20
+ // 濁点・半濁点つきの全角カナと、その素の字(半角では2文字に分かれる)
21
+ const DAKU_ZEN = 'ガギグゲゴザジズゼゾダヂヅデドバビブベボヴヷヺ';
22
+ const DAKU_BASE = 'カキクケコサシスセソタチツテトハヒフヘホウワヲ';
23
+ const HANDAKU_ZEN = 'パピプペポ';
24
+ const HANDAKU_BASE = 'ハヒフヘホ';
25
+
26
+ // 濁点として書かれうる3種(半角・全角・結合文字)。macOSのファイル名は結合文字で来ることがある
27
+ const MARK_DAKU = '\uFF9E\u309B\u3099';
28
+ const MARK_HANDAKU = '\uFF9F\u309C\u309A';
29
+
30
+ // 半角スペース扱いにする空白(NBSP・欧文の各種スペース)。Wordやブラウザからの貼り付けで混ざる
31
+ const SPACE_ODD = '\u00A0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F';
32
+
33
+ // 見えない文字(ゼロ幅・BOM・書字方向指示・制御文字)。改行とタブは残す
34
+ const INVISIBLE_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F\u00AD\u200B-\u200F\u2028\u2029\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFEFF]/g;
35
+
36
+ // 空白として畳んだり削ったりする文字(改行は含めない)
37
+ const SPACE_CLASS = '\u0020\u0009\u3000' + SPACE_ODD;
38
+ const SPACE_RUN_RE = new RegExp('[' + SPACE_CLASS + ']{2,}', 'g');
39
+ const SPACE_EDGE_RE = new RegExp('^[' + SPACE_CLASS + ']+|[' + SPACE_CLASS + ']+$', 'g');
40
+ const SPACE_ONLY_RE = new RegExp('^[' + SPACE_CLASS + ']*$');
41
+
42
+ // 環境依存文字(NEC特殊文字・IBM拡張の代表)。①㈱Ⅲ㍿ など、系によっては化ける字
43
+ const PLATFORM_RE = /[Ⅰ-ⅻ①-⑳㈠-㈩㈱㈹㊤-㊩㌃㌍㌔㌘㌢㌣㌦㌧㌫㌶㌻㍉㍊㍍㍑㍗㍻-㍾㎎㎏㎜-㎞㎡㏄㏋㏍]/g;
44
+
45
+ // 変換表を1度だけ組み立てる(半角→全角・全角→半角の両方向)
46
+ function buildTables() {
47
+ const zen2han = { alnum: new Map(), kana: new Map(), symbol: new Map(), space: new Map() };
48
+ const han2zen = { alnum: new Map(), kana: new Map(), symbol: new Map(), space: new Map() };
49
+
50
+ // 英数字と記号は U+FF01〜U+FF5E がそのまま ASCII の 0x21〜0x7E に対応する(差は 0xFEE0)
51
+ for (let cp = 0xff01; cp <= 0xff5e; cp += 1) {
52
+ const zen = String.fromCharCode(cp);
53
+ const han = String.fromCharCode(cp - 0xfee0);
54
+ const isAlnum = (cp >= 0xff10 && cp <= 0xff19) || (cp >= 0xff21 && cp <= 0xff3a) || (cp >= 0xff41 && cp <= 0xff5a);
55
+ const key = isAlnum ? 'alnum' : 'symbol';
56
+ zen2han[key].set(zen, han);
57
+ han2zen[key].set(han, zen);
58
+ }
59
+
60
+ // カタカナ(句読点・カギ括弧・中黒・長音も半角カナブロックにあるのでこの文字種に含める)
61
+ for (let i = 0; i < KANA_ZEN.length; i += 1) {
62
+ zen2han.kana.set(KANA_ZEN[i], KANA_HAN[i]);
63
+ han2zen.kana.set(KANA_HAN[i], KANA_ZEN[i]);
64
+ }
65
+ // 濁点つきは全角1文字 ⇄ 半角2文字
66
+ for (let i = 0; i < DAKU_ZEN.length; i += 1) {
67
+ zen2han.kana.set(DAKU_ZEN[i], zen2han.kana.get(DAKU_BASE[i]) + '゙');
68
+ }
69
+ for (let i = 0; i < HANDAKU_ZEN.length; i += 1) {
70
+ zen2han.kana.set(HANDAKU_ZEN[i], zen2han.kana.get(HANDAKU_BASE[i]) + '゚');
71
+ }
72
+
73
+ // スペース(全角スペースと、NBSPなど幅の違う欧文スペース)
74
+ zen2han.space.set('\u3000', ' ');
75
+ han2zen.space.set(' ', '\u3000');
76
+ for (const ch of SPACE_ODD) {
77
+ zen2han.space.set(ch, ' ');
78
+ han2zen.space.set(ch, '\u3000');
79
+ }
80
+
81
+ // 半角カナ2文字 → 全角1文字を組み立てるための表
82
+ const compose = { daku: new Map(), handaku: new Map() };
83
+ for (let i = 0; i < DAKU_ZEN.length; i += 1) compose.daku.set(DAKU_BASE[i], DAKU_ZEN[i]);
84
+ for (let i = 0; i < HANDAKU_ZEN.length; i += 1) compose.handaku.set(HANDAKU_BASE[i], HANDAKU_ZEN[i]);
85
+
86
+ return { zen2han, han2zen, compose };
87
+ }
88
+
89
+ const ZK_TABLE = buildTables();
90
+
91
+ // 指定を正規化する(未知の値は既定へ倒す)
92
+ function normalizeDir(value, fallback) {
93
+ return ZK_DIRECTIONS.indexOf(value) !== -1 ? value : fallback;
94
+ }
95
+
96
+ /**
97
+ * 文字種ごとの指定に従って1文字ずつ変換する。
98
+ * カナだけは半角2文字(カ+゙)と全角1文字(ガ)を行き来するので前後を見る。
99
+ *
100
+ * @param {string} text
101
+ * @param {{alnum:string,kana:string,symbol:string,space:string}} dir 文字種ごとの向き
102
+ * @returns {{text:string, converted:number}} converted は実際に書き換わった文字数
103
+ */
104
+ export function convertWidth(text, dir) {
105
+ const { zen2han, han2zen, compose } = ZK_TABLE;
106
+ const chars = [...text];
107
+ const out = [];
108
+ let converted = 0;
109
+
110
+ for (let i = 0; i < chars.length; i += 1) {
111
+ const ch = chars[i];
112
+ let rep;
113
+
114
+ if (dir.kana === 'zen') {
115
+ // 半角カナ → 全角。次が濁点なら1文字に合成する(ガ → ガ)
116
+ const base = han2zen.kana.get(ch) !== undefined ? han2zen.kana.get(ch) : (compose.daku.has(ch) || compose.handaku.has(ch) ? ch : undefined);
117
+ if (base !== undefined) {
118
+ const next = chars[i + 1];
119
+ if (next !== undefined && MARK_DAKU.indexOf(next) !== -1 && compose.daku.has(base)) {
120
+ rep = compose.daku.get(base);
121
+ i += 1;
122
+ } else if (next !== undefined && MARK_HANDAKU.indexOf(next) !== -1 && compose.handaku.has(base)) {
123
+ rep = compose.handaku.get(base);
124
+ i += 1;
125
+ } else if (han2zen.kana.get(ch) !== undefined) {
126
+ rep = base;
127
+ }
128
+ }
129
+ } else if (dir.kana === 'han') {
130
+ rep = zen2han.kana.get(ch);
131
+ }
132
+
133
+ if (rep === undefined && dir.alnum !== 'keep') {
134
+ rep = dir.alnum === 'han' ? zen2han.alnum.get(ch) : han2zen.alnum.get(ch);
135
+ }
136
+ if (rep === undefined && dir.symbol !== 'keep') {
137
+ rep = dir.symbol === 'han' ? zen2han.symbol.get(ch) : han2zen.symbol.get(ch);
138
+ }
139
+ if (rep === undefined && dir.space !== 'keep') {
140
+ rep = dir.space === 'han' ? zen2han.space.get(ch) : han2zen.space.get(ch);
141
+ }
142
+
143
+ if (rep === undefined) {
144
+ out.push(ch);
145
+ } else {
146
+ if (rep !== ch) converted += 1;
147
+ out.push(rep);
148
+ }
149
+ }
150
+
151
+ return { text: out.join(''), converted };
152
+ }
153
+
154
+ // 行と改行を組にして返す(改行コードを混ぜずに行だけを触れるようにする)
155
+ function splitLines(text) {
156
+ const parts = text.split(/(\r\n|\n|\r)/);
157
+ const lines = [];
158
+ for (let i = 0; i < parts.length; i += 2) {
159
+ lines.push({ text: parts[i], eol: parts[i + 1] === undefined ? '' : parts[i + 1] });
160
+ }
161
+ return lines;
162
+ }
163
+
164
+ /**
165
+ * 空白・空行・見えない文字を掃除する。変換のあとに走らせる。
166
+ *
167
+ * @param {string} text
168
+ * @param {object} opts collapseSpaces / trimLines / blankLines / removeInvisible / composeMarks
169
+ */
170
+ export function cleanText(text, opts) {
171
+ let t = text;
172
+ let removed = 0;
173
+
174
+ if (opts.removeInvisible) {
175
+ const hits = t.match(INVISIBLE_RE);
176
+ if (hits) removed += hits.length;
177
+ t = t.replace(INVISIBLE_RE, '');
178
+ }
179
+ // NFCは濁点の結合文字(か+U+3099)を1文字へ合成する。削除ではないので removed に数えない
180
+ if (opts.composeMarks) t = t.normalize('NFC');
181
+
182
+ const before = [...t].length;
183
+
184
+ // 連続する空白は先頭の1文字だけ残す(全角スペースだけの並びは全角のまま残る)
185
+ if (opts.collapseSpaces) t = t.replace(SPACE_RUN_RE, (run) => run[0]);
186
+
187
+ if (opts.trimLines || opts.blankLines !== 'keep') {
188
+ const lines = splitLines(t);
189
+ const kept = [];
190
+ let blankRun = 0;
191
+ for (const line of lines) {
192
+ const body = opts.trimLines ? line.text.replace(SPACE_EDGE_RE, '') : line.text;
193
+ const blank = SPACE_ONLY_RE.test(body);
194
+ if (blank && opts.blankLines !== 'keep') {
195
+ blankRun += 1;
196
+ if (opts.blankLines === 'remove' || blankRun > 1) continue;
197
+ } else if (!blank) {
198
+ blankRun = 0;
199
+ }
200
+ kept.push({ text: body, eol: line.eol });
201
+ }
202
+ // 末尾の行だけを削ったときに改行が浮かないよう、残った最後の行の改行はそのままにする
203
+ t = kept.map((line) => line.text + line.eol).join('');
204
+ }
205
+
206
+ removed += before - [...t].length;
207
+ return { text: t, removed: removed < 0 ? 0 : removed };
208
+ }
209
+
210
+ // 文字列の中の該当文字を数える(コードポイント単位)
211
+ function countMatches(text, re) {
212
+ const hits = text.match(re);
213
+ return hits ? hits.length : 0;
214
+ }
215
+
216
+ const HANKAKU_KANA_RE = /[。-゚]/g;
217
+ const ZEN_SPACE_RE = /\u3000/g;
218
+ const COMBINING_RE = /[\u3099\u309A]/g;
219
+ const ZEN_ALNUM_RE = /[0-9A-Za-z]/g;
220
+ const HAN_ALNUM_RE = /[0-9A-Za-z]/g;
221
+
222
+ /**
223
+ * 全角⇄半角の変換とテキストの掃除をまとめて行う。
224
+ *
225
+ * @param {object} opts
226
+ * @param {string} opts.text 変換するテキスト
227
+ * @param {'keep'|'han'|'zen'} [opts.alnum='han'] 英数字の向き
228
+ * @param {'keep'|'han'|'zen'} [opts.kana='zen'] カタカナ(と句読点・カギ括弧・中黒・長音)の向き
229
+ * @param {'keep'|'han'|'zen'} [opts.symbol='han'] 記号の向き
230
+ * @param {'keep'|'han'|'zen'} [opts.space='han'] スペースの向き
231
+ * @param {boolean} [opts.collapseSpaces=false] 連続する空白を1つにまとめる
232
+ * @param {boolean} [opts.trimLines=false] 行頭・行末の空白を削る
233
+ * @param {'keep'|'collapse'|'remove'} [opts.blankLines='keep'] 空行の扱い
234
+ * @param {boolean} [opts.removeInvisible=false] 見えない文字を削る
235
+ * @param {boolean} [opts.composeMarks=false] 結合した濁点・半濁点を合成する(NFC)
236
+ * @returns {{text,input,options,stats,notes}}
237
+ */
238
+ export function zenkakuConvert(opts) {
239
+ const o = opts || {};
240
+ const input = typeof o.text === 'string' ? o.text : '';
241
+ const options = {
242
+ alnum: normalizeDir(o.alnum, 'han'),
243
+ kana: normalizeDir(o.kana, 'zen'),
244
+ symbol: normalizeDir(o.symbol, 'han'),
245
+ space: normalizeDir(o.space, 'han'),
246
+ collapseSpaces: Boolean(o.collapseSpaces),
247
+ trimLines: Boolean(o.trimLines),
248
+ blankLines: ZK_BLANK.indexOf(o.blankLines) !== -1 ? o.blankLines : 'keep',
249
+ removeInvisible: Boolean(o.removeInvisible),
250
+ composeMarks: Boolean(o.composeMarks),
251
+ };
252
+
253
+ const width = convertWidth(input, options);
254
+ const cleaned = cleanText(width.text, options);
255
+ const text = cleaned.text;
256
+
257
+ const notes = [];
258
+ if (!input) {
259
+ notes.push({ code: 'NOTHING' });
260
+ } else if (text === input) {
261
+ notes.push({ code: 'UNCHANGED' });
262
+ }
263
+
264
+ // 出力に残っていて、後の工程で困りやすいものを指摘する
265
+ const hankakuKana = countMatches(text, HANKAKU_KANA_RE);
266
+ if (hankakuKana) notes.push({ code: 'HANKAKU_KANA', count: hankakuKana });
267
+
268
+ const zenSpace = countMatches(text, ZEN_SPACE_RE);
269
+ if (zenSpace) notes.push({ code: 'ZEN_SPACE', count: zenSpace });
270
+
271
+ const invisible = countMatches(text, INVISIBLE_RE);
272
+ if (invisible) notes.push({ code: 'INVISIBLE', count: invisible });
273
+
274
+ const combining = countMatches(text, COMBINING_RE);
275
+ if (combining) notes.push({ code: 'COMBINING', count: combining });
276
+
277
+ // 波ダッシュ(U+301C)と全角チルダ(U+FF5E)は見た目が近く、環境によって化ける
278
+ const wave = countMatches(text, /[〜~]/g);
279
+ if (wave) notes.push({ code: 'WAVE', count: wave });
280
+
281
+ const platform = countMatches(text, PLATFORM_RE);
282
+ if (platform) notes.push({ code: 'PLATFORM', count: platform });
283
+
284
+ // 変換しなかった文字種で全角と半角が混じっているなら、表記ゆれとして知らせる
285
+ if (options.alnum === 'keep' && countMatches(text, ZEN_ALNUM_RE) && countMatches(text, HAN_ALNUM_RE)) {
286
+ notes.push({ code: 'MIXED_ALNUM' });
287
+ }
288
+
289
+ const lines = splitLines(text);
290
+ // 末尾が改行で終わるとき、最後の空要素は行として数えない
291
+ const lineCount = lines.length && lines[lines.length - 1].text === '' && lines[lines.length - 1].eol === ''
292
+ ? lines.length - 1
293
+ : lines.length;
294
+
295
+ return {
296
+ text,
297
+ input,
298
+ options,
299
+ stats: {
300
+ converted: width.converted,
301
+ removed: cleaned.removed,
302
+ chars_in: [...input].length,
303
+ chars_out: [...text].length,
304
+ lines: lineCount,
305
+ hankaku_kana: hankakuKana,
306
+ zen_space: zenSpace,
307
+ },
308
+ notes,
309
+ };
310
+ }
311
+
312
+ // プリセット(画面のボタンとMCPの preset で同じ指定になる)
313
+ export const ZK_PRESETS = {
314
+ ja: { alnum: 'han', kana: 'zen', symbol: 'han', space: 'han' },
315
+ han: { alnum: 'han', kana: 'han', symbol: 'han', space: 'han' },
316
+ zen: { alnum: 'zen', kana: 'zen', symbol: 'zen', space: 'zen' },
317
+ csv: {
318
+ alnum: 'han',
319
+ kana: 'zen',
320
+ symbol: 'han',
321
+ space: 'han',
322
+ collapseSpaces: true,
323
+ trimLines: true,
324
+ removeInvisible: true,
325
+ composeMarks: true,
326
+ },
327
+ };
328
+
329
+ /* ==================== ここまで変換コア ==================== */
330
+
331
+ // 指摘事項のコード → 文。site側は同じコードを日英それぞれの文へ訳している
332
+ const NOTE_TEXT = {
333
+ ja: {
334
+ NOTHING: () => '変換する文字がありませんでした。',
335
+ UNCHANGED: () => '変更はありません(指定した条件では直すところがありませんでした)。',
336
+ HANKAKU_KANA: (n) => `半角カタカナが ${n} 文字残っています。印刷物や古いシステムでは化けることがあります(kana="zen" で全角へ寄せられます)。`,
337
+ ZEN_SPACE: (n) => `全角スペース(U+3000)が ${n} 個残っています。表計算のセルでは見えず、検索や突合が空振りする原因になります。`,
338
+ INVISIBLE: (n) => `見えない文字が ${n} 個あります(ゼロ幅スペース・BOM・制御文字)。removeInvisible=true で取り除けます。`,
339
+ COMBINING: (n) => `濁点・半濁点が結合文字として ${n} 個入っています(「ガ」が「カ」+濁点の2文字)。composeMarks=true で1文字にまとめられます。`,
340
+ WAVE: (n) => `波ダッシュ・全角チルダ(〜 U+301C / ~ U+FF5E)が ${n} 文字あります。見た目はほぼ同じですが別の文字で、環境によっては一方が文字化けします(自動では変換しません)。`,
341
+ PLATFORM: (n) => `環境依存文字が ${n} 文字あります(① ㈱ Ⅲ など)。Shift_JISや古いシステムでは化けることがあります(自動では変換しません)。`,
342
+ MIXED_ALNUM: () => '結果に全角と半角の英数字が混在しています。alnum を han か zen に指定すると表記が揃います。',
343
+ TRUNCATED: (n) => `本文が長いため、text には先頭 ${n} 文字だけを入れています(全文が必要なときは outputPath を指定してください)。`,
344
+ },
345
+ en: {
346
+ NOTHING: () => 'There was nothing to convert.',
347
+ UNCHANGED: () => 'Nothing changed: the text already matches every setting given.',
348
+ HANKAKU_KANA: (n) => `${n} half-width katakana character(s) remain. They break in many systems and in printed output (kana="zen" folds them to full-width).`,
349
+ ZEN_SPACE: (n) => `${n} ideographic space(s) (U+3000) remain. They are invisible in a spreadsheet cell and a common cause of failed lookups.`,
350
+ INVISIBLE: (n) => `${n} invisible character(s) found (zero-width, BOM or control codes). Pass removeInvisible=true to strip them.`,
351
+ COMBINING: (n) => `${n} combining voiced mark(s) found: the dakuten is a separate character, so "ガ" is really "カ" plus a mark. Pass composeMarks=true to join them.`,
352
+ WAVE: (n) => `${n} wave dash / fullwidth tilde character(s) (〜 U+301C, ~ U+FF5E) found. The two look almost identical but are different characters, and one of them garbles on some systems (never rewritten automatically).`,
353
+ PLATFORM: (n) => `${n} platform-dependent character(s) found (① ㈱ Ⅲ and the like). They may not survive Shift_JIS or an older system (never rewritten automatically).`,
354
+ MIXED_ALNUM: () => 'Both full-width and half-width letters or digits appear in the result. Set alnum to han or zen to make it consistent.',
355
+ TRUNCATED: (n) => `Only the first ${n} characters are returned in text (pass outputPath when you need the whole thing).`,
356
+ },
357
+ };
358
+
359
+ // 返す本文の上限。これを超えたら切り詰めて TRUNCATED を足す(outputPath 指定時は全文をファイルへ書く)
360
+ const MAX_TEXT = 200000;
361
+
362
+ export class ZenkakuError extends Error {}
363
+
364
+ function pickDirection(value, name) {
365
+ if (value === undefined) return undefined;
366
+ if (ZK_DIRECTIONS.indexOf(value) === -1) {
367
+ throw new ZenkakuError(`${name} は ${ZK_DIRECTIONS.join(' / ')} のいずれか: ${value}`);
368
+ }
369
+ return value;
370
+ }
371
+
372
+ /**
373
+ * テキスト(または UTF-8 のテキストファイル)の全角⇄半角を揃え、空白まわりを掃除する。
374
+ *
375
+ * @param {object} opts
376
+ * @param {string} [opts.text] 変換するテキスト(path と排他)
377
+ * @param {string} [opts.path] 変換するファイルの絶対パス(UTF-8として読む)
378
+ * @param {string} [opts.outputPath] 結果を書き出す絶対パス(指定すると本文は返さない)
379
+ * @param {'ja'|'csv'|'han'|'zen'} [opts.preset] よく使う組み合わせ(個別指定で上書きできる)
380
+ * @param {'keep'|'han'|'zen'} [opts.alnum] 英数字の向き(既定 'han')
381
+ * @param {'keep'|'han'|'zen'} [opts.kana] カタカナと句読点・カギ括弧・中黒・長音の向き(既定 'zen')
382
+ * @param {'keep'|'han'|'zen'} [opts.symbol] 記号の向き(既定 'han')
383
+ * @param {'keep'|'han'|'zen'} [opts.space] スペースの向き(既定 'han')
384
+ * @param {boolean} [opts.collapseSpaces=false] 連続する空白を1つにまとめる
385
+ * @param {boolean} [opts.trimLines=false] 行頭・行末の空白を削る
386
+ * @param {'keep'|'collapse'|'remove'} [opts.blankLines='keep'] 空行の扱い
387
+ * @param {boolean} [opts.removeInvisible=false] 見えない文字を削る
388
+ * @param {boolean} [opts.composeMarks=false] 結合した濁点・半濁点を合成する(NFC)
389
+ * @param {boolean} [opts.inspect=false] 変換せず、何が入っているかの指摘だけを返す
390
+ * @param {'ja'|'en'} [opts.lang='ja'] 指摘事項の言語
391
+ */
392
+ export async function zenkakuConvertTool(opts = {}) {
393
+ const lang = opts.lang || 'ja';
394
+ if (lang !== 'ja' && lang !== 'en') throw new ZenkakuError(`lang は ja か en: ${opts.lang}`);
395
+
396
+ if (opts.preset !== undefined && !Object.prototype.hasOwnProperty.call(ZK_PRESETS, opts.preset)) {
397
+ throw new ZenkakuError(`preset は ${Object.keys(ZK_PRESETS).join(' / ')} のいずれか: ${opts.preset}`);
398
+ }
399
+ const preset = opts.preset ? ZK_PRESETS[opts.preset] : {};
400
+
401
+ const blankLines = opts.blankLines === undefined ? (preset.blankLines || 'keep') : opts.blankLines;
402
+ if (ZK_BLANK.indexOf(blankLines) === -1) {
403
+ throw new ZenkakuError(`blankLines は ${ZK_BLANK.join(' / ')} のいずれか: ${opts.blankLines}`);
404
+ }
405
+
406
+ const hasText = typeof opts.text === 'string';
407
+ if (hasText === Boolean(opts.path)) throw new ZenkakuError('text か path のどちらか一方を渡してください');
408
+
409
+ const flag = (name) => (opts[name] === undefined ? Boolean(preset[name]) : Boolean(opts[name]));
410
+ const dir = (name, fallback) => {
411
+ const given = pickDirection(opts[name], name);
412
+ if (given !== undefined) return given;
413
+ return preset[name] !== undefined ? preset[name] : fallback;
414
+ };
415
+
416
+ // inspect は「何も変えずに中身を見る」モード。指摘だけが欲しいときに使う
417
+ const request = opts.inspect
418
+ ? { alnum: 'keep', kana: 'keep', symbol: 'keep', space: 'keep', blankLines: 'keep' }
419
+ : {
420
+ alnum: dir('alnum', 'han'),
421
+ kana: dir('kana', 'zen'),
422
+ symbol: dir('symbol', 'han'),
423
+ space: dir('space', 'han'),
424
+ collapseSpaces: flag('collapseSpaces'),
425
+ trimLines: flag('trimLines'),
426
+ blankLines,
427
+ removeInvisible: flag('removeInvisible'),
428
+ composeMarks: flag('composeMarks'),
429
+ };
430
+
431
+ const input = hasText ? opts.text : await readFile(opts.path, 'utf8');
432
+ const r = zenkakuConvert({ ...request, text: input });
433
+
434
+ const notes = r.notes.slice();
435
+ const result = {
436
+ source: hasText ? { type: 'text' } : { path: opts.path, name: basename(opts.path) },
437
+ options: r.options,
438
+ stats: r.stats,
439
+ };
440
+ if (opts.preset) result.preset = opts.preset;
441
+
442
+ if (opts.inspect) {
443
+ result.inspect = true;
444
+ // 何も変えない指定なので「変更はありません」は情報にならない
445
+ const i = notes.findIndex((n) => n.code === 'UNCHANGED');
446
+ if (i !== -1) notes.splice(i, 1);
447
+ } else if (opts.outputPath) {
448
+ await writeFile(opts.outputPath, r.text, 'utf8');
449
+ result.output = opts.outputPath;
450
+ } else if ([...r.text].length > MAX_TEXT) {
451
+ result.text = [...r.text].slice(0, MAX_TEXT).join('');
452
+ notes.push({ code: 'TRUNCATED', count: MAX_TEXT });
453
+ } else {
454
+ result.text = r.text;
455
+ }
456
+
457
+ result.notes = notes.map((n) => ({
458
+ code: n.code,
459
+ message: NOTE_TEXT[lang][n.code] ? NOTE_TEXT[lang][n.code](n.count) : n.code,
460
+ }));
461
+ return result;
462
+ }