mayx-cli 0.0.0-stage → 1.0.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/src/cli.js ADDED
@@ -0,0 +1,422 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+
6
+ const { C, toAnsi, runs, push, strWidth } = require('./canvas');
7
+ const data = require('./data');
8
+ const fmt = require('./format');
9
+ const mdRenderer = require('./markdown');
10
+ const { openInBrowser } = require('./open');
11
+ const pkg = require('../package.json');
12
+
13
+ const PAGE_SIZE = 20;
14
+
15
+ /* ============================ 输出 ============================ */
16
+
17
+ function outWidth() {
18
+ const w = process.stdout.columns || 80;
19
+ return Math.max(40, Math.min(w, 120));
20
+ }
21
+
22
+ function print(rows) {
23
+ process.stdout.write(rows.map(toAnsi).join('\n') + '\n');
24
+ }
25
+
26
+ function printJson(obj) {
27
+ process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
28
+ }
29
+
30
+ /** 慢请求时给个提示,不打断管道输出 */
31
+ async function withHint(text, fn) {
32
+ const timer = setTimeout(() => {
33
+ if (process.stderr.isTTY) process.stderr.write(`${text}\n`);
34
+ }, 350);
35
+ try {
36
+ return await fn();
37
+ } finally {
38
+ clearTimeout(timer);
39
+ }
40
+ }
41
+
42
+ /* ============================ 帮助 ============================ */
43
+
44
+ function helpText() {
45
+ const rows = [];
46
+ const title = [
47
+ ...runs('mayx', C.title),
48
+ ...runs(' · ' + data.SITE_NAME + ' 的终端版', C.dim),
49
+ ];
50
+ rows.push(title);
51
+ rows.push([]);
52
+
53
+ const sec = (t) => {
54
+ rows.push([...runs('▍' + t, C.h3)]);
55
+ };
56
+ const row = (k, v) => {
57
+ const line = [];
58
+ push(line, ' ', '');
59
+ push(line, k, C.code);
60
+ if (strWidth(k) < 22) push(line, ' '.repeat(22 - strWidth(k)), '');
61
+ push(line, v, C.dim);
62
+ rows.push(line);
63
+ };
64
+
65
+ sec('用法');
66
+ row('mayx', '打开全屏界面(GUI 式操作)');
67
+ row('mayx list [页码]', '分页列出文章');
68
+ row('mayx get <id>', '查看文章元信息');
69
+ row('mayx read <id>', '阅读完整正文');
70
+ row('mayx search <关键词>', '搜索标题、标签、正文');
71
+ row('mayx grep <模式>', '全文检索并显示上下文');
72
+ row('mayx random [--open]', '随机一篇');
73
+ row('mayx comments <id>', '查看 Gitalk 评论');
74
+ row('mayx open <id>', '用浏览器打开');
75
+ row('mayx about', '站点与作者信息');
76
+ row('mayx refresh', '强制刷新文章索引');
77
+
78
+ rows.push([]);
79
+ sec('id 的写法');
80
+ row('序号', '如 12,1 表示最新一篇');
81
+ row('URL', '如 /2026/11/01/compress.html');
82
+ row('标题', '模糊匹配,取第一条');
83
+
84
+ rows.push([]);
85
+ sec('选项');
86
+ row('--json', '以 JSON 输出,方便脚本处理');
87
+ row('--refresh', '忽略本地缓存重新拉取');
88
+ row('--no-color', '关闭颜色');
89
+ row('-h, --help', '显示帮助');
90
+ row('-v, --version', '显示版本');
91
+
92
+ rows.push([]);
93
+ rows.push([...runs(' 不带子命令时参数会被猜:', C.dim)]);
94
+ rows.push([...runs(' mayx 12 → read 12', C.dim)]);
95
+ rows.push([...runs(' mayx jekyll → search jekyll', C.dim)]);
96
+
97
+ rows.push([]);
98
+ rows.push([...runs(` v${pkg.version} · ${data.SITE}`, C.dim)]);
99
+ return rows;
100
+ }
101
+
102
+ /* ============================ 各命令 ============================ */
103
+
104
+ async function ensureIndex(refresh) {
105
+ return withHint(
106
+ COLOR_DIM('正在获取文章索引…'),
107
+ () => data.loadIndex({ refresh })
108
+ );
109
+ }
110
+
111
+ function COLOR_DIM(s) {
112
+ return C.dim + s + C.reset;
113
+ }
114
+
115
+ async function cmdList(rest, flags) {
116
+ const page = Math.max(1, parseInt(rest[0], 10) || 1);
117
+ const res = await ensureIndex(flags.refresh);
118
+ const posts = res.posts;
119
+ const totalPages = Math.max(1, Math.ceil(posts.length / PAGE_SIZE));
120
+ const start = (page - 1) * PAGE_SIZE;
121
+ const slice = posts.slice(start, start + PAGE_SIZE);
122
+
123
+ if (flags.json) {
124
+ printJson({ page, totalPages, total: posts.length, posts: slice.map(brief) });
125
+ return 0;
126
+ }
127
+ if (!slice.length) {
128
+ print([[runs(`第 ${page} 页没有文章(共 ${totalPages} 页)`, C.warn)]]);
129
+ return 1;
130
+ }
131
+
132
+ const W = outWidth();
133
+ const rows = fmt.table(slice, W, { showTags: W > 70 });
134
+ rows.push([]);
135
+ rows.push([
136
+ ...runs(`第 ${page}/${totalPages} 页 · 共 ${posts.length} 篇`, C.dim),
137
+ ...runs(page < totalPages ? ` · mayx list ${page + 1} 看下一页` : '', C.dim),
138
+ ]);
139
+ if (res.stale) rows.push([...runs('(网络不可用,使用的是本地缓存)', C.warn)]);
140
+ print(rows);
141
+ return 0;
142
+ }
143
+
144
+ function brief(p) {
145
+ return {
146
+ num: p.num,
147
+ title: p.title,
148
+ date: p.date,
149
+ url: p.url,
150
+ webUrl: p.webUrl,
151
+ category: p.category,
152
+ tags: p.tags,
153
+ excerpt: p.excerpt,
154
+ chars: p.content.length,
155
+ };
156
+ }
157
+
158
+ async function cmdGet(rest, flags) {
159
+ const res = await ensureIndex(flags.refresh);
160
+ const post = data.resolvePost(res.posts, rest.join(' '));
161
+ if (!post) {
162
+ process.stderr.write(`没有找到文章:${rest.join(' ') || '(空)'}\n`);
163
+ return 1;
164
+ }
165
+ if (flags.json) {
166
+ printJson(brief(post));
167
+ return 0;
168
+ }
169
+ const W = outWidth();
170
+ const rows = fmt.metaBlock(post, W);
171
+ rows.push(...mdRenderer.render(post.excerpt, W));
172
+ rows.push([]);
173
+ rows.push([...runs('链接 ', C.dim), ...runs(post.webUrl, C.link)]);
174
+ rows.push([...runs('字数 ', C.dim), ...runs(String(post.content.length), C.dim)]);
175
+ print(rows);
176
+ return 0;
177
+ }
178
+
179
+ async function cmdRead(rest, flags) {
180
+ const res = await ensureIndex(flags.refresh);
181
+ const post = data.resolvePost(res.posts, rest.join(' '));
182
+ if (!post) {
183
+ process.stderr.write(`没有找到文章:${rest.join(' ') || '(空)'}\n`);
184
+ return 1;
185
+ }
186
+ const md = await withHint(COLOR_DIM('正在获取正文…'), () => data.readPost(post, { refresh: flags.refresh }));
187
+ if (flags.json) {
188
+ printJson({ ...brief(post), markdown: md });
189
+ return 0;
190
+ }
191
+ const W = outWidth();
192
+ const rows = fmt.metaBlock(post, W);
193
+ rows.push([]);
194
+ rows.push(...mdRenderer.render(md, W));
195
+ rows.push([]);
196
+ rows.push([...runs('─'.repeat(W), C.border)]);
197
+ rows.push([...runs('原文 ', C.dim), ...runs(post.webUrl, C.link)]);
198
+ print(rows);
199
+ return 0;
200
+ }
201
+
202
+ async function cmdSearch(rest, flags) {
203
+ const kw = rest.join(' ').trim();
204
+ if (!kw) {
205
+ process.stderr.write('用法:mayx search <关键词>\n');
206
+ return 1;
207
+ }
208
+ const res = await ensureIndex(flags.refresh);
209
+ const hits = data.searchPosts(res.posts, kw, { limit: 100 });
210
+
211
+ if (flags.json) {
212
+ printJson({ keyword: kw, count: hits.length, posts: hits.map(brief) });
213
+ return hits.length ? 0 : 3;
214
+ }
215
+ if (!hits.length) {
216
+ print([[runs(`没有匹配「${kw}」的文章`, C.warn)]]);
217
+ return 3;
218
+ }
219
+ const W = outWidth();
220
+ const rows = fmt.table(hits, W, { showTags: W > 70 });
221
+ rows.push([]);
222
+ rows.push([...runs(`「${kw}」命中 ${hits.length} 篇`, C.dim)]);
223
+ print(rows);
224
+ return 0;
225
+ }
226
+
227
+ async function cmdGrep(rest, flags) {
228
+ const isRegex = rest.includes('--regex') || rest.includes('-r');
229
+ const pattern = rest.filter((a) => a !== '--regex' && a !== '-r').join(' ').trim();
230
+ if (!pattern) {
231
+ process.stderr.write('用法:mayx grep <模式> [--regex]\n');
232
+ return 1;
233
+ }
234
+ const res = await ensureIndex(flags.refresh);
235
+ let result;
236
+ try {
237
+ result = data.grepPosts(res.posts, pattern, { useRegex: isRegex, limit: 50 });
238
+ } catch (e) {
239
+ process.stderr.write(e.message + '\n');
240
+ return 1;
241
+ }
242
+
243
+ if (flags.json) {
244
+ printJson({
245
+ pattern,
246
+ count: result.hits.length,
247
+ hits: result.hits.map((h) => ({ ...brief(h.post), matches: h.matches })),
248
+ });
249
+ return result.hits.length ? 0 : 3;
250
+ }
251
+ if (!result.hits.length) {
252
+ print([[runs('无命中。', C.warn)]]);
253
+ return 3;
254
+ }
255
+ const W = outWidth();
256
+ const rows = [];
257
+ rows.push([...runs(`grep /${result.source}/`, C.dim), ...runs(` ${result.hits.length} 篇命中`, C.dim)]);
258
+ rows.push([]);
259
+ for (const h of result.hits) {
260
+ rows.push([...runs(`#${h.post.num} `, C.date), ...runs(h.post.title, C.strong)]);
261
+ for (const m of h.matches) {
262
+ rows.push(...mdRenderer.render(m, W - 4).map((l) => [...runs(' '), ...l]));
263
+ }
264
+ rows.push([]);
265
+ }
266
+ if (result.timedOut) rows.push([...runs('(已达检索时间上限,结果可能不完整)', C.warn)]);
267
+ print(rows);
268
+ return 0;
269
+ }
270
+
271
+ async function cmdRandom(rest, flags) {
272
+ const res = await ensureIndex(flags.refresh);
273
+ if (!res.posts.length) {
274
+ process.stderr.write('索引为空\n');
275
+ return 1;
276
+ }
277
+ const post = res.posts[Math.floor(Math.random() * res.posts.length)];
278
+ if (flags.json) {
279
+ printJson(brief(post));
280
+ } else {
281
+ print([
282
+ [...runs(`🎲 #${post.num} `, C.ok), ...runs(post.title, C.title)],
283
+ [...runs(post.webUrl, C.link)],
284
+ ]);
285
+ }
286
+ if (rest.includes('--open')) openInBrowser(post.webUrl);
287
+ return 0;
288
+ }
289
+
290
+ async function cmdComments(rest, flags) {
291
+ const res = await ensureIndex(flags.refresh);
292
+ const post = data.resolvePost(res.posts, rest.join(' '));
293
+ if (!post) {
294
+ process.stderr.write(`没有找到文章:${rest.join(' ')}\n`);
295
+ return 1;
296
+ }
297
+ const result = await withHint(COLOR_DIM('正在获取评论…'), () => data.readComments(post));
298
+ if (flags.json) {
299
+ printJson({ ...brief(post), issueUrl: result.issueUrl, comments: result.comments });
300
+ return 0;
301
+ }
302
+ const W = outWidth();
303
+ print(fmt.commentsBlock(result, W));
304
+ return 0;
305
+ }
306
+
307
+ async function cmdAbout(flags) {
308
+ const about = await withHint(COLOR_DIM('正在获取站点信息…'), () => data.readAbout());
309
+ if (flags.json) {
310
+ printJson({ url: about.url, text: about.text });
311
+ return 0;
312
+ }
313
+ const W = outWidth();
314
+ const rows = fmt.aboutBlock(about.text, W);
315
+ rows.push([]);
316
+ rows.push([...runs('站点 ', C.dim), ...runs(data.SITE, C.link)]);
317
+ print(rows);
318
+ return 0;
319
+ }
320
+
321
+ async function cmdOpen(rest, flags) {
322
+ const res = await ensureIndex(flags.refresh);
323
+ const post = data.resolvePost(res.posts, rest.join(' '));
324
+ if (!post) {
325
+ process.stderr.write(`没有找到文章:${rest.join(' ')}\n`);
326
+ return 1;
327
+ }
328
+ const ok = openInBrowser(post.webUrl);
329
+ if (!ok) process.stderr.write('无法调用系统浏览器,直接给你链接:\n');
330
+ print([[runs(post.title, C.title)], [...runs(post.webUrl, C.link)]]);
331
+ return 0;
332
+ }
333
+
334
+ async function cmdRefresh() {
335
+ const res = await withHint(COLOR_DIM('正在刷新索引…'), () => data.loadIndex({ refresh: true }));
336
+ print([
337
+ [...runs('✓ ', C.ok), ...runs(`索引已更新,共 ${res.posts.length} 篇`, C.dim)],
338
+ ]);
339
+ return 0;
340
+ }
341
+
342
+ /* ============================ 入口 ============================ */
343
+
344
+ const COMMANDS = new Set([
345
+ 'list', 'ls', 'get', 'read', 'show', 'search', 'grep', 'random', 'comments', 'comment',
346
+ 'about', 'open', 'refresh', 'help', '-h', '--help', 'version', '-v', '--version',
347
+ ]);
348
+
349
+ async function main(argv) {
350
+ const args = argv.slice();
351
+ const flags = {
352
+ json: false,
353
+ refresh: false,
354
+ };
355
+
356
+ // 抽掉全局 flag
357
+ const rest = [];
358
+ for (const a of args) {
359
+ if (a === '--json') flags.json = true;
360
+ else if (a === '--refresh' || a === '-r') flags.refresh = true;
361
+ else if (a === '--no-color') {
362
+ /* 已在 ansi.js 处理 */
363
+ } else rest.push(a);
364
+ }
365
+
366
+ let cmd = rest[0];
367
+ let params = rest.slice(1);
368
+
369
+ // 无子命令 → TUI
370
+ if (!cmd) {
371
+ const tty = process.stdout.isTTY && process.stdin.isTTY;
372
+ if (!tty) {
373
+ print(helpText());
374
+ return 0;
375
+ }
376
+ return require('./tui').run({}).then(() => 0);
377
+ }
378
+
379
+ switch (cmd) {
380
+ case '-h':
381
+ case '--help':
382
+ case 'help':
383
+ print(helpText());
384
+ return 0;
385
+ case '-v':
386
+ case '--version':
387
+ case 'version':
388
+ process.stdout.write(pkg.version + '\n');
389
+ return 0;
390
+ case 'list':
391
+ case 'ls':
392
+ return cmdList(params, flags);
393
+ case 'get':
394
+ return cmdGet(params, flags);
395
+ case 'read':
396
+ case 'show':
397
+ return cmdRead(params, flags);
398
+ case 'search':
399
+ return cmdSearch(params, flags);
400
+ case 'grep':
401
+ return cmdGrep(params, flags);
402
+ case 'random':
403
+ return cmdRandom(params, flags);
404
+ case 'comments':
405
+ case 'comment':
406
+ return cmdComments(params, flags);
407
+ case 'about':
408
+ return cmdAbout(flags);
409
+ case 'open':
410
+ return cmdOpen(params, flags);
411
+ case 'refresh':
412
+ return cmdRefresh();
413
+ default:
414
+ break;
415
+ }
416
+
417
+ // 猜意图:数字当序号读文章,其它当关键词搜索
418
+ if (/^\d+$/.test(cmd)) return cmdRead([cmd, ...params], flags);
419
+ return cmdSearch([cmd, ...params], flags);
420
+ }
421
+
422
+ module.exports = { main };