memd-cli 1.0.4

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.
@@ -0,0 +1,7 @@
1
+ {
2
+ "permissions": {
3
+ "deny": [
4
+ "Read(./.entire/metadata/**)"
5
+ ]
6
+ }
7
+ }
@@ -0,0 +1,12 @@
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
+ }
@@ -0,0 +1,31 @@
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
@@ -0,0 +1,111 @@
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 |
@@ -0,0 +1,19 @@
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`
@@ -0,0 +1,115 @@
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
package/CLAUDE.md ADDED
@@ -0,0 +1,4 @@
1
+ ## how to test
2
+
3
+ - `node main.js test/test1.md`
4
+ - `node main.js test/test2.md`
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ktrysmt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,302 @@
1
+ # memd
2
+
3
+ > View mermaid-ed markdown in terminal
4
+
5
+ ## Install/Update
6
+
7
+ ```bash
8
+ npm install -g memd-cli
9
+ ```
10
+
11
+
12
+ ## Usage
13
+
14
+ ### File input
15
+
16
+ ```
17
+ $ memd test/test1.md
18
+ # Hello
19
+
20
+ This is markdown with mermaid:
21
+
22
+ ┌───┐ ┌───┐
23
+ │ │ │ │
24
+ │ A ├────►│ B │
25
+ │ │ │ │
26
+ └───┘ └───┘
27
+
28
+ More text.
29
+
30
+ ```
31
+
32
+ ### test2.md - flowchart with decision
33
+
34
+ ```
35
+ $ memd test/test2.md
36
+ # Hello
37
+
38
+ This is markdown printed in the terminal.
39
+
40
+ ┌───────────┐
41
+ │ │
42
+ │ Start │
43
+ │ │
44
+ └─────┬─────┘
45
+
46
+
47
+
48
+
49
+
50
+ ┌───────────┐
51
+ │ │
52
+ │ Decision? ├──No────┐
53
+ │ │ │
54
+ └─────┬─────┘ │
55
+ │ │
56
+ │ │
57
+ Yes │
58
+ │ │
59
+ ▼ ▼
60
+ ┌───────────┐ ┌─────┐
61
+ │ │ │ │
62
+ │ Action ├────►│ End │
63
+ │ │ │ │
64
+ └───────────┘ └─────┘
65
+
66
+ More text after the diagram.
67
+
68
+ ```
69
+
70
+ ### test3.md - Complex Mermaid diagrams (English)
71
+
72
+ ```
73
+ $ memd test/test3.md
74
+ # Complex Mermaid Diagrams Test
75
+
76
+ ## flowchart LR Test
77
+
78
+ ┌────────────────┐ ┌──────────┐ ┌──────────┐ ┌─────┐
79
+ │ │ │ │ │ │ │ │
80
+ │ Starting Point ├────►│ Decision ├─Yes►│ Action 1 ├────►│ End │
81
+ │ │ │ │ │ │ │ │
82
+ └────────────────┘ └─────┬────┘ └──────────┘ └─────┘
83
+ │ ▲
84
+ │ │
85
+ │ │
86
+ No │
87
+ │ │
88
+ │ ┌──────────┐ │
89
+ │ │ │ │
90
+ └─────────►│ Action 2 ├────────┘
91
+ │ │
92
+ └──────────┘
93
+
94
+ ┌──────────┐ ┌────────────────┐ ┌────────────┐ ┌───────┐
95
+ │ │ │ │ │ │ │ │
96
+ │ Database ├────►│ Authentication ├────►│ API Server ├◄───►┤ Redis │
97
+ │ │ │ │ │ │ │ │
98
+ └──────────┘ └────────────────┘ └──────┬─────┘ └───────┘
99
+ ▲ │
100
+ └────────────────────────────────────────┘
101
+
102
+
103
+ ## Sequence Diagram
104
+
105
+ ┌────────┐ ┌────────┐ ┌──────────┐ ┌───────┐
106
+ │ Client │ │ Server │ │ Database │ │ Cache │
107
+ └────┬───┘ └────┬───┘ └─────┬────┘ └───┬───┘
108
+ │ │ │ │
109
+ │ HTTP GET /api/data │ │ │
110
+ │───────────────────────▶ │ │
111
+ │ │ HGET user:123 │
112
+ │ │─────────────────────────▶
113
+ │ │ │ │
114
+ │ │ data (hit) │
115
+ │ ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│
116
+ │ │ │ │
117
+ │ 200 OK │ │ │
118
+ ◀───────────────────────│ │ │
119
+ │ │ │ │
120
+ ┌────┴───┐ ┌────┴───┐ ┌─────┴────┐ ┌───┴───┐
121
+ │ Client │ │ Server │ │ Database │ │ Cache │
122
+ └────────┘ └────────┘ └──────────┘ └───────┘
123
+
124
+ ## Class Diagram
125
+
126
+ ┌───────────────┐
127
+ │ Animal │
128
+ ├───────────────┤
129
+ │ +name: String │
130
+ ├───────────────┤
131
+ │ +eat │
132
+ │ +sleep │
133
+ └───────────────┘
134
+
135
+ ┌─└────────────┐
136
+ │ │
137
+ ┌──────────┐ ┌────────┐
138
+ │ Bird │ │ Fish │
139
+ ├──────────┤ ├────────┤
140
+ │ │ │ │
141
+ ├──────────┤ ├────────┤
142
+ │ +fly │ │ +swim │
143
+ │ +layEggs │ │ +gills │
144
+ └──────────┘ └────────┘
145
+
146
+
147
+ ## State Diagram
148
+
149
+ ┌────────┐
150
+ │ │
151
+ │ │
152
+ │ │
153
+ └────┬───┘
154
+
155
+
156
+
157
+
158
+
159
+ ┌────────┐
160
+ │ │
161
+ │ Still │
162
+ │ │
163
+ └────┬───┘
164
+
165
+
166
+
167
+
168
+
169
+ ┌────┴───┐
170
+ │ │
171
+ │ Moving │
172
+ │ │
173
+ └────┬───┘
174
+
175
+
176
+
177
+
178
+
179
+ ┌────────┐
180
+ │ │
181
+ │ Crash │
182
+ │ │
183
+ └────┬───┘
184
+
185
+
186
+
187
+
188
+
189
+ ┌────────┐
190
+ │ │
191
+ │ │
192
+ │ │
193
+ └────────┘
194
+
195
+ ## Error Handling Example
196
+
197
+ ┌──────────────┐
198
+ │ │
199
+ │ Start │
200
+ │ │
201
+ └───────┬──────┘
202
+
203
+
204
+
205
+
206
+
207
+ ┌──────────────┐
208
+ │ │
209
+ │ Check Error? ├─────No──────┐
210
+ │ │ │
211
+ └───────┬──────┘ │
212
+ │ │
213
+ │ │
214
+ Yes │
215
+ │ │
216
+ ▼ ▼
217
+ ┌──────────────┐ ┌───────────────┐
218
+ │ │ │ │
219
+ │ Log Error │◄─┐ │ Process Data │
220
+ │ │ │ │ │
221
+ └───────┬──────┘ │ └───────┬───────┘
222
+ │ │ │
223
+ │ │ │
224
+ │ └──────────┤
225
+ │ No
226
+ ▼ ▼
227
+ ┌──────────────┐ ┌───────┴───────┐
228
+ │ │ │ Success? │
229
+ │ Show Message │ │ │
230
+ │ │ │ │
231
+ └───────┬──────┘ └───────┬───────┘
232
+ │ │
233
+ │ │
234
+ │ Yes
235
+ │ │
236
+ ▼ ▼
237
+ ┌──────────────┐ ┌───────────────┐
238
+ │ │ │ │
239
+ │ Return Null │ │ Return Result │
240
+ │ │ │ │
241
+ └──────────────┘ └───────────────┘
242
+
243
+ ## Gantt Chart (not supported by beautiful-mermaid)
244
+
245
+ gantt
246
+ title Project Development
247
+ dateFormat YYYY-MM-DD
248
+ section Section
249
+ Task 1 :a1, 2024-01-01, 30d
250
+ Task 2 :after a1 , 20d
251
+ section Another
252
+ Task 3 :2024-01-12 , 12d
253
+ Task 4 : 24d
254
+
255
+ ## Regular Text
256
+
257
+ This is regular text between mermaid diagrams.
258
+
259
+ * Point 1
260
+ * Point 2
261
+ * Point 3
262
+
263
+ `Inline code` is also supported.
264
+
265
+ **Bold** and *italic* text work fine.
266
+
267
+ ```
268
+
269
+ ### Stdin input
270
+
271
+ ```
272
+ $ echo '# Hello\n\n```mermaid\nflowchart LR\n A --> B\n```' | memd
273
+ # Hello
274
+
275
+ ┌───┐ ┌───┐
276
+ │ │ │ │
277
+ │ A ├────►│ B │
278
+ │ │ │ │
279
+ └───┘ └───┘
280
+ ```
281
+
282
+ ## Uninstall
283
+
284
+ ```bash
285
+ npm remove -g memd-cli
286
+ ```
287
+
288
+ ## Debug
289
+
290
+ ```bash
291
+ # tag
292
+ npm install -g git+https://github.com/ktrysmt/memd.git#v1.0.4
293
+ # branch
294
+ npm install -g git+https://github.com/ktrysmt/memd.git#master
295
+ npm install -g git+https://github.com/ktrysmt/memd.git#feature
296
+ # hash
297
+ npm install -g git+https://github.com/ktrysmt/memd.git#a52a596
298
+ ```
299
+
300
+ ## Author
301
+
302
+ [ktrysmt](https://github.com/ktrysmt)
package/main.js ADDED
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env node
2
+ // @ts-nocheck
3
+ import { marked } from 'marked';
4
+ import { markedTerminal } from 'marked-terminal';
5
+ import { renderMermaidAscii } from 'beautiful-mermaid';
6
+ import { highlight, supportsLanguage } from 'cli-highlight';
7
+ import { program } from 'commander';
8
+ import { spawn } from 'child_process';
9
+ import * as fs from 'fs';
10
+ import * as path from 'path';
11
+ import { fileURLToPath } from 'url';
12
+
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = path.dirname(__filename);
15
+ const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'));
16
+
17
+ // Initialize marked configuration (will be configured in main function with color options)
18
+
19
+ function readMarkdownFile(filePath) {
20
+ const absolutePath = path.resolve(filePath);
21
+ const currentDir = process.cwd();
22
+ const currentDirResolved = path.resolve(currentDir);
23
+ const relativePath = path.relative(currentDirResolved, absolutePath);
24
+
25
+ if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
26
+ throw new Error('Invalid path: access outside current directory is not allowed');
27
+ }
28
+
29
+ if (!fs.existsSync(absolutePath)) {
30
+ throw new Error('File not found: ' + absolutePath);
31
+ }
32
+
33
+ return fs.readFileSync(absolutePath, 'utf-8');
34
+ }
35
+
36
+ function convertMermaidToAscii(markdown, options = {}) {
37
+ const mermaidRegex = /```mermaid\s+([\s\S]+?)```/g;
38
+
39
+ return markdown.replace(mermaidRegex, function (_, code) {
40
+ try {
41
+ // Pass width option to beautiful-mermaid if provided
42
+ const mermaidOptions = {};
43
+ if (options.width) {
44
+ mermaidOptions.maxWidth = options.width;
45
+ }
46
+ const asciiArt = renderMermaidAscii(code.trim(), mermaidOptions);
47
+ return '```text\n' + asciiArt + '\n```';
48
+ } catch (error) {
49
+ // Warn user about conversion failure (helps with debugging)
50
+ console.warn(`Warning: Mermaid diagram conversion failed: ${error.message}`);
51
+ // Return as text block if conversion fails (not mermaid, to avoid highlight errors)
52
+ return '```text\n' + code.trim() + '\n```';
53
+ }
54
+ });
55
+ }
56
+
57
+ function renderToString(markdown, options = {}) {
58
+ const processedMarkdown = convertMermaidToAscii(markdown, options);
59
+ let result = marked.parse(processedMarkdown);
60
+
61
+ // Strip ANSI color codes if --no-color is specified
62
+ if (options.color === false) {
63
+ // Remove ANSI escape codes (color, style, etc.)
64
+ result = result.replace(/\x1b\[[0-9;]*m/g, '');
65
+ }
66
+
67
+ return result;
68
+ }
69
+
70
+ function readStdin() {
71
+ return new Promise((resolve, reject) => {
72
+ let data = '';
73
+ process.stdin.on('data', chunk => {
74
+ data += chunk;
75
+ });
76
+ process.stdin.on('end', () => {
77
+ resolve(data);
78
+ });
79
+ process.stdin.on('error', reject);
80
+ });
81
+ }
82
+
83
+ function shouldUsePager(text, options) {
84
+ // Check TTY first - most important (prevents pager on pipes/redirects)
85
+ if (!process.stdout.isTTY) return false;
86
+
87
+ // User explicitly disabled pager (--no-pager sets options.pager to false)
88
+ if (options.pager === false) return false;
89
+
90
+ // NO_PAGER environment variable
91
+ if (process.env.NO_PAGER) return false;
92
+
93
+ // Check if output exceeds 90% of terminal height
94
+ const lines = text.split('\n').length;
95
+ const terminalRows = process.stdout.rows ?? 24;
96
+ return lines > terminalRows * 0.9;
97
+ }
98
+
99
+ function spawnPager(text, options) {
100
+ // Respect $PAGER environment variable (like glow, bat, mdcat)
101
+ const pagerCmd = process.env.PAGER || 'less';
102
+ const pagerArgs = pagerCmd === 'less' ? ['-R'] : [];
103
+
104
+ const pager = spawn(pagerCmd, pagerArgs, {
105
+ stdio: ['pipe', 'inherit', 'inherit']
106
+ });
107
+
108
+ pager.on('error', (err) => {
109
+ // Fallback if pager is not found
110
+ if (err.code === 'ENOENT') {
111
+ process.stdout.write(text);
112
+ } else {
113
+ console.error(`Pager error: ${err.message}`);
114
+ process.exit(1);
115
+ }
116
+ });
117
+
118
+ pager.stdin.write(text);
119
+ pager.stdin.end();
120
+
121
+ pager.on('close', code => {
122
+ process.exit(code ?? 0);
123
+ });
124
+ }
125
+
126
+ async function main() {
127
+ program
128
+ .name('memd')
129
+ .version(packageJson.version)
130
+ .description('Render markdown with mermaid diagrams to terminal output')
131
+ .argument('[files...]', 'markdown file(s) to render')
132
+ .option('--no-pager', 'disable pager (less)')
133
+ .option('--no-color', 'disable colored output')
134
+ .option('--no-highlight', 'disable syntax highlighting')
135
+ .option('--width <number>', 'terminal width override', Number, process.stdout.columns ?? 80)
136
+ .action(async (files, options) => {
137
+ // Check if color should be disabled (--no-color or NO_COLOR env var)
138
+ const useColor = options.color !== false && !process.env.NO_COLOR;
139
+
140
+ // Configure syntax highlighting options (passed to cli-highlight)
141
+ const shouldHighlight = options.highlight !== false && useColor;
142
+
143
+ // Configure marked with terminal renderer
144
+ const highlightOptions = shouldHighlight ? { ignoreIllegals: true } : undefined;
145
+
146
+ marked.use(markedTerminal({
147
+ reflowText: true,
148
+ width: options.width,
149
+ }, highlightOptions));
150
+
151
+ // Override link renderer to avoid OSC 8 escape sequences (fixes tmux display issues)
152
+ marked.use({
153
+ renderer: {
154
+ link(token) {
155
+ // URLとテキストを両方表示する場合
156
+ return token.text + (token.text !== token.href ? ` (${token.href})` : '');
157
+ }
158
+ }
159
+ });
160
+
161
+ // If highlighting is disabled, override the code renderer to bypass cli-highlight
162
+ if (!shouldHighlight) {
163
+ marked.use({
164
+ renderer: {
165
+ code(token) {
166
+ // Extract code text from token
167
+ const codeText = typeof token === 'string' ? token : (token.text || token);
168
+ // Return plain code without highlighting
169
+ // Note: We still need to format it as marked-terminal would
170
+ const lines = String(codeText).split('\n');
171
+ const indented = lines.map(line => ' ' + line).join('\n');
172
+ return indented + '\n';
173
+ }
174
+ }
175
+ });
176
+ }
177
+
178
+ const parts = [];
179
+
180
+ if (files.length === 0) {
181
+ // Read from stdin
182
+ if (process.stdin.isTTY) {
183
+ program.help();
184
+ }
185
+
186
+ const stdinData = await readStdin();
187
+ if (stdinData.trim()) {
188
+ parts.push(renderToString(stdinData, options));
189
+ } else {
190
+ program.help();
191
+ }
192
+ } else {
193
+ // Read from files
194
+ let exitCode = 0;
195
+ for (const filePath of files) {
196
+ try {
197
+ const markdown = readMarkdownFile(filePath);
198
+ parts.push(renderToString(markdown, options));
199
+ } catch (error) {
200
+ const errorMessage = error instanceof Error ? error.message : String(error);
201
+ console.error(`Error reading file ${filePath}: ${errorMessage}`);
202
+ exitCode = 1;
203
+ }
204
+ }
205
+
206
+ if (exitCode !== 0) {
207
+ process.exit(exitCode);
208
+ }
209
+ }
210
+
211
+ // Combine all output
212
+ const fullText = parts.join('\n\n') + '\n';
213
+
214
+ // Use pager if needed
215
+ if (shouldUsePager(fullText, options)) {
216
+ spawnPager(fullText, options);
217
+ } else {
218
+ process.stdout.write(fullText);
219
+ }
220
+ });
221
+
222
+ program.parse();
223
+ }
224
+
225
+ main();
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "memd-cli",
3
+ "version": "1.0.4",
4
+ "type": "module",
5
+ "main": "main.js",
6
+ "bin": {
7
+ "memd": "main.js"
8
+ },
9
+ "dependencies": {
10
+ "beautiful-mermaid": "^0.1.3",
11
+ "cli-highlight": "^2.1.11",
12
+ "commander": "^14.0.3",
13
+ "marked": "^15.0.12",
14
+ "marked-terminal": "^7.3.0"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/ktrysmt/memd.git"
19
+ },
20
+ "license": "MIT"
21
+ }
package/test/poc_md.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { marked } from 'marked';
2
+ import { markedTerminal } from 'marked-terminal';
3
+
4
+ marked.use(markedTerminal());
5
+
6
+ const result = marked.parse('# Hello \n This is **markdown** printed in the `terminal`');
7
+ console.log(result);
8
+
@@ -0,0 +1,17 @@
1
+ import { renderMermaid, renderMermaidAscii } from 'beautiful-mermaid';
2
+
3
+ const mermaidCode = `
4
+ flowchart TD
5
+ A[Start] --> B{Decision?}
6
+ B -->|Yes| C[Action]
7
+ B -->|No| D[End]
8
+ C --> D
9
+ `;
10
+
11
+ // const asciiArt = await renderMermaid(mermaidCode, {
12
+ // bg: "#27272A",
13
+ // fg: "#FFFFFF",
14
+ // });
15
+ const asciiArt = await renderMermaidAscii(mermaidCode, {});
16
+
17
+ console.log(asciiArt);
@@ -0,0 +1,53 @@
1
+ # Syntax Highlighting Test
2
+
3
+ ## JavaScript Code
4
+
5
+ ```javascript
6
+ function hello(name) {
7
+ const greeting = `Hello, ${name}!`;
8
+ console.log(greeting);
9
+ return greeting;
10
+ }
11
+
12
+ // Call the function
13
+ hello('World');
14
+ ```
15
+
16
+ ## Python Code
17
+
18
+ ```python
19
+ def fibonacci(n):
20
+ if n <= 1:
21
+ return n
22
+ return fibonacci(n-1) + fibonacci(n-2)
23
+
24
+ # Generate fibonacci sequence
25
+ for i in range(10):
26
+ print(fibonacci(i))
27
+ ```
28
+
29
+ ## Bash Script
30
+
31
+ ```bash
32
+ #!/bin/bash
33
+ echo "Hello from bash"
34
+ for i in {1..5}; do
35
+ echo "Count: $i"
36
+ done
37
+ ```
38
+
39
+ ## TypeScript
40
+
41
+ ```typescript
42
+ interface User {
43
+ name: string;
44
+ age: number;
45
+ }
46
+
47
+ const user: User = {
48
+ name: 'Alice',
49
+ age: 30
50
+ };
51
+
52
+ console.log(user);
53
+ ```
package/test/test1.md ADDED
@@ -0,0 +1,10 @@
1
+ # Hello
2
+
3
+ This is **markdown** with mermaid:
4
+
5
+ ```mermaid
6
+ flowchart LR
7
+ A --> B
8
+ ```
9
+
10
+ More text.
package/test/test2.md ADDED
@@ -0,0 +1,13 @@
1
+ # Hello
2
+
3
+ This is **markdown** printed in the `terminal`.
4
+
5
+ ```mermaid
6
+ flowchart TD
7
+ A[Start] --> B{Decision?}
8
+ B -->|Yes| C[Action]
9
+ B -->|No| D[End]
10
+ C --> D
11
+ ```
12
+
13
+ More text after the diagram.
package/test/test3.md ADDED
@@ -0,0 +1,114 @@
1
+ # Complex Mermaid Diagrams Test
2
+
3
+ ## flowchart LR Test
4
+
5
+ ```mermaid
6
+ flowchart LR
7
+ A[Starting Point] --> B{Decision}
8
+ B -->|Yes| C[Action 1]
9
+ B -->|No| D[Action 2]
10
+ C --> E[End]
11
+ D --> E
12
+ ```
13
+
14
+ ```mermaid
15
+ flowchart LR
16
+ DB[(Database)] --> Auth[Authentication]
17
+ Auth --> API[API Server]
18
+ API --> Cache[(Redis)]
19
+ API --> DB
20
+ Cache --> API
21
+ ```
22
+
23
+ ## Sequence Diagram
24
+
25
+ ```mermaid
26
+ sequenceDiagram
27
+ participant Client
28
+ participant Server
29
+ participant Database
30
+ participant Cache
31
+
32
+ Client->>Server: HTTP GET /api/data
33
+ activate Server
34
+ Server->>Cache: HGET user:123
35
+ Cache-->>Server: data (hit)
36
+ Server->>Client: 200 OK
37
+ deactivate Server
38
+ ```
39
+
40
+ ## Class Diagram
41
+
42
+ ```mermaid
43
+ classDiagram
44
+ class Animal {
45
+ +String name
46
+ +eat()
47
+ +sleep()
48
+ }
49
+
50
+ class Bird {
51
+ +fly()
52
+ +layEggs()
53
+ }
54
+
55
+ class Fish {
56
+ +swim()
57
+ +gills()
58
+ }
59
+
60
+ Animal <|-- Bird
61
+ Animal <|-- Fish
62
+ ```
63
+
64
+ ## State Diagram
65
+
66
+ ```mermaid
67
+ stateDiagram-v2
68
+ [*] --> Still
69
+ Still --> Moving
70
+ Moving --> Still
71
+ Moving --> Crash
72
+ Crash --> [*]
73
+ ```
74
+
75
+ ## Error Handling Example
76
+
77
+ ```mermaid
78
+ flowchart TD
79
+ A[Start] --> B{Check Error?}
80
+ B -->|Yes| C[Log Error]
81
+ C --> D[Show Message]
82
+ D --> E[Return Null]
83
+ B -->|No| F[Process Data]
84
+ F --> G{Success?}
85
+ G -->|Yes| H[Return Result]
86
+ G -->|No| C
87
+ ```
88
+
89
+ ## Gantt Chart (not supported by beautiful-mermaid)
90
+
91
+ ```mermaid
92
+ gantt
93
+ title Project Development
94
+ dateFormat YYYY-MM-DD
95
+ section Section
96
+ Task 1 :a1, 2024-01-01, 30d
97
+ Task 2 :after a1 , 20d
98
+ section Another
99
+ Task 3 :2024-01-12 , 12d
100
+ Task 4 : 24d
101
+ ```
102
+
103
+ ## Regular Text
104
+
105
+ This is regular text between mermaid diagrams.
106
+
107
+ - Point 1
108
+ - Point 2
109
+ - Point 3
110
+
111
+ `Inline code` is also supported.
112
+
113
+ **Bold** and *italic* text work fine.
114
+