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.
@@ -0,0 +1,303 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 命令层。
5
+ *
6
+ * 一套命令同时服务于 TUI 的 `:` 命令模式和直接执行(如 `mayx search xxx`)。
7
+ * 命令返回的都是「怎么画」,而不是画好的字符串 —— 这样窗口大小变了能重新排版。
8
+ */
9
+
10
+ const data = require('./data');
11
+ const fmt = require('./format');
12
+ const mdRenderer = require('./markdown');
13
+ const { C, runs, push, wrapRuns, strWidth } = require('./canvas');
14
+ const { openInBrowser } = require('./open');
15
+
16
+ const PAGE_SIZE = 20;
17
+
18
+ /* ============================ 帮助 ============================ */
19
+
20
+ const KEYS = [
21
+ ['↑ ↓ / j k', '移动选择 · 滚动正文'],
22
+ ['PgUp PgDn', '翻页'],
23
+ ['g / G', '回到顶部 / 跳到底部'],
24
+ ['Enter', '阅读全文(右窗格加载完整 Markdown)'],
25
+ ['Tab', '在文章列表和正文之间切换焦点'],
26
+ ['/', '搜索(边打边过滤)'],
27
+ [':', '命令模式'],
28
+ ['?', '这份帮助'],
29
+ ['r', '随机一篇'],
30
+ ['o', '在浏览器里打开当前文章'],
31
+ ['c', '查看评论(Gitalk / GitHub Issues)'],
32
+ ['y', '复制当前文章链接'],
33
+ ['Esc', '返回 / 关闭弹窗 / 清空搜索'],
34
+ ['q', '退出'],
35
+ ['鼠标', '滚轮滚动,点击选中'],
36
+ ];
37
+
38
+ const COMMANDS = [
39
+ ['list [页码]', '分页列出文章'],
40
+ ['get <序号|URL|标题>', '查看文章元信息'],
41
+ ['read <序号|URL|标题>', '在主界面打开文章'],
42
+ ['search <关键词>', '搜索标题、标签、正文'],
43
+ ['grep <模式> [--regex]', '全文检索,显示上下文'],
44
+ ['random', '随机打开一篇'],
45
+ ['open <序号>', '用系统浏览器打开'],
46
+ ['comments <序号>', '查看评论'],
47
+ ['about', '站点与作者信息'],
48
+ ['refresh', '强制刷新文章索引'],
49
+ ['clear', '清空搜索过滤'],
50
+ ['help', '帮助'],
51
+ ['q', '退出'],
52
+ ];
53
+
54
+ function buildHelp(width) {
55
+ const out = [];
56
+ const colW = Math.min(22, Math.max(12, Math.floor(width * 0.28)));
57
+
58
+ const section = (title) => {
59
+ out.push([]);
60
+ out.push([...runs('▍' + title, C.h3)]);
61
+ };
62
+
63
+ // 两列:左边快捷键/命令,右边说明;说明过长时折行并缩进对齐
64
+ const row = (k, v) => {
65
+ const kw = strWidth(k);
66
+ const line = [];
67
+ push(line, ' ', '');
68
+ push(line, k, C.code);
69
+ if (kw < colW) push(line, ' '.repeat(Math.max(1, colW - kw)), '');
70
+ push(line, v, C.dim);
71
+ const wrapped = wrapRuns(line, width);
72
+ for (const l of wrapped) out.push(l);
73
+ };
74
+
75
+ section('快捷键');
76
+ for (const [k, v] of KEYS) row(k, v);
77
+
78
+ section('命令(按 : 进入)');
79
+ for (const [k, v] of COMMANDS) row(k, v);
80
+
81
+ out.push([]);
82
+ out.push([...runs('提示:', C.dim), ...runs('列表里按 Enter 载入正文,Tab 把焦点切到右窗格后就能滚动了。', C.dim)]);
83
+
84
+ return out;
85
+ }
86
+
87
+ /* ============================ 命令实现 ============================ */
88
+
89
+ function parseArgs(text) {
90
+ const parts = [];
91
+ let cur = '';
92
+ let quote = null;
93
+ for (const ch of text) {
94
+ if (quote) {
95
+ if (ch === quote) quote = null;
96
+ else cur += ch;
97
+ } else if (ch === '"' || ch === "'") {
98
+ quote = ch;
99
+ } else if (/\s/.test(ch)) {
100
+ if (cur) {
101
+ parts.push(cur);
102
+ cur = '';
103
+ }
104
+ } else {
105
+ cur += ch;
106
+ }
107
+ }
108
+ if (cur) parts.push(cur);
109
+ return parts;
110
+ }
111
+
112
+ function overlay(title, build, hint) {
113
+ return { kind: 'overlay', title, build, hint };
114
+ }
115
+
116
+ /**
117
+ * 执行一条命令。
118
+ * @param {string} line
119
+ * @param {{posts: Array, filtered?: Array}} ctx
120
+ */
121
+ async function run(line, ctx) {
122
+ const args = parseArgs(String(line || '').trim());
123
+ if (!args.length) return null;
124
+
125
+ const cmd = args[0].toLowerCase();
126
+ const rest = args.slice(1);
127
+ const posts = ctx.posts || [];
128
+
129
+ switch (cmd) {
130
+ case 'help':
131
+ case '?':
132
+ return overlay('帮助', buildHelp, 'Esc 关闭');
133
+
134
+ case 'q':
135
+ case 'quit':
136
+ case 'exit':
137
+ return { kind: 'quit' };
138
+
139
+ case 'list': {
140
+ const page = Math.max(1, parseInt(rest[0], 10) || 1);
141
+ const totalPages = Math.max(1, Math.ceil(posts.length / PAGE_SIZE));
142
+ const start = (page - 1) * PAGE_SIZE;
143
+ const slice = posts.slice(start, start + PAGE_SIZE);
144
+ return overlay(
145
+ `文章列表 第 ${page}/${totalPages} 页`,
146
+ (w) => {
147
+ if (!slice.length) return fmt.table([], w);
148
+ const rows = fmt.table(slice, w, { showTags: w > 60 });
149
+ rows.push([]);
150
+ rows.push(fmt.hint(`共 ${posts.length} 篇 · 每页 ${PAGE_SIZE} 篇 · :list ${page + 1} 下一页`));
151
+ return rows;
152
+ },
153
+ '↑↓ 滚动 · Esc 关闭'
154
+ );
155
+ }
156
+
157
+ case 'get': {
158
+ const post = data.resolvePost(posts, rest[0]);
159
+ if (!post) return overlay('未找到', (w) => [fmt.errorLine(`没有匹配的文章:${rest[0] || '(空)'}`)]);
160
+ return overlay(
161
+ `#${post.num}`,
162
+ (w) => {
163
+ const rows = fmt.metaBlock(post, w);
164
+ rows.push(...mdRenderer.render(post.excerpt, w));
165
+ rows.push([]);
166
+ rows.push([...runs('链接 ', C.dim), ...runs(post.url, C.link)]);
167
+ rows.push([...runs('源码 ', C.dim), ...runs(post.rawUrl, C.dim)]);
168
+ return rows;
169
+ },
170
+ 'Esc 关闭'
171
+ );
172
+ }
173
+
174
+ case 'read': {
175
+ const post = data.resolvePost(posts, rest[0]);
176
+ if (!post) return overlay('未找到', (w) => [fmt.errorLine(`没有匹配的文章:${rest[0] || '(空)'}`)]);
177
+ return { kind: 'view', post };
178
+ }
179
+
180
+ case 'search': {
181
+ const kw = rest.join(' ');
182
+ if (!kw) return overlay('搜索', (w) => [fmt.errorLine('用法::search <关键词>')]);
183
+ const hits = data.searchPosts(posts, kw, { limit: 100 });
184
+ return overlay(
185
+ `搜索「${kw}」· ${hits.length} 条`,
186
+ (w) => {
187
+ if (!hits.length) return [fmt.hint('没有匹配的文章。')];
188
+ const rows = fmt.table(hits, w, { showTags: w > 60 });
189
+ rows.push([]);
190
+ rows.push(fmt.hint('回车后可用 :read <序号> 打开'));
191
+ return rows;
192
+ },
193
+ 'Esc 关闭'
194
+ );
195
+ }
196
+
197
+ case 'grep': {
198
+ const isRegex = rest.includes('--regex') || rest.includes('-r');
199
+ const pattern = rest.filter((a) => a !== '--regex' && a !== '-r').join(' ');
200
+ if (!pattern) return overlay('grep', (w) => [fmt.errorLine('用法::grep <模式> [--regex]')]);
201
+ let result;
202
+ try {
203
+ result = data.grepPosts(posts, pattern, { useRegex: isRegex, limit: 30 });
204
+ } catch (e) {
205
+ return overlay('grep', (w) => [fmt.errorLine(e.message)]);
206
+ }
207
+ return overlay(
208
+ `grep /${result.source}/ · ${result.hits.length} 篇命中`,
209
+ (w) => {
210
+ if (!result.hits.length) return [fmt.hint('无命中。')];
211
+ const rows = [];
212
+ for (const h of result.hits) {
213
+ rows.push([...runs(`#${h.post.num} `, C.date), ...runs(h.post.title, C.strong)]);
214
+ for (const m of h.matches) {
215
+ for (const l of wrapRuns([...runs(m, C.dim)], w - 4)) {
216
+ rows.push([...runs(' '), ...l]);
217
+ }
218
+ }
219
+ rows.push([]);
220
+ }
221
+ if (result.timedOut) rows.push(fmt.hint('(已达检索时间上限,结果可能不完整)'));
222
+ return rows;
223
+ },
224
+ 'Esc 关闭'
225
+ );
226
+ }
227
+
228
+ case 'random': {
229
+ if (!posts.length) return overlay('随机', (w) => [fmt.errorLine('文章列表还是空的')]);
230
+ const post = posts[Math.floor(Math.random() * posts.length)];
231
+ return { kind: 'view', post };
232
+ }
233
+
234
+ case 'open': {
235
+ const post = data.resolvePost(posts, rest[0]) || (ctx.current ? ctx.current : null);
236
+ if (!post) return overlay('打开', (w) => [fmt.errorLine('没有匹配的文章')]);
237
+ const ok = openInBrowser(post.webUrl);
238
+ return overlay(
239
+ '打开',
240
+ () => [
241
+ ok
242
+ ? [...runs('✅ 已在浏览器中打开:', C.ok), ...runs(post.title, C.strong)]
243
+ : fmt.errorLine('无法调用系统浏览器'),
244
+ [],
245
+ [...runs(post.webUrl, C.link)],
246
+ ],
247
+ 'Esc 关闭'
248
+ );
249
+ }
250
+
251
+ case 'comments': {
252
+ const post = data.resolvePost(posts, rest[0]) || (ctx.current ? ctx.current : null);
253
+ if (!post) return overlay('评论', (w) => [fmt.errorLine('没有匹配的文章')]);
254
+ let result;
255
+ try {
256
+ result = await data.readComments(post);
257
+ } catch (e) {
258
+ return overlay('评论', () => [fmt.errorLine(e.message)]);
259
+ }
260
+ return overlay(
261
+ `评论 · ${post.title}`,
262
+ (w) => fmt.commentsBlock(result, w),
263
+ 'Esc 关闭'
264
+ );
265
+ }
266
+
267
+ case 'about': {
268
+ let about;
269
+ try {
270
+ about = await data.readAbout();
271
+ } catch (e) {
272
+ return overlay('关于', () => [fmt.errorLine(e.message)]);
273
+ }
274
+ return overlay('关于本站', (w) => {
275
+ const rows = fmt.aboutBlock(about.text, w);
276
+ rows.push([]);
277
+ rows.push([...runs('站点 ', C.dim), ...runs(data.SITE, C.link)]);
278
+ return rows;
279
+ }, 'Esc 关闭');
280
+ }
281
+
282
+ case 'refresh':
283
+ return { kind: 'refresh' };
284
+
285
+ case 'clear':
286
+ return { kind: 'clear' };
287
+
288
+ case 'theme':
289
+ return overlay('主题', () => [fmt.hint('配色跟随终端,不提供切换。')]);
290
+
291
+ default:
292
+ return overlay(
293
+ '未知命令',
294
+ () => [
295
+ fmt.errorLine(`未知命令:${cmd}`),
296
+ [],
297
+ fmt.hint('输入 :help 查看全部命令'),
298
+ ]
299
+ );
300
+ }
301
+ }
302
+
303
+ module.exports = { run, buildHelp, KEYS, COMMANDS };
package/src/data.js ADDED
@@ -0,0 +1,408 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 数据层。
5
+ *
6
+ * 和网页版 blog-console.js 的区别:
7
+ * - 网页版靠宿主提供的 getSearchJSON()(localStorage 缓存),这里自己拉 search.json 并落盘缓存;
8
+ * - 网页版读评论要带 Gitalk 的 clientID/clientSecret 做 Basic 认证(密钥泄露在前端)。
9
+ * 这里读的是公开仓库,匿名请求 GitHub API 就够,**不需要也不应该**在客户端塞任何密钥。
10
+ */
11
+
12
+ const os = require('os');
13
+ const path = require('path');
14
+ const fs = require('fs');
15
+ const fsp = fs.promises;
16
+
17
+ const SITE = 'https://mabbs.github.io';
18
+ const SITE_HOST = 'mabbs.github.io';
19
+ const SITE_NAME = "Mayx's Blog";
20
+ const REPO = 'Mabbs/mabbs.github.io';
21
+ const BRANCH = 'master';
22
+ const RAW_BASE = `https://raw.githubusercontent.com/${REPO}/refs/heads/${BRANCH}/_posts/`;
23
+
24
+ const CACHE_ROOT = path.join(
25
+ process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'),
26
+ 'mayx'
27
+ );
28
+ const INDEX_PATH = path.join(CACHE_ROOT, 'search.json');
29
+ const POST_DIR = path.join(CACHE_ROOT, 'posts');
30
+
31
+ // 默认 6 小时内不再重复拉索引(1.5MB,实测 1~3 秒)
32
+ const INDEX_TTL = Number(process.env.MAYX_CACHE_TTL || 6 * 60 * 60 * 1000);
33
+ const HTTP_TIMEOUT = Number(process.env.MAYX_TIMEOUT || 20000);
34
+
35
+ /* ============================ 小工具 ============================ */
36
+
37
+ const HTML_ENTITIES = {
38
+ '&amp;': '&',
39
+ '&lt;': '<',
40
+ '&gt;': '>',
41
+ '&quot;': '"',
42
+ '&#39;': "'",
43
+ '&#x27;': "'",
44
+ '&nbsp;': ' ',
45
+ };
46
+
47
+ function unescapeHTML(str) {
48
+ if (!str || str.indexOf('&') === -1) return str || '';
49
+ return str.replace(/&(?:amp|lt|gt|quot|#39|#x27|nbsp);/g, (m) => HTML_ENTITIES[m] || m);
50
+ }
51
+
52
+ async function fetchText(url, init) {
53
+ const res = await fetch(url, {
54
+ ...init,
55
+ headers: {
56
+ 'user-agent': `mayx-cli (+${SITE})`,
57
+ accept: '*/*',
58
+ ...((init && init.headers) || {}),
59
+ },
60
+ signal: AbortSignal.timeout(HTTP_TIMEOUT),
61
+ });
62
+ if (!res.ok) {
63
+ const err = new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());
64
+ err.status = res.status;
65
+ throw err;
66
+ }
67
+ return res.text();
68
+ }
69
+
70
+ /* ============================ 索引 ============================ */
71
+
72
+ let _cache = null; // { posts, at, stale }
73
+
74
+ function normalize(item, i) {
75
+ const url = item.url || '';
76
+ const date = item.date || '';
77
+ const lastSeg = url.split('/').pop() || '';
78
+ let slug = lastSeg.replace(/\.html$/, '');
79
+ try {
80
+ slug = decodeURIComponent(slug);
81
+ } catch (_) {
82
+ /* 保持原样 */
83
+ }
84
+ const title = unescapeHTML(item.title || '');
85
+ const category = item.category || '';
86
+ const tags = String(item.tags || '')
87
+ .split(',')
88
+ .map((t) => t.trim())
89
+ .filter(Boolean);
90
+ const content = item.content || '';
91
+ const preview = 160;
92
+
93
+ return {
94
+ num: i + 1,
95
+ title,
96
+ url,
97
+ date,
98
+ category,
99
+ tags,
100
+ content,
101
+ excerpt: content.slice(0, preview) + (content.length > preview ? '……' : ''),
102
+ slug,
103
+ // 正文从源码仓库取,这一点和网页版 Blog.show() 完全一致
104
+ rawUrl: `${RAW_BASE}${date.replace(/\//g, '-')}-${slug}.md`,
105
+ webUrl: SITE + url,
106
+ // 预先小写化,搜索时不用每次重算 1.5MB
107
+ hay: `${title} ${category} ${tags.join(' ')} ${content}`.toLowerCase(),
108
+ };
109
+ }
110
+
111
+ async function readIndexCache() {
112
+ try {
113
+ const st = await fsp.stat(INDEX_PATH);
114
+ const raw = await fsp.readFile(INDEX_PATH, 'utf8');
115
+ const data = JSON.parse(raw);
116
+ if (!Array.isArray(data)) return null;
117
+ return { raw: data, at: st.mtimeMs };
118
+ } catch (_) {
119
+ return null;
120
+ }
121
+ }
122
+
123
+ async function writeIndexCache(raw) {
124
+ try {
125
+ await fsp.mkdir(CACHE_ROOT, { recursive: true });
126
+ await fsp.writeFile(INDEX_PATH, JSON.stringify(raw));
127
+ } catch (_) {
128
+ /* 缓存失败不影响主流程 */
129
+ }
130
+ }
131
+
132
+ /**
133
+ * 载入文章索引。
134
+ * @param {{refresh?: boolean}} opts refresh=true 时忽略缓存
135
+ * @returns {Promise<{posts: Array, at: number, stale: boolean, fromCache: boolean}>}
136
+ */
137
+ async function loadIndex(opts) {
138
+ const { refresh = false } = opts || {};
139
+ if (_cache && !refresh) return _cache;
140
+
141
+ const cached = await readIndexCache();
142
+
143
+ if (cached && !refresh && Date.now() - cached.at < INDEX_TTL) {
144
+ _cache = {
145
+ posts: cached.raw.map(normalize),
146
+ at: cached.at,
147
+ stale: false,
148
+ fromCache: true,
149
+ };
150
+ return _cache;
151
+ }
152
+
153
+ try {
154
+ const text = await fetchText(`${SITE}/search.json`, {
155
+ headers: { accept: 'application/json' },
156
+ });
157
+ const raw = JSON.parse(text);
158
+ if (!Array.isArray(raw)) throw new Error('search.json 格式异常');
159
+ await writeIndexCache(raw);
160
+ _cache = { posts: raw.map(normalize), at: Date.now(), stale: false, fromCache: false };
161
+ return _cache;
162
+ } catch (e) {
163
+ // 网络挂了但有旧缓存:降级使用,并标记 stale 让 UI 提示
164
+ if (cached) {
165
+ _cache = {
166
+ posts: cached.raw.map(normalize),
167
+ at: cached.at,
168
+ stale: true,
169
+ fromCache: true,
170
+ };
171
+ return _cache;
172
+ }
173
+ throw new Error(`无法获取文章索引(${e.message})`);
174
+ }
175
+ }
176
+
177
+ /* ============================ 正文 ============================ */
178
+
179
+ function safeFileName(s) {
180
+ return String(s).replace(/[^\w.\u4e00-\u9fff-]+/g, '_').slice(0, 120);
181
+ }
182
+
183
+ /**
184
+ * 读取文章原始 Markdown,优先用本地缓存。
185
+ * @param {object} post
186
+ * @param {{refresh?: boolean}} [opts]
187
+ */
188
+ async function readPost(post, opts) {
189
+ const { refresh = false } = opts || {};
190
+ if (!post) throw new Error('未指定文章');
191
+ const file = path.join(POST_DIR, `${post.date.replace(/\//g, '-')}-${safeFileName(post.slug)}.md`);
192
+
193
+ if (!refresh) {
194
+ try {
195
+ const cached = await fsp.readFile(file, 'utf8');
196
+ if (cached && cached.trim()) return cached;
197
+ } catch (_) {
198
+ /* 未命中,走网络 */
199
+ }
200
+ }
201
+
202
+ let md;
203
+ try {
204
+ md = await fetchText(post.rawUrl);
205
+ } catch (e) {
206
+ // 网络失败但有旧缓存就用旧的
207
+ try {
208
+ const cached = await fsp.readFile(file, 'utf8');
209
+ if (cached && cached.trim()) return cached;
210
+ } catch (_) {
211
+ /* ignore */
212
+ }
213
+ throw new Error(`无法获取正文(${e.message})`);
214
+ }
215
+
216
+ try {
217
+ await fsp.mkdir(POST_DIR, { recursive: true });
218
+ await fsp.writeFile(file, md);
219
+ } catch (_) {
220
+ /* ignore */
221
+ }
222
+ return md;
223
+ }
224
+
225
+ /* ============================ 评论 ============================ */
226
+
227
+ /**
228
+ * 读取 Gitalk 评论(存在 GitHub Issues 里,label 为 "Gitalk,<文章路径>")。
229
+ * 匿名访问,60 次/小时限流。
230
+ */
231
+ async function readComments(post) {
232
+ if (!post) throw new Error('未指定文章');
233
+ const label = post.url.replace(/\.html$/, '');
234
+ const listUrl =
235
+ `https://api.github.com/repos/${REPO}/issues` +
236
+ `?labels=${encodeURIComponent('Gitalk,' + label)}&per_page=1&state=all`;
237
+
238
+ let issues;
239
+ try {
240
+ issues = JSON.parse(
241
+ await fetchText(listUrl, { headers: { accept: 'application/vnd.github+json' } })
242
+ );
243
+ } catch (e) {
244
+ if (e.status === 403) throw new Error('GitHub API 限流了(匿名 60 次/小时),稍后再试');
245
+ throw new Error(`无法获取评论(${e.message})`);
246
+ }
247
+
248
+ if (!Array.isArray(issues) || issues.length === 0) {
249
+ return { issueUrl: null, comments: [], reason: 'NO_ISSUE' };
250
+ }
251
+
252
+ const issue = issues[0];
253
+ let comments = [];
254
+ if (issue.comments > 0) {
255
+ try {
256
+ comments = JSON.parse(
257
+ await fetchText(`${issue.comments_url}?per_page=100`, {
258
+ headers: { accept: 'application/vnd.github+json' },
259
+ })
260
+ );
261
+ } catch (e) {
262
+ if (e.status === 403) throw new Error('GitHub API 限流了,稍后再试');
263
+ throw new Error(`无法获取评论内容(${e.message})`);
264
+ }
265
+ }
266
+
267
+ return {
268
+ issueUrl: issue.html_url,
269
+ reason: comments.length ? null : 'NO_COMMENT',
270
+ comments: (comments || []).map((c) => ({
271
+ author: (c.user && c.user.login) || 'unknown',
272
+ avatar: (c.user && c.user.avatar_url) || '',
273
+ date: c.created_at || '',
274
+ body: c.body || '',
275
+ })),
276
+ };
277
+ }
278
+
279
+ /* ============================ 站点信息 ============================ */
280
+
281
+ async function readAbout() {
282
+ try {
283
+ const text = await fetchText(`${SITE}/humans.txt`);
284
+ return { url: `${SITE}/humans.txt`, text };
285
+ } catch (e) {
286
+ throw new Error(`无法获取 humans.txt(${e.message})`);
287
+ }
288
+ }
289
+
290
+ /* ============================ 检索 ============================ */
291
+
292
+ /** 子序列模糊匹配 */
293
+ function fuzzyMatch(needle, hay) {
294
+ let i = 0;
295
+ for (let j = 0; j < hay.length && i < needle.length; j++) {
296
+ if (hay[j] === needle[i]) i++;
297
+ }
298
+ return i === needle.length;
299
+ }
300
+
301
+ /**
302
+ * 关键词搜索:标题 / 分类 / 标签 / 正文,大小写不敏感。
303
+ */
304
+ function searchPosts(posts, keyword, opts) {
305
+ const { limit = 20, fuzzy = false } = opts || {};
306
+ const kw = String(keyword || '').trim().toLowerCase();
307
+ if (!kw) return [];
308
+ const out = [];
309
+ for (const p of posts) {
310
+ const hit = fuzzy ? fuzzyMatch(kw, p.hay) : p.hay.indexOf(kw) !== -1;
311
+ if (hit) {
312
+ out.push(p);
313
+ if (out.length >= limit) break;
314
+ }
315
+ }
316
+ return out;
317
+ }
318
+
319
+ /**
320
+ * 正则/纯文本全文检索,返回带上下文的命中片段。
321
+ */
322
+ function grepPosts(posts, pattern, opts) {
323
+ const { useRegex = false, flags = 'gi', context = 60, limit = 20 } = opts || {};
324
+ let src = String(pattern || '');
325
+ if (!useRegex) src = src.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
326
+ let re;
327
+ try {
328
+ re = new RegExp(src, flags.indexOf('g') === -1 ? flags + 'g' : flags);
329
+ } catch (e) {
330
+ const err = new Error(`无效的正则表达式:${e.message}`);
331
+ err.code = 'BAD_PATTERN';
332
+ throw err;
333
+ }
334
+
335
+ const hits = [];
336
+ const t0 = Date.now();
337
+ let timedOut = false;
338
+
339
+ for (const p of posts) {
340
+ if (hits.length >= limit) break;
341
+ if (Date.now() - t0 > 3000) {
342
+ timedOut = true;
343
+ break;
344
+ }
345
+ const matches = [];
346
+ re.lastIndex = 0;
347
+ let m;
348
+ while ((m = re.exec(p.content)) !== null && matches.length < 3) {
349
+ const s = Math.max(0, m.index - context);
350
+ const e = Math.min(p.content.length, m.index + m[0].length + context);
351
+ matches.push((s > 0 ? '…' : '') + p.content.slice(s, e) + (e < p.content.length ? '…' : ''));
352
+ if (m[0] === '') re.lastIndex++;
353
+ }
354
+ if (matches.length) hits.push({ post: p, matches });
355
+ }
356
+
357
+ return { hits, timedOut, source: re.source };
358
+ }
359
+
360
+ /**
361
+ * 按 序号 / URL / 标题 定位一篇文章。
362
+ */
363
+ function resolvePost(posts, id) {
364
+ if (!posts || !posts.length) return null;
365
+ if (id === undefined || id === null || id === '') return null;
366
+
367
+ const s = String(id).trim();
368
+ const n = Number(s);
369
+ if (Number.isInteger(n) && n >= 1 && n <= posts.length) return posts[n - 1];
370
+
371
+ const byPath = posts.find((p) => p.url === s || p.webUrl === s || p.slug === s);
372
+ if (byPath) return byPath;
373
+
374
+ const low = s.toLowerCase();
375
+ return posts.find((p) => p.title.toLowerCase().includes(low)) || null;
376
+ }
377
+
378
+ /* ============================ 时间格式化 ============================ */
379
+
380
+ function humanAge(ts) {
381
+ const d = Date.now() - ts;
382
+ const m = Math.floor(d / 60000);
383
+ if (m < 1) return '刚刚';
384
+ if (m < 60) return `${m} 分钟前`;
385
+ const h = Math.floor(m / 60);
386
+ if (h < 24) return `${h} 小时前`;
387
+ const days = Math.floor(h / 24);
388
+ if (days < 30) return `${days} 天前`;
389
+ return new Date(ts).toLocaleDateString('zh-CN');
390
+ }
391
+
392
+ module.exports = {
393
+ SITE,
394
+ SITE_HOST,
395
+ SITE_NAME,
396
+ REPO,
397
+ CACHE_ROOT,
398
+ INDEX_TTL,
399
+ loadIndex,
400
+ readPost,
401
+ readComments,
402
+ readAbout,
403
+ searchPosts,
404
+ grepPosts,
405
+ resolvePost,
406
+ humanAge,
407
+ unescapeHTML,
408
+ };