memd-cli 1.1.0 → 1.2.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/main.js CHANGED
@@ -102,7 +102,7 @@ function shouldUsePager(text, options) {
102
102
  function spawnPager(text, options) {
103
103
  // Respect $PAGER environment variable (like glow, bat, mdcat)
104
104
  const pagerCmd = process.env.PAGER || 'less';
105
- const pagerArgs = pagerCmd === 'less' ? ['-R'] : [];
105
+ const pagerArgs = pagerCmd === 'less' ? ['-R', ...(options.mouse !== false ? ['--mouse'] : [])] : [];
106
106
 
107
107
  const pager = spawn(pagerCmd, pagerArgs, {
108
108
  stdio: ['pipe', 'inherit', 'inherit']
@@ -133,6 +133,7 @@ async function main() {
133
133
  .description('Render markdown with mermaid diagrams to terminal output')
134
134
  .argument('[files...]', 'markdown file(s) to render')
135
135
  .option('--no-pager', 'disable pager (less)')
136
+ .option('--no-mouse', 'disable mouse scroll in pager')
136
137
  .option('--no-color', 'disable colored output')
137
138
  .option('--no-highlight', 'disable syntax highlighting')
138
139
  .option('--width <number>', 'terminal width override', Number)
package/package.json CHANGED
@@ -1,21 +1,32 @@
1
1
  {
2
2
  "name": "memd-cli",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "main": "main.js",
6
6
  "bin": {
7
7
  "memd": "main.js"
8
8
  },
9
+ "scripts": {
10
+ "test": "vitest run"
11
+ },
9
12
  "dependencies": {
10
13
  "beautiful-mermaid": "^0.1.3",
11
14
  "cli-highlight": "^2.1.11",
12
15
  "commander": "^14.0.3",
13
- "marked": "^15.0.12",
16
+ "marked": "^17.0.3",
14
17
  "marked-terminal": "^7.3.0"
15
18
  },
16
19
  "repository": {
17
20
  "type": "git",
18
21
  "url": "https://github.com/ktrysmt/memd.git"
19
22
  },
20
- "license": "MIT"
23
+ "license": "MIT",
24
+ "packageManager": "pnpm@10.15.1",
25
+ "devDependencies": {
26
+ "tuistory": "^0.0.16",
27
+ "vitest": "^4.0.18"
28
+ },
29
+ "pnpm": {
30
+ "onlyBuiltDependencies": ["esbuild", "node-pty"]
31
+ }
21
32
  }
package/plan.md ADDED
@@ -0,0 +1,283 @@
1
+ # memd TUI Outline Sidebar 設計案
2
+
3
+ ## 背景
4
+
5
+ memd は現在 `less` (または `$PAGER`) をフルスクリーンページャーとして使用している。
6
+ Markdown の見出し構造をサイドバーにアウトラインとして表示し、ナビゲーション可能にする機能を追加する。
7
+
8
+ ## TUI ライブラリ選定
9
+
10
+ | ライブラリ | 判定 | 理由 |
11
+ |---|---|---|
12
+ | blessed-contrib | 不採用 | 放棄済み (最終更新4年前)、未修正の Prototype Pollution 脆弱性 |
13
+ | Ink | 保留 | 最も活発だが React 依存が重い。軽量 CLI には過剰 |
14
+ | terminal-kit | 採用 | Node 18/20/22 対応、純 JS、既知脆弱性修正済み、ドキュメント良好 |
15
+
16
+ リスク: メンテナ1名、更新頻度低下傾向、79件のオープンイシュー積み残し。
17
+ terminal-kit 依存は `lib/tui.js` に閉じ込め、将来の差し替えに備える。
18
+
19
+ ## ディレクトリ構成
20
+
21
+ ```
22
+ memd/
23
+ main.js # エントリーポイント (CLI 解析 + モード分岐のみ)
24
+ lib/
25
+ markdown.js # Markdown 処理 (既存ロジックの抽出)
26
+ outline.js # 見出し抽出・アウトラインデータ生成
27
+ pager.js # 既存の less/pager ロジック
28
+ tui.js # terminal-kit TUI モード (新規)
29
+ test/
30
+ test1.md
31
+ test2.md
32
+ package.json
33
+ ```
34
+
35
+ ## モジュール設計
36
+
37
+ ### main.js -- エントリーポイント
38
+
39
+ CLI 解析 (commander) とモード分岐のみ。
40
+
41
+ ```
42
+ CLI 解析
43
+ |
44
+ +-- --outline あり & TTY --> tui.js (TUI モード)
45
+ +-- パイプ / --no-pager / 短い出力 --> stdout 直接出力
46
+ +-- 長い出力 --> pager.js (less モード)
47
+ ```
48
+
49
+ 追加オプション:
50
+
51
+ ```js
52
+ .option('--outline', 'show outline sidebar (TUI mode)')
53
+ ```
54
+
55
+ 分岐ロジック:
56
+
57
+ ```js
58
+ if (options.outline && process.stdout.isTTY) {
59
+ launchTui(markdown, renderedText, options);
60
+ } else if (shouldUsePager(renderedText, options)) {
61
+ spawnPager(renderedText, options);
62
+ } else {
63
+ process.stdout.write(renderedText);
64
+ }
65
+ ```
66
+
67
+ ### lib/markdown.js -- Markdown 処理
68
+
69
+ 既存の `main.js` から抽出する pure function 群。
70
+
71
+ ```js
72
+ export function readMarkdownFile(filePath)
73
+ // 現在の readMarkdownFile と同一
74
+
75
+ export function configureMarked(options)
76
+ // marked.use(...) の設定を集約
77
+
78
+ export function convertMermaidToAscii(markdown, options)
79
+ // 現在と同一
80
+
81
+ export function renderToString(markdown, options)
82
+ // 現在と同一
83
+
84
+ export function readStdin()
85
+ // 現在と同一
86
+ ```
87
+
88
+ ### lib/outline.js -- アウトライン抽出
89
+
90
+ terminal-kit に依存しない pure function。テスト容易。
91
+
92
+ ```js
93
+ /**
94
+ * Markdown ソースから見出しを抽出
95
+ * @param {string} markdown - 生の Markdown テキスト
96
+ * @returns {Array<{level: number, text: string, line: number}>}
97
+ *
98
+ * 例: [
99
+ * { level: 1, text: "Hello", line: 0 },
100
+ * { level: 2, text: "Section A", line: 15 },
101
+ * { level: 3, text: "Subsection A-1", line: 28 },
102
+ * ]
103
+ */
104
+ export function extractHeadings(markdown)
105
+
106
+ /**
107
+ * レンダリング済みテキスト内で各見出しが何行目に対応するか算出
108
+ * (スクロール位置ジャンプに使用)
109
+ * @param {string} renderedText - marked で変換済みの ANSI 文字列
110
+ * @param {Array} headings - extractHeadings の結果
111
+ * @returns {Array<{...heading, renderedLine: number}>}
112
+ */
113
+ export function mapHeadingsToRenderedLines(renderedText, headings)
114
+ ```
115
+
116
+ ### lib/pager.js -- Pager 処理
117
+
118
+ ```js
119
+ export function shouldUsePager(text, options)
120
+ // 現在と同一
121
+
122
+ export function spawnPager(text, options)
123
+ // 現在と同一
124
+ ```
125
+
126
+ ### lib/tui.js -- TUI モード (新規コア)
127
+
128
+ terminal-kit 依存はこのファイルに閉じ込める。
129
+ `--outline` 指定時のみ動的 import で読み込み、通常利用時のロード時間に影響しない。
130
+
131
+ ```js
132
+ import termkit from 'terminal-kit';
133
+
134
+ /**
135
+ * TUI モードを起動
136
+ * @param {string} markdown - 生の Markdown ソース
137
+ * @param {string} renderedText - レンダリング済みテキスト
138
+ * @param {object} options - CLI オプション
139
+ */
140
+ export function launchTui(markdown, renderedText, options)
141
+ ```
142
+
143
+ 内部関数:
144
+
145
+ ```
146
+ launchTui(markdown, renderedText, options)
147
+ |
148
+ +-- createLayout(term)
149
+ | ターミナル幅を取得し、左右のカラム幅を決定
150
+ | 左: サイドバー (幅の 25%, 最小 20, 最大 40)
151
+ | 右: コンテンツ (残り)
152
+ | 戻り値: { sidebarWidth, contentWidth, height }
153
+ |
154
+ +-- renderSidebar(term, headings, selectedIndex, scrollOffset, layout)
155
+ | アウトラインを左カラムに描画
156
+ | 選択中の見出しをハイライト
157
+ | インデント: level に応じて 2*(level-1) スペース
158
+ |
159
+ +-- renderContent(term, lines, scrollOffset, layout)
160
+ | レンダリング済みテキストを右カラムに描画
161
+ | contentWidth に合わせて行を切り詰め
162
+ |
163
+ +-- renderStatusBar(term, state, layout)
164
+ | 最下行にステータス表示
165
+ | "[q]quit [j/k]navigate [Enter]jump [Tab]toggle sidebar"
166
+ |
167
+ +-- setupKeyBindings(term, state)
168
+ キー入力ハンドラ登録
169
+ ```
170
+
171
+ キーバインド:
172
+
173
+ | キー | 動作 |
174
+ |---|---|
175
+ | j / Down | 次の見出し |
176
+ | k / Up | 前の見出し |
177
+ | Enter | 選択した見出しの位置にコンテンツをスクロール |
178
+ | g / G | 先頭 / 末尾 |
179
+ | Ctrl+D / Ctrl+U | 半ページスクロール |
180
+ | Tab | サイドバーフォーカス切替 |
181
+ | q / Ctrl+C | 終了 |
182
+
183
+ ## 画面レイアウト
184
+
185
+ ```
186
+ +-- Outline (25%) --+-- Content (75%) --------------------------+
187
+ | # Hello | # Hello |
188
+ | ## Section A | |
189
+ | ## Section B | This is **markdown** printed in the |
190
+ | > ## Section C < | `terminal`. |
191
+ | ### C-1 | |
192
+ | ### C-2 | ## Section C |
193
+ | ## Section D | |
194
+ | | Lorem ipsum dolor sit amet... |
195
+ | | ... |
196
+ +-------------------+--------------------------------------------+
197
+ [q]quit [j/k]move [Enter]jump [Tab]focus Section C 3/6
198
+ ```
199
+
200
+ ## データフロー
201
+
202
+ ```
203
+ markdown (raw)
204
+ |
205
+ +------------+------------+
206
+ | |
207
+ extractHeadings() configureMarked()
208
+ | renderToString()
209
+ | |
210
+ headings[] renderedText
211
+ | |
212
+ mapHeadingsToRenderedLines() |
213
+ | |
214
+ headings[] with |
215
+ renderedLine |
216
+ | |
217
+ +-------+ +--------------+
218
+ | |
219
+ launchTui()
220
+ or spawnPager()
221
+ or stdout.write()
222
+ ```
223
+
224
+ ## 設計上のポイント
225
+
226
+ 1. **既存モードへの影響ゼロ** -- `--outline` なしなら従来通り `less` または stdout。TUI は `--outline` 時のみ動的ロードする
227
+ 2. **モジュール分割は最小限** -- `tui.js` + `outline.js` の 2 ファイル追加のみ。`main.js` の既存ロジック (markdown 処理, pager) はそのまま残す。小さな CLI に不要な分割はしない
228
+ 3. **outline.js は pure function** -- TUI ライブラリに依存しない。単体テスト可能
229
+ 4. **TUI 依存は tui.js に閉じ込める** -- 将来別ライブラリに差し替える場合も tui.js だけ書き換えればよい
230
+
231
+ ## レビュー指摘事項 (2026-03-07)
232
+
233
+ ### terminal-kit 選定リスクの再評価
234
+
235
+ メンテナ1名 + 79件のオープンイシュー積み残しは「リスク」ではなく「既に問題化」に近い。
236
+ memd の TUI は比較的シンプル (2カラムレイアウト + キー入力) なので、以下の代替案も検討する:
237
+
238
+ - **案A: terminal-kit 採用** (現行案) -- 機能は豊富だがメンテナンス不安
239
+ - **案B: 自前 ANSI 実装** -- `process.stdout.write` + ANSI エスケープ + `readline` rawMode で実現。依存ゼロ。memd の TUI 要件 (2カラム描画, キー入力, カーソル制御) は Node.js 標準 API で十分カバー可能
240
+
241
+ ### mapHeadingsToRenderedLines の実装方針
242
+
243
+ ANSI エスケープ付きレンダリング済みテキストから見出し位置を特定する必要がある。
244
+ marked-terminal の出力には以下の複雑性がある:
245
+
246
+ - ANSI カラーコード
247
+ - reflowText による折り返し
248
+ - テーブル・コードブロックの展開
249
+
250
+ 実装方針: レンダリング後テキストを `strip-ansi` して各行を走査し、見出しテキスト (extractHeadings の結果) と前方一致でマッチさせる。
251
+ 完全一致が困難な場合は、marked のレンダリング時にカスタム renderer で見出し行にマーカー文字列を埋め込み、レンダリング後にマーカーで検索する方式をフォールバックとする。
252
+
253
+ ### コンテンツ描画時の ANSI 対応
254
+
255
+ - 行の切り詰め (truncate) 時に ANSI エスケープシーケンスの途中で切断すると表示が崩れる
256
+ - `strip-ansi` + `string-width` を利用して表示幅を正確に算出し、ANSI シーケンスを壊さない切り詰め処理が必要
257
+ - TUI モードでは marked-terminal の `width` オプションをコンテンツカラム幅に合わせて設定する (全幅ではなく右カラム幅)
258
+
259
+ ### ターミナルリサイズ対応
260
+
261
+ `process.stdout.on('resize', ...)` (SIGWINCH) でリサイズイベントを検知し、レイアウトを再計算して再描画する。
262
+
263
+ ### Tab フォーカス切替時の UX 定義
264
+
265
+ - サイドバーフォーカス時: j/k で見出し間を移動、Enter でコンテンツをジャンプ
266
+ - コンテンツフォーカス時: j/k で 1 行単位スクロール、g/G で先頭/末尾
267
+
268
+ ## モジュール分割方針 (修正)
269
+
270
+ `main.js` の既存ロジック (readMarkdownFile, convertMermaidToAscii, renderToString, readStdin, shouldUsePager, spawnPager) はそのまま残す。
271
+ 新規追加は以下の 2 ファイルのみ:
272
+
273
+ ```
274
+ memd/
275
+ main.js # エントリーポイント (既存 + --outline 分岐追加)
276
+ lib/
277
+ outline.js # 見出し抽出・アウトラインデータ生成 (pure function, 新規)
278
+ tui.js # TUI モード (新規)
279
+ test/
280
+ test1.md
281
+ test2.md
282
+ package.json
283
+ ```
package/planb.md ADDED
@@ -0,0 +1,186 @@
1
+ # 案B: 自前 ANSI 実装による TUI モード設計
2
+
3
+ ## 方針
4
+
5
+ terminal-kit を使わず、Node.js 標準 API + ANSI エスケープシーケンスのみで TUI を実装する。
6
+ memd の TUI 要件 (2カラム描画 + キー入力 + スクロール) は限定的であり、外部依存なしで実現可能。
7
+
8
+ ## 使用する Node.js 標準 API
9
+
10
+ | 用途 | API |
11
+ |---|---|
12
+ | 画面描画 | `process.stdout.write` + ANSI エスケープシーケンス |
13
+ | キー入力 | `readline.emitKeypressEvents` + `process.stdin.setRawMode(true)` |
14
+ | 画面サイズ | `process.stdout.columns` / `process.stdout.rows` |
15
+ | リサイズ検知 | `process.stdout.on('resize', ...)` |
16
+
17
+ 外部依存は `strip-ansi` と `string-width` のみ (いずれも marked-terminal の transitive dep として既存)。
18
+
19
+ ## ANSI エスケープの基本操作
20
+
21
+ ```js
22
+ const ESC = '\x1b[';
23
+ const cursor = {
24
+ moveTo: (x, y) => `${ESC}${y + 1};${x + 1}H`,
25
+ hide: `${ESC}?25l`,
26
+ show: `${ESC}?25h`,
27
+ clearScreen: `${ESC}2J`,
28
+ clearLine: `${ESC}2K`,
29
+ };
30
+ const style = {
31
+ reverse: `${ESC}7m`,
32
+ reset: `${ESC}0m`,
33
+ dim: `${ESC}2m`,
34
+ bold: `${ESC}1m`,
35
+ };
36
+ ```
37
+
38
+ ## モジュール構成
39
+
40
+ ```
41
+ memd/
42
+ main.js # エントリーポイント (既存 + --outline 分岐追加)
43
+ lib/
44
+ outline.js # 見出し抽出・アウトラインデータ生成 (pure function, 新規)
45
+ tui.js # TUI モード (新規, 自前 ANSI 実装)
46
+ test/
47
+ test1.md
48
+ test2.md
49
+ package.json
50
+ ```
51
+
52
+ ## tui.js の内部構造
53
+
54
+ ```
55
+ launchTui(markdown, renderedText, headings, options)
56
+ |
57
+ +-- state = {
58
+ | sidebarFocused: true,
59
+ | selectedHeading: 0,
60
+ | contentScroll: 0,
61
+ | sidebarScroll: 0,
62
+ | layout: computeLayout(),
63
+ | }
64
+ |
65
+ +-- computeLayout()
66
+ | cols = process.stdout.columns
67
+ | rows = process.stdout.rows
68
+ | sidebarWidth = clamp(Math.floor(cols * 0.25), 20, 40)
69
+ | contentWidth = cols - sidebarWidth - 1 // 1 for separator
70
+ | height = rows - 1 // 1 for status bar
71
+ |
72
+ +-- render(state)
73
+ | buf = ''
74
+ | buf += cursor.hide
75
+ | buf += renderSidebar(state)
76
+ | buf += renderSeparator(state)
77
+ | buf += renderContent(state)
78
+ | buf += renderStatusBar(state)
79
+ | process.stdout.write(buf) // 1回の write でフリッカー軽減
80
+ |
81
+ +-- renderSidebar(state)
82
+ | 各見出しを sidebarWidth 内に収めて描画
83
+ | 選択行は reverse video で表示
84
+ | level に応じて 2*(level-1) スペースでインデント
85
+ |
86
+ +-- renderSeparator(state)
87
+ | 縦線 '|' を各行の sidebarWidth 位置に描画
88
+ |
89
+ +-- renderContent(state)
90
+ | renderedText を行分割済み配列として保持
91
+ | contentScroll から height 行分を描画
92
+ | 各行を contentWidth でスライス (ANSI 対応)
93
+ |
94
+ +-- renderStatusBar(state)
95
+ | 最下行にキーバインドヘルプ + 現在位置表示
96
+ |
97
+ +-- handleKeypress(key, state)
98
+ keypress イベントから state を更新し render() を呼ぶ
99
+ ```
100
+
101
+ ## キー入力の実装
102
+
103
+ ```js
104
+ import readline from 'readline';
105
+
106
+ readline.emitKeypressEvents(process.stdin);
107
+ process.stdin.setRawMode(true);
108
+ process.stdin.on('keypress', (str, key) => {
109
+ if (key.name === 'q' || (key.ctrl && key.name === 'c')) {
110
+ cleanup();
111
+ process.exit(0);
112
+ }
113
+ handleKeypress(key, state);
114
+ render(state);
115
+ });
116
+ ```
117
+
118
+ ### キーバインド
119
+
120
+ | キー | サイドバーフォーカス時 | コンテンツフォーカス時 |
121
+ |---|---|---|
122
+ | j / Down | 次の見出し | 1行下スクロール |
123
+ | k / Up | 前の見出し | 1行上スクロール |
124
+ | Enter | 選択した見出しの位置にコンテンツをスクロール | -- |
125
+ | g / G | 先頭 / 末尾 | 先頭 / 末尾 |
126
+ | Ctrl+D / Ctrl+U | -- | 半ページスクロール |
127
+ | Tab | コンテンツへフォーカス移動 | サイドバーへフォーカス移動 |
128
+ | q / Ctrl+C | 終了 | 終了 |
129
+
130
+ ## フリッカー対策
131
+
132
+ - 毎フレーム `clearScreen` せず、各行を `moveTo` + `clearLine` + 描画で上書き
133
+ - 全描画内容を文字列バッファに溜めてから1回の `process.stdout.write(buf)` で出力
134
+
135
+ ## ANSI 対応の行スライス
136
+
137
+ コンテンツ行を `contentWidth` に切り詰める際の処理:
138
+
139
+ ```js
140
+ function sliceAnsiLine(line, maxWidth) {
141
+ // 1. ANSI エスケープを位置情報付きで分離
142
+ // 2. 表示文字の幅を string-width で計測しながら maxWidth まで切り詰め
143
+ // 3. 切り詰め後に開いたままの ANSI シーケンスを reset で閉じる
144
+ }
145
+ ```
146
+
147
+ ## cleanup 処理
148
+
149
+ ```js
150
+ function cleanup() {
151
+ process.stdout.write(cursor.show);
152
+ process.stdout.write(cursor.clearScreen);
153
+ process.stdout.write(cursor.moveTo(0, 0));
154
+ process.stdin.setRawMode(false);
155
+ }
156
+ // 異常終了時もクリーンアップ
157
+ process.on('exit', cleanup);
158
+ process.on('SIGINT', () => { cleanup(); process.exit(0); });
159
+ ```
160
+
161
+ ## ターミナルリサイズ対応
162
+
163
+ ```js
164
+ process.stdout.on('resize', () => {
165
+ state.layout = computeLayout();
166
+ render(state);
167
+ });
168
+ ```
169
+
170
+ ## mapHeadingsToRenderedLines の実装方針
171
+
172
+ ANSI 付きレンダリング済みテキストから見出し位置を特定する:
173
+
174
+ 1. レンダリング後テキストを `strip-ansi` して各行を走査
175
+ 2. `extractHeadings` の結果と前方一致でマッチさせる
176
+ 3. フォールバック: marked のカスタム renderer で見出し行にマーカー文字列を埋め込み、レンダリング後にマーカーで検索
177
+
178
+ ## 案A (terminal-kit) との比較
179
+
180
+ | | 案A (terminal-kit) | 案B (自前 ANSI) |
181
+ |---|---|---|
182
+ | 外部依存 | +1 (terminal-kit, ~2MB) | +0 (strip-ansi, string-width は既存 transitive dep) |
183
+ | 実装量 | 少ない (API 呼ぶだけ) | 中程度 (~200行の描画コード) |
184
+ | メンテリスク | メンテナ1名、更新頻度低下 | 自前なので自己責任 |
185
+ | 機能カバー | 豊富 (使わない機能も多い) | 必要最小限 |
186
+ | インストール速度 | native module なし、影響軽微 | 影響なし |
@@ -0,0 +1,117 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { launchTerminal } from 'tuistory'
3
+ import path from 'path'
4
+ import { fileURLToPath } from 'url'
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
7
+ const MAIN = path.join(__dirname, '..', 'main.js')
8
+
9
+ async function run(args, { waitFor = null } = {}) {
10
+ const session = await launchTerminal({
11
+ command: 'node',
12
+ args: [MAIN, ...args],
13
+ cols: 80,
14
+ rows: 30,
15
+ waitForData: false,
16
+ })
17
+ const waitText = waitFor ?? (t => t.trim().length > 0)
18
+ const output = await session.text({ waitFor: waitText, timeout: 8000 })
19
+ return output.trim()
20
+ }
21
+
22
+ describe('memd CLI', () => {
23
+ it('--version', async () => {
24
+ const output = await run(['-v'])
25
+ expect(output).toContain('1.1.1')
26
+ })
27
+
28
+ it('--help', async () => {
29
+ const output = await run(['--help'])
30
+ expect(output).toContain('Usage: memd')
31
+ expect(output).toContain('--no-pager')
32
+ expect(output).toContain('--no-color')
33
+ expect(output).toContain('--ascii')
34
+ })
35
+
36
+ it('renders test1.md (basic markdown + mermaid)', async () => {
37
+ const output = await run(
38
+ ['--no-pager', '--no-color', '--width', '80', 'test/test1.md'],
39
+ { waitFor: t => t.includes('More text.') },
40
+ )
41
+ expect(output).toMatchInlineSnapshot(`
42
+ "# Hello
43
+
44
+ This is markdown with mermaid:
45
+
46
+ ┌───┐ ┌───┐
47
+ │ │ │ │
48
+ │ A ├────►│ B │
49
+ │ │ │ │
50
+ └───┘ └───┘
51
+ More text."
52
+ `)
53
+ })
54
+
55
+ it('renders test2.md (complex mermaid diagram)', async () => {
56
+ const output = await run(
57
+ ['--no-pager', '--no-color', '--width', '80', 'test/test2.md'],
58
+ { waitFor: t => t.includes('More text after the diagram.') },
59
+ )
60
+ expect(output).toContain('Start')
61
+ expect(output).toContain('Decision?')
62
+ expect(output).toContain('Action')
63
+ expect(output).toContain('End')
64
+ expect(output).toContain('More text after the diagram.')
65
+ })
66
+
67
+ it('--ascii renders ASCII-only diagram', async () => {
68
+ const output = await run(
69
+ ['--no-pager', '--no-color', '--width', '80', '--ascii', 'test/test1.md'],
70
+ { waitFor: t => t.includes('More text.') },
71
+ )
72
+ expect(output).toContain('+---+')
73
+ expect(output).toContain('---->')
74
+ expect(output).not.toContain('┌')
75
+ expect(output).not.toContain('►')
76
+ })
77
+
78
+ it('--no-color strips ANSI escape codes', async () => {
79
+ const output = await run(
80
+ ['--no-pager', '--no-color', '--width', '80', 'test/test1.md'],
81
+ { waitFor: t => t.includes('More text.') },
82
+ )
83
+ // eslint-disable-next-line no-control-regex
84
+ expect(output).not.toMatch(/\x1b\[[\d;]*m/)
85
+ })
86
+
87
+ it('error on missing file', async () => {
88
+ const session = await launchTerminal({
89
+ command: 'node',
90
+ args: [MAIN, '--no-pager', 'test/nonexistent.md'],
91
+ cols: 80,
92
+ rows: 10,
93
+ waitForData: false,
94
+ })
95
+ const output = (await session.text({
96
+ waitFor: t => t.includes('Error'),
97
+ timeout: 8000,
98
+ })).trim()
99
+ expect(output).toContain('Error reading file')
100
+ expect(output).toContain('nonexistent.md')
101
+ })
102
+
103
+ it('reads markdown from stdin via shell', async () => {
104
+ const session = await launchTerminal({
105
+ command: 'sh',
106
+ args: ['-c', `echo '# stdin test' | node ${MAIN} --no-pager --no-color`],
107
+ cols: 80,
108
+ rows: 10,
109
+ waitForData: false,
110
+ })
111
+ const output = (await session.text({
112
+ waitFor: t => t.includes('stdin test'),
113
+ timeout: 8000,
114
+ })).trim()
115
+ expect(output).toContain('stdin test')
116
+ })
117
+ })
@@ -1,7 +0,0 @@
1
- {
2
- "permissions": {
3
- "deny": [
4
- "Read(./.entire/metadata/**)"
5
- ]
6
- }
7
- }
@@ -1,12 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "Bash(npx:*)",
5
- "Bash(npmwhoami)",
6
- "Bash(LINES=20 node main.js:*)",
7
- "Bash(LINES=10 node:*)",
8
- "Bash(1)",
9
- "Bash(DEBUG=1 node main.js:*)"
10
- ]
11
- }
12
- }
@@ -1,31 +0,0 @@
1
- # termaid Project Overview
2
-
3
- ## Purpose
4
- termaid is a CLI tool that renders Mermaid diagrams in markdown files to ASCII art for terminal display. It converts ```mermaid code blocks to terminal-friendly ASCII diagrams.
5
-
6
- ## Tech Stack
7
- - Runtime: Node.js (ES modules)
8
- - Markdown parser: marked + marked-terminal
9
- - Mermaid rendering: beautiful-mermaid
10
-
11
- ## Key Files
12
- - main.js - Entry point (ESM module)
13
- - package.json - Project metadata and dependencies
14
- - test/ - Test markdown files
15
-
16
- ## Project Structure
17
- ```
18
- ├── main.js # Main CLI entry point
19
- ├── package.json
20
- ├── test/
21
- │ ├── test1.md # Basic flowchart test
22
- │ ├── test2.md # Decision flowchart test
23
- │ └── test3.md # Complex diagrams (sequence, class, state)
24
- ├── README.md
25
- └── .gitignore
26
- ```
27
-
28
- ## Code Style
29
- - ES modules (`import`/`export`)
30
- - No TypeScript types (has `// @ts-nocheck`)
31
- - Simple, functional approach
@@ -1,111 +0,0 @@
1
- # Publishing to npm
2
-
3
- ## Current Status
4
- - Package name: `@ktrysmt/termaid` (Scoped package under ktrysmt org)
5
- - Version: 1.0.3 (from package.json)
6
- - Status: NOT YET published (E404 when checking registry)
7
-
8
- ## Prerequisites
9
-
10
- ### 1. npm Account
11
- - Create an account at https://www.npmjs.com/
12
- - Login with: `npm login`
13
-
14
- ### 2. Package Name Considerations
15
- - `@ktrysmt/termaid` requires write access to the `ktrysmt` scope
16
- - If you don't have access, you can:
17
- - Use a different scope: `@yourname/termaid`
18
- - Use an unscoped package: `termaid` (check availability first)
19
-
20
- ## Publish Steps
21
-
22
- ### Step 1: Verify package.json
23
- Check these fields:
24
- ```json
25
- {
26
- "name": "@ktrysmt/termaid",
27
- "version": "1.0.3",
28
- "main": "main.js",
29
- "bin": {
30
- "termaid": "main.js"
31
- },
32
- "repository": {
33
- "type": "git",
34
- "url": "https://github.com/ktrysmt/termaid.git"
35
- }
36
- }
37
- ```
38
-
39
- ### Step 2: Login to npm
40
- ```bash
41
- npm login
42
- # Follow prompts for username, password, email
43
- ```
44
-
45
- ### Step 3: Check Package Access
46
- ```bash
47
- npm access ls-collaborators @ktrysmt/termaid
48
- ```
49
-
50
- ### Step 4: Publish
51
- ```bash
52
- npm publish
53
- ```
54
-
55
- ### Step 5: Verify
56
- ```bash
57
- npm view @ktrysmt/termaid
58
- npm install -g @ktrysmt/termaid
59
- ```
60
-
61
- ## Version Management
62
-
63
- ### Bump version before publish:
64
- ```bash
65
- # Patch (bug fixes): 1.0.2 -> 1.0.3
66
- npm version patch
67
-
68
- # Minor (new features): 1.0.2 -> 1.1.0
69
- npm version minor
70
-
71
- # Major (breaking changes): 1.0.2 -> 2.0.0
72
- npm version major
73
- ```
74
-
75
- ### Or manually edit package.json, then:
76
- ```bash
77
- git add .
78
- git commit -m "chore: bump version"
79
- git tag v1.0.3 # or new version
80
- git push && git push --tags
81
- npm publish
82
- ```
83
-
84
- ## Private vs Public
85
-
86
- ### Public (default):
87
- ```bash
88
- npm publish
89
- # Accessible to everyone
90
- ```
91
-
92
- ### Private (requires paid plan):
93
- ```bash
94
- npm publish --access restricted
95
- # Only accessible to collaborators
96
- ```
97
-
98
- ### Public with scoped package (free):
99
- ```bash
100
- npm publish --access public
101
- # Works for scoped packages under free plan
102
- ```
103
-
104
- ## Common Issues
105
-
106
- | Issue | Solution |
107
- |-------|----------|
108
- | E403 Forbidden | You don't have access to this scope |
109
- | E409 Conflict | Version already exists, bump version |
110
- | ENEEDAUTH | Run `npm login` first |
111
- | EMISSINGARG | Missing name/version in package.json |
@@ -1,19 +0,0 @@
1
- # Suggested Commands for termaid
2
-
3
- ## Testing
4
- - `node main.js test/test1.md` - Test with test1.md
5
- - `node main.js test/test2.md` - Test with test2.md
6
- - `echo '# Hello\n\n```mermaid\nflowchart LR\n A --> B\n```' | node main.js` - Test with stdin
7
-
8
- ## Version Management
9
- - Check current version: `node main.js -v`
10
-
11
- ## Development
12
- - Install dependencies: `npm install`
13
- - Run with a markdown file: `node main.js <file.md>`
14
-
15
- ## Publishing (to npm)
16
- 1. Check current version in package.json
17
- 2. Update version (e.g., `npm version patch` or `npm version minor`)
18
- 3. Login: `npm login`
19
- 4. Publish: `npm publish`
@@ -1,115 +0,0 @@
1
-
2
- # whether to use the project's gitignore file to ignore files
3
- # Added on 2025-04-07
4
- ignore_all_files_in_gitignore: true
5
- # list of additional paths to ignore
6
- # same syntax as gitignore, so you can use * and **
7
- # Was previously called `ignored_dirs`, please update your config if you are using that.
8
- # Added (renamed) on 2025-04-07
9
- ignored_paths: []
10
-
11
- # whether the project is in read-only mode
12
- # If set to true, all editing tools will be disabled and attempts to use them will result in an error
13
- # Added on 2025-04-18
14
- read_only: false
15
-
16
-
17
- # list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
18
- # Below is the complete list of tools for convenience.
19
- # To make sure you have the latest list of tools, and to view their descriptions,
20
- # execute `uv run scripts/print_tool_overview.py`.
21
- #
22
- # * `activate_project`: Activates a project by name.
23
- # * `check_onboarding_performed`: Checks whether project onboarding was already performed.
24
- # * `create_text_file`: Creates/overwrites a file in the project directory.
25
- # * `delete_lines`: Deletes a range of lines within a file.
26
- # * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
27
- # * `execute_shell_command`: Executes a shell command.
28
- # * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
29
- # * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
30
- # * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
31
- # * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
32
- # * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
33
- # * `initial_instructions`: Gets the initial instructions for the current project.
34
- # Should only be used in settings where the system prompt cannot be set,
35
- # e.g. in clients you have no control over, like Claude Desktop.
36
- # * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
37
- # * `insert_at_line`: Inserts content at a given line in a file.
38
- # * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
39
- # * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
40
- # * `list_memories`: Lists memories in Serena's project-specific memory store.
41
- # * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
42
- # * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
43
- # * `read_file`: Reads a file within the project directory.
44
- # * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
45
- # * `remove_project`: Removes a project from the Serena configuration.
46
- # * `replace_lines`: Replaces a range of lines within a file with new content.
47
- # * `replace_symbol_body`: Replaces the full definition of a symbol.
48
- # * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
49
- # * `search_for_pattern`: Performs a search for a pattern in the project.
50
- # * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
51
- # * `switch_modes`: Activates modes by providing a list of their names
52
- # * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
53
- # * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
54
- # * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
55
- # * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
56
- excluded_tools: []
57
-
58
- # initial prompt for the project. It will always be given to the LLM upon activating the project
59
- # (contrary to the memories, which are loaded on demand).
60
- initial_prompt: ""
61
- # the name by which the project can be referenced within Serena
62
- project_name: "termaid"
63
-
64
- # list of mode names to that are always to be included in the set of active modes
65
- # The full set of modes to be activated is base_modes + default_modes.
66
- # If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
67
- # Otherwise, this setting overrides the global configuration.
68
- # Set this to [] to disable base modes for this project.
69
- # Set this to a list of mode names to always include the respective modes for this project.
70
- base_modes:
71
-
72
- # list of mode names that are to be activated by default.
73
- # The full set of modes to be activated is base_modes + default_modes.
74
- # If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
75
- # Otherwise, this overrides the setting from the global configuration (serena_config.yml).
76
- # This setting can, in turn, be overridden by CLI parameters (--mode).
77
- default_modes:
78
-
79
- # list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default)
80
- included_optional_tools: []
81
-
82
- # fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
83
- # This cannot be combined with non-empty excluded_tools or included_optional_tools.
84
- fixed_tools: []
85
-
86
- # the encoding used by text files in the project
87
- # For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
88
- encoding: utf-8
89
-
90
-
91
- # list of languages for which language servers are started; choose from:
92
- # al bash clojure cpp csharp
93
- # csharp_omnisharp dart elixir elm erlang
94
- # fortran fsharp go groovy haskell
95
- # java julia kotlin lua markdown
96
- # matlab nix pascal perl php
97
- # php_phpactor powershell python python_jedi r
98
- # rego ruby ruby_solargraph rust scala
99
- # swift terraform toml typescript typescript_vts
100
- # vue yaml zig
101
- # (This list may be outdated. For the current list, see values of Language enum here:
102
- # https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
103
- # For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
104
- # Note:
105
- # - For C, use cpp
106
- # - For JavaScript, use typescript
107
- # - For Free Pascal/Lazarus, use pascal
108
- # Special requirements:
109
- # Some languages require additional setup/installations.
110
- # See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
111
- # When using multiple languages, the first language server that supports a given file will be used for that file.
112
- # The first language is the default language and the respective language server will be used as a fallback.
113
- # Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
114
- languages:
115
- - typescript