plugin-autosummary 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 科技酱
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 CHANGED
@@ -1,3 +1,213 @@
1
- # Temporary Holding Version
1
+ # plugin-autosummary
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ VuePress 2 插件:在构建期自动生成文章摘要、结构化导读与 SEO description。默认使用纯本地抽取策略,不依赖任何外部服务;可选 OpenAI 兼容接口,所有网络调用都发生在 Node 端构建期,`apiKey` 不会进入客户端产物。
4
+
5
+ 同时发布为 [`autosummary`](https://www.npmjs.com/package/autosummary) 与 [`plugin-autosummary`](https://www.npmjs.com/package/plugin-autosummary),两者 API 一致。
6
+
7
+ ## 特性
8
+
9
+ - `extendsPage` 构建期处理,零客户端运行时开销。
10
+ - 手动分隔符 `<!-- more -->` 优先,适合人工精修摘要。
11
+ - 本地结构化抽取:标题层级、各节首句、列表项、代码块语言分布按权重组合。
12
+ - 可选 AI 摘要:接口配置不完整或请求失败时自动回退本地策略。
13
+ - 写入 `page.data.summary`,客户端通过 `usePageData()` 直接读取。
14
+ - 自动同步 `frontmatter.description`,并注入 `description` / `og:description`。
15
+ - 已有 `description` 默认跳过,`overwrite: true` 可显式覆盖。
16
+ - 构建结束输出中文统计,并对跳过页面给出中文原因与文件路径。
17
+ - 符合 VuePress 2 的 ESM + TypeScript + peerDependencies 规范。
18
+
19
+ ## 目录结构
20
+
21
+ ```text
22
+ vuepress-plugin-autosummary/
23
+ ├─ package.json
24
+ ├─ tsconfig.json
25
+ ├─ tsup.config.ts
26
+ ├─ .gitignore
27
+ ├─ LICENSE
28
+ ├─ README.md
29
+ ├─ src/
30
+ │ ├─ index.ts # 插件入口:extendsPage / onGenerated / SEO head 写入
31
+ │ ├─ extract.ts # 本地抽取与手动分隔符
32
+ │ ├─ ai.ts # Node 端模型接口调用与失败回退
33
+ │ └─ types.ts # 配置、统计与客户端读取类型声明
34
+ ├─ scripts/
35
+ │ └─ publish.mjs # 双包名发布脚本(失败自动恢复 package.json)
36
+ ├─ tests/
37
+ │ └─ run.mjs # 回归测试
38
+ ├─ example/
39
+ │ └─ .vuepress/
40
+ │ └─ config.ts # VuePress 配置示例
41
+ └─ dist/ # tsup 构建产物
42
+ ├─ index.js
43
+ ├─ index.js.map
44
+ └─ index.d.ts
45
+ ```
46
+
47
+ ## 安装
48
+
49
+ ```bash
50
+ npm install plugin-autosummary
51
+ # 或使用兼容别名
52
+ npm install autosummary
53
+ ```
54
+
55
+ 要求 Node.js 18+,VuePress 2(`>=2.0.0-rc.0 <3`)。
56
+
57
+ ## 使用
58
+
59
+ 在 `.vuepress/config.ts` 中:
60
+
61
+ ```ts
62
+ import { defineUserConfig } from 'vuepress'
63
+ import autoSummaryPlugin from 'plugin-autosummary'
64
+
65
+ export default defineUserConfig({
66
+ lang: 'zh-CN',
67
+ title: '我的站点',
68
+ description: '站点级默认描述',
69
+ plugins: [
70
+ autoSummaryPlugin({
71
+ length: 120,
72
+ separator: '<!-- more -->',
73
+ overwrite: false,
74
+ insertToHead: true,
75
+ strategy: 'local',
76
+ filter: (page) => !page.path.startsWith('/404'),
77
+ }),
78
+ ],
79
+ })
80
+ ```
81
+
82
+ 使用 `autosummary` 别名时,只需替换 import:
83
+
84
+ ```ts
85
+ import autoSummaryPlugin from 'autosummary'
86
+ ```
87
+
88
+ ### 手动摘要
89
+
90
+ 文章中放置分隔符后,标记之前的内容会优先成为摘要:
91
+
92
+ ```md
93
+ 这是人工撰写的摘要。
94
+
95
+ <!-- more -->
96
+
97
+ 这里是正文其余部分。
98
+ ```
99
+
100
+ ### 客户端读取
101
+
102
+ ```vue
103
+ <script setup lang="ts">
104
+ import { computed } from 'vue'
105
+ import { usePageData } from 'vuepress/client'
106
+ import type { PageDataWithSummary } from 'plugin-autosummary'
107
+
108
+ const page = usePageData()
109
+ const summary = computed(() => (page.value as PageDataWithSummary).summary)
110
+ </script>
111
+
112
+ <template>
113
+ <p v-if="summary">{{ summary }}</p>
114
+ </template>
115
+ ```
116
+
117
+ ### AI 策略
118
+
119
+ ```ts
120
+ autoSummaryPlugin({
121
+ strategy: 'ai',
122
+ api: 'https://api.example.com/v1/chat/completions',
123
+ apiKey: process.env.OPENAI_API_KEY,
124
+ model: 'gpt-4o-mini',
125
+ prompt: '请用中文写一段约 {length} 字的导读摘要,只输出摘要正文。',
126
+ })
127
+ ```
128
+
129
+ 接口需兼容 OpenAI Chat Completions 的请求格式。响应支持 `choices[0].message.content`、`choices[0].text`、`output.text`、`summary` 等常见字段。缺少 `api` / `apiKey` / `model` 任一项,或请求失败、超时、返回空文本时,都会回退本地策略,不会影响站点构建。
130
+
131
+ ## 配置项
132
+
133
+ | 配置 | 类型 | 默认值 | 说明 |
134
+ | --- | --- | --- | --- |
135
+ | `length` | `number` | `120` | 摘要目标字数 |
136
+ | `separator` | `string` | `<!-- more -->` | 手动摘要分隔符,传空字符串关闭 |
137
+ | `overwrite` | `boolean` | `false` | 是否覆盖已有 `frontmatter.description` |
138
+ | `filter` | `(page: Page) => boolean` | - | 返回 `false` 的页面不处理 |
139
+ | `insertToHead` | `boolean` | `true` | 是否写入 `description` / `og:description` |
140
+ | `strategy` | `'local' \| 'ai'` | `'local'` | 摘要策略;AI 不可用时自动回退 local |
141
+ | `minLength` | `number` | `40` | 正文低于该字数时跳过自动摘要 |
142
+ | `api` | `string` | - | OpenAI 兼容聊天接口地址 |
143
+ | `apiKey` | `string` | - | 接口密钥,仅 Node 端使用 |
144
+ | `model` | `string` | - | 模型名称 |
145
+ | `prompt` | `string` | 内置提示词 | 支持 `{length}` 占位符 |
146
+
147
+ ## 构建统计
148
+
149
+ 构建结束后终端会打印:
150
+
151
+ ```text
152
+ [AutoSummary] 构建期摘要统计
153
+ 共处理篇数:N
154
+ 使用手动摘要:N
155
+ 自动生成:N
156
+ 因内容过短跳过:N
157
+ ```
158
+
159
+ 跳过页面会输出中文原因、相对路径或路由路径,例如:
160
+
161
+ ```text
162
+ [AutoSummary] 跳过 guide/intro.md:正文仅 12 字,少于 40 字
163
+ ```
164
+
165
+ ## VuePress Marketplace
166
+
167
+ 所属分区:**站点管理 → SEO**。
168
+
169
+ 投稿时应编辑 `vuepress/marketplace` 仓库的 `config/plugins/manage.json`,将下面条目追加到 `"SEO"` 分组的 `items` 末尾:
170
+
171
+ ```json
172
+ {
173
+ "name": "plugin-autosummary",
174
+ "icon": "wrench",
175
+ "tag": "latest",
176
+ "desc": {
177
+ "/": "Generate summaries, structured reading guides and SEO descriptions at build time for VuePress 2.",
178
+ "/zh/": "在构建期为 VuePress 2 文章生成摘要、结构化导读与 SEO description,支持纯本地抽取与可选 AI 接口。"
179
+ },
180
+ "source": "techjiang/vuepress-plugin-autosummary",
181
+ "url": "github.com/techjiang/vuepress-plugin-autosummary"
182
+ }
183
+ ```
184
+
185
+ PR 正文应包含贡献指南要求的声明:作品是 VuePress 2 插件、开源且使用 MIT 协议、已有详细文档、兼容最新 VuePress 2 并将持续支持、放弃维护时会提交 PR 移除条目。
186
+
187
+ ## 开发
188
+
189
+ ```bash
190
+ npm install
191
+ npm run verify
192
+ ```
193
+
194
+ `npm run verify` 会依次执行类型检查、tsup 构建与回归测试。
195
+
196
+ ## 作者
197
+
198
+ 作者:科技酱
199
+
200
+ 作者描述:同一个世界,同一个互联网!
201
+
202
+ - 科技酱的技术文档:https://docs.asoe.cn
203
+ - GitHub:https://github.com/techjiang/
204
+ - 哔哩哔哩:https://space.bilibili.com/1768832152
205
+ - 邮箱:official@tech.asoe.cn
206
+ - 玲珑:https://forums.asoe.cn/
207
+ - QQ群:291974598
208
+ - QQ群②:474819022
209
+ - QQ群③:631167288
210
+
211
+ ## 许可证
212
+
213
+ [MIT](./LICENSE) © 科技酱
@@ -0,0 +1,48 @@
1
+ import { Page, PageData, Plugin } from 'vuepress/core';
2
+
3
+ /** 摘要生成策略。 */
4
+ type SummaryStrategy = 'local' | 'ai';
5
+ /** 摘要来源,仅用于内部统计。 */
6
+ type SummarySource = 'manual' | 'local' | 'ai';
7
+ /**
8
+ * 插件配置。
9
+ * apiKey 只会在 Node 端构建期使用,不会写入 page.data 或客户端产物。
10
+ */
11
+ interface AutoSummaryOptions {
12
+ /** 摘要目标字数,默认 120。 */
13
+ length?: number;
14
+ /** 正文低于该字数时跳过自动摘要,默认 40;手动摘要不受影响。 */
15
+ minLength?: number;
16
+ /** 手动摘要分隔符,默认 `<!-- more -->`;传空字符串可关闭。 */
17
+ separator?: string;
18
+ /** 页面已有 frontmatter.description 时是否覆盖,默认 false。 */
19
+ overwrite?: boolean;
20
+ /** 页面过滤函数,返回 false 的页面不处理。 */
21
+ filter?: (page: Page) => boolean;
22
+ /** 是否向页面 head 写入 description / og:description,默认 true。 */
23
+ insertToHead?: boolean;
24
+ /** 摘要策略,默认 local;配置为 ai 但接口参数不完整时自动回退 local。 */
25
+ strategy?: SummaryStrategy;
26
+ /** OpenAI 兼容的聊天接口地址。 */
27
+ api?: string;
28
+ /** 接口密钥,仅在 Node 端使用。 */
29
+ apiKey?: string;
30
+ /** 模型名称。 */
31
+ model?: string;
32
+ /** 自定义提示词,可用 `{length}` 占位符。 */
33
+ prompt?: string;
34
+ }
35
+ /** 客户端 usePageData() 读取 summary 时可用的类型。 */
36
+ type PageDataWithSummary = PageData & {
37
+ summary?: string;
38
+ };
39
+
40
+ /**
41
+ * AutoSummary 插件入口。
42
+ *
43
+ * 只返回 VuePress Node 端插件对象,不注册任何客户端配置,
44
+ * 因此 apiKey 不会出现在浏览器产物中。
45
+ */
46
+ declare const autoSummaryPlugin: (options?: AutoSummaryOptions) => Plugin;
47
+
48
+ export { type AutoSummaryOptions, type PageDataWithSummary, type SummarySource, type SummaryStrategy, autoSummaryPlugin, autoSummaryPlugin as default };
package/dist/index.js ADDED
@@ -0,0 +1,469 @@
1
+ // src/extract.ts
2
+ var MIN_SUMMARY_CONTENT_LENGTH = 40;
3
+ function normalizeText(text) {
4
+ return text.replace(/\s+/g, " ").trim();
5
+ }
6
+ function fitSummary(text, length) {
7
+ const normalized = normalizeText(text);
8
+ const max = Math.max(1, Math.floor(length));
9
+ const chars = Array.from(normalized);
10
+ if (chars.length <= max) return normalized;
11
+ if (max === 1) return "\u2026";
12
+ return `${chars.slice(0, max - 1).join("")}\u2026`;
13
+ }
14
+ function stripFrontmatter(content) {
15
+ const source = content.replace(/^\uFEFF/, "");
16
+ const match = source.match(/^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);
17
+ return match ? source.slice(match[0].length) : source;
18
+ }
19
+ function cleanInline(input) {
20
+ return input.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/`([^`]*)`/g, "$1").replace(/(\*\*|__)(.*?)\1/g, "$2").replace(/(\*|_)(.*?)\1/g, "$2").replace(/~~(.*?)~~/g, "$1").replace(/<[^>]*>/g, "").replace(/\\([\\`*_{}[\]()#+\-.!])/g, "$1").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;|&apos;/gi, "'").replace(/\s+/g, " ").trim();
21
+ }
22
+ function splitFirstSentence(text) {
23
+ const normalized = normalizeText(text);
24
+ if (!normalized) return "";
25
+ const match = normalized.match(/^.*?(?:[。!?!?;;]+|\.(?=\s|$))/u);
26
+ return (match?.[0] ?? normalized).trim();
27
+ }
28
+ function ensureTerminalPunctuation(text) {
29
+ if (!text) return text;
30
+ return /[。!?!?;;…]$/u.test(text) ? text : `${text}\u3002`;
31
+ }
32
+ function extractMarkdown(content) {
33
+ const source = stripFrontmatter(content);
34
+ const lines = source.split(/\r?\n/);
35
+ const bodyParts = [];
36
+ const sections = [];
37
+ const listItems = [];
38
+ const codeLanguageCounts = {};
39
+ let inFence = false;
40
+ let fenceChar = "";
41
+ let fenceLength = 0;
42
+ let currentSection = null;
43
+ let sectionBuffer = [];
44
+ for (const line of lines) {
45
+ const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
46
+ if (inFence) {
47
+ const closing = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
48
+ if (closing && closing[1][0] === fenceChar && closing[1].length >= fenceLength) {
49
+ inFence = false;
50
+ }
51
+ continue;
52
+ }
53
+ if (fenceMatch) {
54
+ inFence = true;
55
+ fenceChar = fenceMatch[1][0];
56
+ fenceLength = fenceMatch[1].length;
57
+ const language = (fenceMatch[2] ?? "").trim().split(/\s+/)[0]?.replace(/[^\w+#.-]/g, "").toLowerCase();
58
+ if (language) {
59
+ codeLanguageCounts[language] = (codeLanguageCounts[language] ?? 0) + 1;
60
+ }
61
+ continue;
62
+ }
63
+ const headingMatch = line.match(/^ {0,3}(#{1,6})\s+(.+?)\s*#*\s*$/);
64
+ if (headingMatch) {
65
+ const title2 = cleanInline(headingMatch[2].replace(/\s+#+\s*$/, ""));
66
+ currentSection = {
67
+ level: headingMatch[1].length,
68
+ title: title2,
69
+ firstSentence: ""
70
+ };
71
+ sections.push(currentSection);
72
+ sectionBuffer = [];
73
+ continue;
74
+ }
75
+ const listMatch = line.match(/^\s*(?:[-*+]|\d+[.)])\s+(.+)$/);
76
+ if (listMatch) {
77
+ const item = cleanInline(listMatch[1]);
78
+ if (item.length >= 2) listItems.push(item);
79
+ continue;
80
+ }
81
+ const cleaned = cleanInline(line);
82
+ if (!cleaned) continue;
83
+ bodyParts.push(cleaned);
84
+ if (currentSection && !currentSection.firstSentence) {
85
+ sectionBuffer.push(cleaned);
86
+ const joined = sectionBuffer.join(" ");
87
+ if (/[。!?!?;;]|\.(?=\s|$)/u.test(joined) || joined.length >= 160) {
88
+ currentSection.firstSentence = splitFirstSentence(joined);
89
+ sectionBuffer = [];
90
+ }
91
+ }
92
+ }
93
+ if (currentSection && !currentSection.firstSentence && sectionBuffer.length) {
94
+ currentSection.firstSentence = splitFirstSentence(sectionBuffer.join(" "));
95
+ }
96
+ const plainText = normalizeText(bodyParts.join(" "));
97
+ const title = sections.find((section) => section.level === 1)?.title ?? splitFirstSentence(plainText);
98
+ const codeLanguages = Object.entries(codeLanguageCounts).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([language]) => language);
99
+ return {
100
+ plainText,
101
+ title,
102
+ sections,
103
+ listItems,
104
+ codeLanguages,
105
+ codeLanguageCounts
106
+ };
107
+ }
108
+ function extractPlainText(content) {
109
+ return extractMarkdown(content).plainText;
110
+ }
111
+ function getManualSummary(content, separator) {
112
+ if (!separator) return null;
113
+ const source = stripFrontmatter(content);
114
+ const index = source.indexOf(separator);
115
+ if (index < 0) return null;
116
+ return normalizeText(cleanInline(source.slice(0, index)));
117
+ }
118
+ function isTextTooShort(text, minLength = MIN_SUMMARY_CONTENT_LENGTH) {
119
+ return normalizeText(text).length < Math.max(1, Math.floor(minLength));
120
+ }
121
+ function dedupeCandidates(candidates) {
122
+ const map = /* @__PURE__ */ new Map();
123
+ for (const candidate of candidates) {
124
+ const text = normalizeText(candidate.text);
125
+ if (text.length < 2) continue;
126
+ const previous = map.get(text);
127
+ if (!previous || previous.weight < candidate.weight) {
128
+ map.set(text, { ...candidate, text });
129
+ }
130
+ }
131
+ return [...map.values()];
132
+ }
133
+ function pickByWeight(candidates, budget, limit) {
134
+ const useful = dedupeCandidates(candidates);
135
+ if (!useful.length || budget <= 0) return [];
136
+ const sorted = [...useful].sort((a, b) => b.weight - a.weight);
137
+ const picked = [];
138
+ let used = 0;
139
+ for (const candidate of sorted) {
140
+ if (picked.length >= limit || used >= budget) break;
141
+ const text = candidate.text.replace(/[。!?!?;;,,]+$/u, "");
142
+ const length = Array.from(text).length;
143
+ if (length < 2) continue;
144
+ const remaining = budget - used;
145
+ let selected = text;
146
+ if (length > remaining) {
147
+ if (remaining < 12 || length < remaining + 6) continue;
148
+ selected = `${Array.from(text).slice(0, remaining - 1).join("")}\u2026`;
149
+ }
150
+ picked.push(selected);
151
+ used += Array.from(selected).length + 1;
152
+ }
153
+ return picked;
154
+ }
155
+ function extractLocalSummary(content, length = 120) {
156
+ const extracted = extractMarkdown(content);
157
+ const target = Math.max(1, Math.floor(length));
158
+ const intro = splitFirstSentence(extracted.plainText);
159
+ const introCandidates = intro ? [{ text: intro, weight: 5, kind: "sentence" }] : [];
160
+ const outlineCandidates = [];
161
+ for (const section of extracted.sections) {
162
+ if (section.title) {
163
+ const weight = section.level <= 2 ? 3.4 : Math.max(1.6, 3.4 - (section.level - 2) * 0.4);
164
+ outlineCandidates.push({ text: section.title, weight, kind: "section" });
165
+ }
166
+ if (section.firstSentence && section.firstSentence !== intro) {
167
+ outlineCandidates.push({
168
+ text: section.firstSentence,
169
+ weight: 4.2,
170
+ kind: "sentence"
171
+ });
172
+ }
173
+ }
174
+ for (const item of extracted.listItems.slice(0, 10)) {
175
+ if (item !== intro) {
176
+ outlineCandidates.push({ text: item, weight: 1.8, kind: "list" });
177
+ }
178
+ }
179
+ const evidenceCandidates = extracted.codeLanguages.slice(0, 4).map((language) => ({ text: language, weight: 1.2, kind: "code" }));
180
+ const introBudget = Math.max(20, Math.floor(target * 0.35));
181
+ const outlineBudget = Math.max(20, Math.floor(target * 0.5));
182
+ const evidenceBudget = Math.max(8, target - introBudget - outlineBudget);
183
+ const introText = pickByWeight(introCandidates, introBudget, 1)[0] ?? "";
184
+ const outline = pickByWeight(outlineCandidates, outlineBudget, 6);
185
+ const evidence = pickByWeight(evidenceCandidates, evidenceBudget, 3);
186
+ const parts = [];
187
+ if (extracted.title) parts.push(`\u672C\u6587\u56F4\u7ED5\u300A${extracted.title}\u300B`);
188
+ if (introText) parts.push(introText);
189
+ if (outline.length) parts.push(`\u91CD\u70B9\u5305\u62EC\uFF1A${outline.join("\uFF1B")}`);
190
+ if (evidence.length) parts.push(`\u6587\u4E2D\u7ED3\u5408 ${evidence.join("\u3001")} \u4EE3\u7801\u793A\u4F8B`);
191
+ const summary = ensureTerminalPunctuation(
192
+ parts.join("\uFF0C").replace(/,{2,}/g, "\uFF0C").replace(/;{2,}/g, "\uFF1B")
193
+ );
194
+ return fitSummary(summary, target);
195
+ }
196
+
197
+ // src/ai.ts
198
+ var DEFAULT_TIMEOUT_MS = 3e4;
199
+ var DEFAULT_MAX_INPUT_CHARS = 12e3;
200
+ var DEFAULT_PROMPT = `\u8BF7\u4E3A\u4EE5\u4E0B Markdown \u6587\u7AE0\u751F\u6210\u4E00\u6BB5\u4E2D\u6587\u5BFC\u8BFB\u6458\u8981\uFF0C\u7EA6 {length} \u5B57\u3002\u8981\u6C42\uFF1A\u53EA\u8F93\u51FA\u6458\u8981\u6B63\u6587\uFF1B\u6982\u62EC\u6587\u7AE0\u4E3B\u9898\u3001\u6838\u5FC3\u7ED3\u8BBA\u548C\u4E3B\u8981\u5185\u5BB9\uFF1B\u4E0D\u8981\u8F93\u51FA\u201C\u6458\u8981\uFF1A\u201D\u7B49\u524D\u7F00\uFF0C\u4E0D\u8981\u4F7F\u7528 Markdown \u6216 HTML\u3002`;
201
+ function isAiConfigured(options) {
202
+ return Boolean(options.api && options.apiKey && options.model);
203
+ }
204
+ function readText(value) {
205
+ if (typeof value === "string") return value.trim();
206
+ if (Array.isArray(value)) {
207
+ return value.map((item) => readText(item)).filter(Boolean).join("\n").trim();
208
+ }
209
+ if (value && typeof value === "object") {
210
+ const record = value;
211
+ for (const key of ["text", "content", "value", "message"]) {
212
+ const text = readText(record[key]);
213
+ if (text) return text;
214
+ }
215
+ }
216
+ return "";
217
+ }
218
+ function pickAiText(data) {
219
+ if (!data || typeof data !== "object") return "";
220
+ const record = data;
221
+ const choices = record.choices;
222
+ if (Array.isArray(choices) && choices.length > 0) {
223
+ const first = choices[0];
224
+ const text = readText(first);
225
+ if (text) return text;
226
+ }
227
+ for (const key of ["summary", "response", "output", "content", "text"]) {
228
+ const text = readText(record[key]);
229
+ if (text) return text;
230
+ }
231
+ return "";
232
+ }
233
+ function truncateInput(content) {
234
+ const chars = Array.from(content);
235
+ if (chars.length <= DEFAULT_MAX_INPUT_CHARS) return content;
236
+ return `${chars.slice(0, DEFAULT_MAX_INPUT_CHARS).join("")}
237
+
238
+ [\u6B63\u6587\u5DF2\u622A\u65AD]`;
239
+ }
240
+ function sanitizeError(message, options) {
241
+ let result = message;
242
+ if (options.apiKey) result = result.split(options.apiKey).join("***");
243
+ if (options.api) result = result.split(options.api).join("[API]");
244
+ return result.replace(/Bearer\s+[^\s"']+/gi, "Bearer ***").replace(/sk-[A-Za-z0-9_-]{8,}/g, "sk-***");
245
+ }
246
+ async function generateAiSummary(content, options) {
247
+ if (!isAiConfigured(options)) return null;
248
+ const prompt = (options.prompt ?? DEFAULT_PROMPT).replaceAll(
249
+ "{length}",
250
+ String(options.length)
251
+ );
252
+ const controller = new AbortController();
253
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
254
+ try {
255
+ const response = await fetch(options.api, {
256
+ method: "POST",
257
+ headers: {
258
+ "content-type": "application/json",
259
+ authorization: `Bearer ${options.apiKey}`
260
+ },
261
+ body: JSON.stringify({
262
+ model: options.model,
263
+ stream: false,
264
+ temperature: 0.2,
265
+ messages: [
266
+ { role: "system", content: prompt },
267
+ { role: "user", content: truncateInput(content) }
268
+ ]
269
+ }),
270
+ signal: controller.signal
271
+ });
272
+ if (!response.ok) {
273
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
274
+ }
275
+ const data = await response.json();
276
+ const summary = normalizeText(pickAiText(data));
277
+ return summary || null;
278
+ } catch (error) {
279
+ const rawMessage = error instanceof Error ? error.message : String(error);
280
+ console.warn(
281
+ `[AutoSummary] AI \u6458\u8981\u8C03\u7528\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u672C\u5730\u7B56\u7565\uFF1A${sanitizeError(rawMessage, options)}`
282
+ );
283
+ return null;
284
+ } finally {
285
+ clearTimeout(timer);
286
+ }
287
+ }
288
+
289
+ // src/index.ts
290
+ var DEFAULT_OPTIONS = {
291
+ length: 120,
292
+ minLength: 40,
293
+ separator: "<!-- more -->",
294
+ overwrite: false,
295
+ insertToHead: true,
296
+ strategy: "local"
297
+ };
298
+ function createStats() {
299
+ return {
300
+ total: 0,
301
+ written: 0,
302
+ manual: 0,
303
+ generated: 0,
304
+ tooShort: 0,
305
+ existingDescription: 0,
306
+ filtered: 0,
307
+ aiFallback: 0
308
+ };
309
+ }
310
+ function resolveOptions(options) {
311
+ if (options.strategy && options.strategy !== "local" && options.strategy !== "ai") {
312
+ console.warn(
313
+ `[AutoSummary] \u672A\u77E5 strategy\uFF1A${String(options.strategy)}\uFF0C\u5DF2\u56DE\u9000\u4E3A local\u3002`
314
+ );
315
+ }
316
+ const length = Number.isFinite(options.length) ? Math.max(1, Math.floor(options.length)) : DEFAULT_OPTIONS.length;
317
+ const minLength = Number.isFinite(options.minLength) ? Math.max(1, Math.floor(options.minLength)) : DEFAULT_OPTIONS.minLength;
318
+ const resolved = {
319
+ ...DEFAULT_OPTIONS,
320
+ ...options,
321
+ length,
322
+ minLength,
323
+ strategy: options.strategy === "ai" ? "ai" : "local"
324
+ };
325
+ if (resolved.strategy === "ai" && !isAiConfigured(resolved)) {
326
+ console.warn(
327
+ "[AutoSummary] ai \u7B56\u7565\u7F3A\u5C11 api / apiKey / model\uFF0C\u5DF2\u81EA\u52A8\u56DE\u9000 local \u7B56\u7565\u3002"
328
+ );
329
+ resolved.strategy = "local";
330
+ }
331
+ return resolved;
332
+ }
333
+ function pageLabel(page) {
334
+ return page.filePathRelative || page.filePath || page.path || "<\u672A\u77E5\u9875\u9762>";
335
+ }
336
+ function logSkip(page, reason) {
337
+ console.warn(`[AutoSummary] \u8DF3\u8FC7 ${pageLabel(page)}\uFF1A${reason}`);
338
+ }
339
+ function hasExistingDescription(page) {
340
+ const frontmatter = page.frontmatter;
341
+ const dataFrontmatter = page.data.frontmatter;
342
+ return [frontmatter.description, dataFrontmatter.description].some(
343
+ (value) => typeof value === "string" && value.trim().length > 0
344
+ );
345
+ }
346
+ function isTargetMeta(tag, attribute, value) {
347
+ if (!Array.isArray(tag) || tag[0] !== "meta") return false;
348
+ const attrs = tag[1];
349
+ return attrs?.[attribute] === value;
350
+ }
351
+ function upsertHead(page, summary) {
352
+ const frontmatter = page.frontmatter;
353
+ const currentHead = Array.isArray(frontmatter.head) ? frontmatter.head : [];
354
+ const nextHead = currentHead.filter(
355
+ (tag) => !isTargetMeta(tag, "name", "description") && !isTargetMeta(tag, "property", "og:description")
356
+ );
357
+ nextHead.push(
358
+ ["meta", { name: "description", content: summary }],
359
+ ["meta", { property: "og:description", content: summary }]
360
+ );
361
+ frontmatter.head = nextHead;
362
+ const data = page.data;
363
+ const dataFrontmatter = data.frontmatter;
364
+ dataFrontmatter.head = nextHead;
365
+ }
366
+ function writeSummary(page, summary, insertToHead) {
367
+ const data = page.data;
368
+ data.summary = summary;
369
+ const frontmatter = page.frontmatter;
370
+ frontmatter.description = summary;
371
+ const dataFrontmatter = data.frontmatter;
372
+ dataFrontmatter.description = summary;
373
+ if (insertToHead) upsertHead(page, summary);
374
+ }
375
+ async function processPage(page, options, stats) {
376
+ if (options.filter) {
377
+ let allowed = false;
378
+ try {
379
+ allowed = options.filter(page) !== false;
380
+ } catch (error) {
381
+ const message = error instanceof Error ? error.message : String(error);
382
+ console.warn(`[AutoSummary] filter \u6267\u884C\u5931\u8D25\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u9875\u9762\uFF1A${message}`);
383
+ }
384
+ if (!allowed) {
385
+ stats.filtered += 1;
386
+ logSkip(page, "\u88AB filter \u914D\u7F6E\u6392\u9664");
387
+ return;
388
+ }
389
+ }
390
+ if (hasExistingDescription(page) && !options.overwrite) {
391
+ stats.existingDescription += 1;
392
+ logSkip(page, "\u5DF2\u5B58\u5728 description\uFF0C\u4E14 overwrite=false");
393
+ return;
394
+ }
395
+ const content = typeof page.content === "string" ? page.content : "";
396
+ const manual = getManualSummary(content, options.separator);
397
+ let summary;
398
+ if (manual !== null) {
399
+ if (!manual) {
400
+ stats.tooShort += 1;
401
+ logSkip(page, "\u624B\u52A8\u6458\u8981\u5206\u9694\u7B26\u4E4B\u524D\u6CA1\u6709\u53EF\u7528\u6B63\u6587");
402
+ return;
403
+ }
404
+ summary = fitSummary(manual, options.length);
405
+ stats.manual += 1;
406
+ } else {
407
+ const plainText = extractPlainText(content);
408
+ if (isTextTooShort(plainText, options.minLength)) {
409
+ stats.tooShort += 1;
410
+ logSkip(
411
+ page,
412
+ `\u6B63\u6587\u4EC5 ${plainText.length} \u5B57\uFF0C\u5C11\u4E8E ${options.minLength} \u5B57`
413
+ );
414
+ return;
415
+ }
416
+ if (options.strategy === "ai") {
417
+ const aiSummary = await generateAiSummary(content, options);
418
+ if (aiSummary) {
419
+ summary = fitSummary(aiSummary, options.length);
420
+ } else {
421
+ stats.aiFallback += 1;
422
+ summary = extractLocalSummary(content, options.length);
423
+ }
424
+ } else {
425
+ summary = extractLocalSummary(content, options.length);
426
+ }
427
+ stats.generated += 1;
428
+ }
429
+ writeSummary(page, summary, options.insertToHead);
430
+ stats.written += 1;
431
+ }
432
+ function printStats(stats) {
433
+ const lines = [
434
+ "",
435
+ "[AutoSummary] \u6784\u5EFA\u671F\u6458\u8981\u7EDF\u8BA1",
436
+ ` \u5171\u5904\u7406\u7BC7\u6570\uFF1A${stats.total}`,
437
+ ` \u4F7F\u7528\u624B\u52A8\u6458\u8981\uFF1A${stats.manual}`,
438
+ ` \u81EA\u52A8\u751F\u6210\uFF1A${stats.generated}`,
439
+ ` \u56E0\u5185\u5BB9\u8FC7\u77ED\u8DF3\u8FC7\uFF1A${stats.tooShort}`,
440
+ ` \u5DF2\u6709 description \u8DF3\u8FC7\uFF1A${stats.existingDescription}`,
441
+ ` \u88AB filter \u6392\u9664\uFF1A${stats.filtered}`
442
+ ];
443
+ if (stats.aiFallback > 0) {
444
+ lines.push(` AI \u56DE\u9000\u672C\u5730\uFF1A${stats.aiFallback}`);
445
+ }
446
+ lines.push(` \u5B9E\u9645\u5199\u5165 page.data.summary\uFF1A${stats.written}`, "");
447
+ console.log(lines.join("\n"));
448
+ }
449
+ var autoSummaryPlugin = (options = {}) => {
450
+ const resolvedOptions = resolveOptions(options);
451
+ const stats = createStats();
452
+ return {
453
+ name: "plugin-autosummary",
454
+ multiple: false,
455
+ extendsPage: async (page) => {
456
+ stats.total += 1;
457
+ await processPage(page, resolvedOptions, stats);
458
+ },
459
+ onGenerated: () => {
460
+ printStats(stats);
461
+ }
462
+ };
463
+ };
464
+ var index_default = autoSummaryPlugin;
465
+ export {
466
+ autoSummaryPlugin,
467
+ index_default as default
468
+ };
469
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/extract.ts","../src/ai.ts","../src/index.ts"],"sourcesContent":["import type {\n CandidateSegment,\n ExtractedMarkdown,\n} from './types.js'\n\n/** 正文字数低于该阈值时视为“内容过短”,跳过自动摘要。 */\nexport const MIN_SUMMARY_CONTENT_LENGTH = 40\n\n/** 压缩所有空白字符,便于计数与拼接。 */\nexport function normalizeText(text: string): string {\n return text.replace(/\\s+/g, ' ').trim()\n}\n\n/** 按字节安全的目标字数截断,超长时以省略号结尾。 */\nexport function fitSummary(text: string, length: number): string {\n const normalized = normalizeText(text)\n const max = Math.max(1, Math.floor(length))\n const chars = Array.from(normalized)\n\n if (chars.length <= max) return normalized\n if (max === 1) return '…'\n\n return `${chars.slice(0, max - 1).join('')}…`\n}\n\n/** 去掉 VuePress 可能保留下来的 YAML frontmatter。 */\nfunction stripFrontmatter(content: string): string {\n const source = content.replace(/^\\uFEFF/, '')\n const match = source.match(/^---[ \\t]*\\r?\\n[\\s\\S]*?\\r?\\n---[ \\t]*(?:\\r?\\n|$)/)\n return match ? source.slice(match[0].length) : source\n}\n\n/** 将行内 Markdown 标记还原为可读文本。 */\nfunction cleanInline(input: string): string {\n return input\n .replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1') // 图片保留 alt\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1') // 链接保留文字\n .replace(/`([^`]*)`/g, '$1') // 行内代码\n .replace(/(\\*\\*|__)(.*?)\\1/g, '$2') // 粗体\n .replace(/(\\*|_)(.*?)\\1/g, '$2') // 斜体\n .replace(/~~(.*?)~~/g, '$1') // 删除线\n .replace(/<[^>]*>/g, '') // HTML 标签\n .replace(/\\\\([\\\\`*_{}[\\]()#+\\-.!])/g, '$1') // 转义符\n .replace(/&nbsp;/gi, ' ')\n .replace(/&amp;/gi, '&')\n .replace(/&lt;/gi, '<')\n .replace(/&gt;/gi, '>')\n .replace(/&quot;/gi, '\"')\n .replace(/&#39;|&apos;/gi, \"'\")\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** 取一段文本中的第一句(同时支持中英文标点)。 */\nfunction splitFirstSentence(text: string): string {\n const normalized = normalizeText(text)\n if (!normalized) return ''\n\n const match = normalized.match(/^.*?(?:[。!?!?;;]+|\\.(?=\\s|$))/u)\n return (match?.[0] ?? normalized).trim()\n}\n\n/** 给摘要补上中文句号,让导读末尾保持完整。 */\nfunction ensureTerminalPunctuation(text: string): string {\n if (!text) return text\n return /[。!?!?;;…]$/u.test(text) ? text : `${text}。`\n}\n\n/**\n * 解析 Markdown 结构:标题层级、各节首句、列表项、代码块语言分布。\n * 全程只做字符串处理,不依赖任何外部服务。\n */\nexport function extractMarkdown(content: string): ExtractedMarkdown {\n const source = stripFrontmatter(content)\n const lines = source.split(/\\r?\\n/)\n\n const bodyParts: string[] = []\n const sections: ExtractedMarkdown['sections'] = []\n const listItems: string[] = []\n const codeLanguageCounts: Record<string, number> = {}\n\n let inFence = false\n let fenceChar = ''\n let fenceLength = 0\n let currentSection: ExtractedMarkdown['sections'][number] | null = null\n let sectionBuffer: string[] = []\n\n for (const line of lines) {\n const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)\n\n if (inFence) {\n const closing = line.match(/^ {0,3}(`{3,}|~{3,})[ \\t]*$/)\n if (\n closing\n && closing[1][0] === fenceChar\n && closing[1].length >= fenceLength\n ) {\n inFence = false\n }\n continue\n }\n\n if (fenceMatch) {\n inFence = true\n fenceChar = fenceMatch[1][0]\n fenceLength = fenceMatch[1].length\n const language = (fenceMatch[2] ?? '')\n .trim()\n .split(/\\s+/)[0]\n ?.replace(/[^\\w+#.-]/g, '')\n .toLowerCase()\n\n if (language) {\n codeLanguageCounts[language] = (codeLanguageCounts[language] ?? 0) + 1\n }\n continue\n }\n\n const headingMatch = line.match(/^ {0,3}(#{1,6})\\s+(.+?)\\s*#*\\s*$/)\n if (headingMatch) {\n const title = cleanInline(headingMatch[2].replace(/\\s+#+\\s*$/, ''))\n currentSection = {\n level: headingMatch[1].length,\n title,\n firstSentence: '',\n }\n sections.push(currentSection)\n sectionBuffer = []\n continue\n }\n\n const listMatch = line.match(/^\\s*(?:[-*+]|\\d+[.)])\\s+(.+)$/)\n if (listMatch) {\n const item = cleanInline(listMatch[1])\n if (item.length >= 2) listItems.push(item)\n continue\n }\n\n const cleaned = cleanInline(line)\n if (!cleaned) continue\n\n bodyParts.push(cleaned)\n\n if (currentSection && !currentSection.firstSentence) {\n sectionBuffer.push(cleaned)\n const joined = sectionBuffer.join(' ')\n if (/[。!?!?;;]|\\.(?=\\s|$)/u.test(joined) || joined.length >= 160) {\n currentSection.firstSentence = splitFirstSentence(joined)\n sectionBuffer = []\n }\n }\n }\n\n if (currentSection && !currentSection.firstSentence && sectionBuffer.length) {\n currentSection.firstSentence = splitFirstSentence(sectionBuffer.join(' '))\n }\n\n const plainText = normalizeText(bodyParts.join(' '))\n const title = sections.find((section) => section.level === 1)?.title\n ?? splitFirstSentence(plainText)\n const codeLanguages = Object.entries(codeLanguageCounts)\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([language]) => language)\n\n return {\n plainText,\n title,\n sections,\n listItems,\n codeLanguages,\n codeLanguageCounts,\n }\n}\n\n/** 只取正文纯文本,用于过短判断。 */\nexport function extractPlainText(content: string): string {\n return extractMarkdown(content).plainText\n}\n\n/** 读取手动分隔符之前的正文;没有分隔符时返回 null。 */\nexport function getManualSummary(content: string, separator: string): string | null {\n if (!separator) return null\n\n const source = stripFrontmatter(content)\n const index = source.indexOf(separator)\n if (index < 0) return null\n\n return normalizeText(cleanInline(source.slice(0, index)))\n}\n\n/** 判断正文是否过短。 */\nexport function isTextTooShort(\n text: string,\n minLength = MIN_SUMMARY_CONTENT_LENGTH,\n): boolean {\n return normalizeText(text).length < Math.max(1, Math.floor(minLength))\n}\n\n/** 同文本只保留权重最高的候选片段。 */\nfunction dedupeCandidates(candidates: CandidateSegment[]): CandidateSegment[] {\n const map = new Map<string, CandidateSegment>()\n\n for (const candidate of candidates) {\n const text = normalizeText(candidate.text)\n if (text.length < 2) continue\n\n const previous = map.get(text)\n if (!previous || previous.weight < candidate.weight) {\n map.set(text, { ...candidate, text })\n }\n }\n\n return [...map.values()]\n}\n\n/**\n * 按权重挑选片段:权重高的完整保留,低权重片段只有在预算充足时才加入。\n * 只在剩余空间足够时截断最后一个长片段,避免把句子切得支离破碎。\n */\nfunction pickByWeight(\n candidates: CandidateSegment[],\n budget: number,\n limit: number,\n): string[] {\n const useful = dedupeCandidates(candidates)\n if (!useful.length || budget <= 0) return []\n\n const sorted = [...useful].sort((a, b) => b.weight - a.weight)\n const picked: string[] = []\n let used = 0\n\n for (const candidate of sorted) {\n if (picked.length >= limit || used >= budget) break\n\n const text = candidate.text.replace(/[。!?!?;;,,]+$/u, '')\n const length = Array.from(text).length\n if (length < 2) continue\n\n const remaining = budget - used\n let selected = text\n\n if (length > remaining) {\n // 剩余空间太少就不硬塞,保证导读由完整句子组成。\n if (remaining < 12 || length < remaining + 6) continue\n selected = `${Array.from(text).slice(0, remaining - 1).join('')}…`\n }\n\n picked.push(selected)\n used += Array.from(selected).length + 1\n }\n\n return picked\n}\n\n/**\n * 默认本地策略:\n * 1. 一级标题 / 首句作为主题;\n * 2. 二三级标题、各节首句、列表项按权重组成导读;\n * 3. 代码块语言分布作为补充说明。\n */\nexport function extractLocalSummary(content: string, length = 120): string {\n const extracted = extractMarkdown(content)\n const target = Math.max(1, Math.floor(length))\n const intro = splitFirstSentence(extracted.plainText)\n\n const introCandidates: CandidateSegment[] = intro\n ? [{ text: intro, weight: 5, kind: 'sentence' }]\n : []\n\n const outlineCandidates: CandidateSegment[] = []\n\n // 一级标题已经作为“本文围绕《...》”的前缀,不再重复放进导读提纲。\n for (const section of extracted.sections) {\n if (section.title) {\n const weight = section.level <= 2\n ? 3.4\n : Math.max(1.6, 3.4 - (section.level - 2) * 0.4)\n outlineCandidates.push({ text: section.title, weight, kind: 'section' })\n }\n if (section.firstSentence && section.firstSentence !== intro) {\n outlineCandidates.push({\n text: section.firstSentence,\n weight: 4.2,\n kind: 'sentence',\n })\n }\n }\n\n for (const item of extracted.listItems.slice(0, 10)) {\n if (item !== intro) {\n outlineCandidates.push({ text: item, weight: 1.8, kind: 'list' })\n }\n }\n\n const evidenceCandidates: CandidateSegment[] = extracted.codeLanguages\n .slice(0, 4)\n .map((language) => ({ text: language, weight: 1.2, kind: 'code' }))\n\n const introBudget = Math.max(20, Math.floor(target * 0.35))\n const outlineBudget = Math.max(20, Math.floor(target * 0.5))\n const evidenceBudget = Math.max(8, target - introBudget - outlineBudget)\n\n const introText = pickByWeight(introCandidates, introBudget, 1)[0] ?? ''\n const outline = pickByWeight(outlineCandidates, outlineBudget, 6)\n const evidence = pickByWeight(evidenceCandidates, evidenceBudget, 3)\n\n const parts: string[] = []\n if (extracted.title) parts.push(`本文围绕《${extracted.title}》`)\n if (introText) parts.push(introText)\n if (outline.length) parts.push(`重点包括:${outline.join(';')}`)\n if (evidence.length) parts.push(`文中结合 ${evidence.join('、')} 代码示例`)\n\n const summary = ensureTerminalPunctuation(\n parts.join(',').replace(/,{2,}/g, ',').replace(/;{2,}/g, ';'),\n )\n\n return fitSummary(summary, target)\n}\n","import { normalizeText } from './extract.js'\nimport type { RequiredAutoSummaryOptions } from './types.js'\n\n// 注意:本文件只会被插件的 Node 入口引入。\n// 不要从任何客户端组件中 import 本模块,否则 apiKey 可能被打进浏览器产物。\n\n/** 默认接口超时时间。 */\nconst DEFAULT_TIMEOUT_MS = 30_000\n\n/** 默认发送给模型的最大正文字符数,避免单次请求过大。 */\nconst DEFAULT_MAX_INPUT_CHARS = 12_000\n\n/** 默认提示词,{length} 会被替换成配置的目标字数。 */\nconst DEFAULT_PROMPT = `请为以下 Markdown 文章生成一段中文导读摘要,约 {length} 字。要求:只输出摘要正文;概括文章主题、核心结论和主要内容;不要输出“摘要:”等前缀,不要使用 Markdown 或 HTML。`\n\n/** 判断 AI 接口三要素是否齐全。 */\nexport function isAiConfigured(options: RequiredAutoSummaryOptions): boolean {\n return Boolean(options.api && options.apiKey && options.model)\n}\n\n/** 递归提取模型返回中的文本字段,兼容常见 OpenAI 兼容接口。 */\nfunction readText(value: unknown): string {\n if (typeof value === 'string') return value.trim()\n\n if (Array.isArray(value)) {\n return value\n .map((item) => readText(item))\n .filter(Boolean)\n .join('\\n')\n .trim()\n }\n\n if (value && typeof value === 'object') {\n const record = value as Record<string, unknown>\n for (const key of ['text', 'content', 'value', 'message']) {\n const text = readText(record[key])\n if (text) return text\n }\n }\n\n return ''\n}\n\n/** 从响应体中读取摘要文本。 */\nfunction pickAiText(data: unknown): string {\n if (!data || typeof data !== 'object') return ''\n\n const record = data as Record<string, unknown>\n const choices = record.choices\n\n if (Array.isArray(choices) && choices.length > 0) {\n const first = choices[0]\n const text = readText(first)\n if (text) return text\n }\n\n for (const key of ['summary', 'response', 'output', 'content', 'text']) {\n const text = readText(record[key])\n if (text) return text\n }\n\n return ''\n}\n\n/** 截断正文,保护大文章不超出接口预算。 */\nfunction truncateInput(content: string): string {\n const chars = Array.from(content)\n if (chars.length <= DEFAULT_MAX_INPUT_CHARS) return content\n return `${chars.slice(0, DEFAULT_MAX_INPUT_CHARS).join('')}\\n\\n[正文已截断]`\n}\n\n/** 脱敏错误信息,绝不将 apiKey 原样输出到终端。 */\nfunction sanitizeError(message: string, options: RequiredAutoSummaryOptions): string {\n let result = message\n\n if (options.apiKey) result = result.split(options.apiKey).join('***')\n if (options.api) result = result.split(options.api).join('[API]')\n\n return result\n .replace(/Bearer\\s+[^\\s\"']+/gi, 'Bearer ***')\n .replace(/sk-[A-Za-z0-9_-]{8,}/g, 'sk-***')\n}\n\n/**\n * 在 Node 端构建期调用大模型接口生成摘要。\n * 配置不完整或请求失败时返回 null,由调用方回退本地策略。\n */\nexport async function generateAiSummary(\n content: string,\n options: RequiredAutoSummaryOptions,\n): Promise<string | null> {\n if (!isAiConfigured(options)) return null\n\n const prompt = (options.prompt ?? DEFAULT_PROMPT).replaceAll(\n '{length}',\n String(options.length),\n )\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS)\n\n try {\n const response = await fetch(options.api!, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${options.apiKey}`,\n },\n body: JSON.stringify({\n model: options.model,\n stream: false,\n temperature: 0.2,\n messages: [\n { role: 'system', content: prompt },\n { role: 'user', content: truncateInput(content) },\n ],\n }),\n signal: controller.signal,\n })\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status} ${response.statusText}`)\n }\n\n const data: unknown = await response.json()\n const summary = normalizeText(pickAiText(data))\n return summary || null\n } catch (error) {\n const rawMessage = error instanceof Error ? error.message : String(error)\n console.warn(\n `[AutoSummary] AI 摘要调用失败,已回退本地策略:${sanitizeError(rawMessage, options)}`,\n )\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n","import type {\n HeadConfig,\n Page,\n PageData,\n Plugin,\n} from 'vuepress/core'\nimport { isAiConfigured, generateAiSummary } from './ai.js'\nimport {\n extractLocalSummary,\n extractPlainText,\n fitSummary,\n getManualSummary,\n isTextTooShort,\n} from './extract.js'\nimport type {\n AutoSummaryOptions,\n AutoSummaryStats,\n RequiredAutoSummaryOptions,\n} from './types.js'\n\n/** 默认配置。所有接口调用都发生在 Node 端构建期。 */\nconst DEFAULT_OPTIONS: RequiredAutoSummaryOptions = {\n length: 120,\n minLength: 40,\n separator: '<!-- more -->',\n overwrite: false,\n insertToHead: true,\n strategy: 'local',\n}\n\n/** 创建一份独立的统计数据,避免多次使用插件时互相污染。 */\nfunction createStats(): AutoSummaryStats {\n return {\n total: 0,\n written: 0,\n manual: 0,\n generated: 0,\n tooShort: 0,\n existingDescription: 0,\n filtered: 0,\n aiFallback: 0,\n }\n}\n\n/** 补齐默认值,并对非法 strategy 做容错。 */\nfunction resolveOptions(options: AutoSummaryOptions): RequiredAutoSummaryOptions {\n if (\n options.strategy\n && options.strategy !== 'local'\n && options.strategy !== 'ai'\n ) {\n console.warn(\n `[AutoSummary] 未知 strategy:${String(options.strategy)},已回退为 local。`,\n )\n }\n\n const length = Number.isFinite(options.length)\n ? Math.max(1, Math.floor(options.length!))\n : DEFAULT_OPTIONS.length\n const minLength = Number.isFinite(options.minLength)\n ? Math.max(1, Math.floor(options.minLength!))\n : DEFAULT_OPTIONS.minLength\n\n const resolved: RequiredAutoSummaryOptions = {\n ...DEFAULT_OPTIONS,\n ...options,\n length,\n minLength,\n strategy: options.strategy === 'ai' ? 'ai' : 'local',\n }\n\n // AI 策略缺少 api / apiKey / model 中任意一项时,静默回退本地策略。\n if (resolved.strategy === 'ai' && !isAiConfigured(resolved)) {\n console.warn(\n '[AutoSummary] ai 策略缺少 api / apiKey / model,已自动回退 local 策略。',\n )\n resolved.strategy = 'local'\n }\n\n return resolved\n}\n\n/** 获取用于日志的页面路径。 */\nfunction pageLabel(page: Page): string {\n return page.filePathRelative || page.filePath || page.path || '<未知页面>'\n}\n\n/** 统一输出中文跳过提示,并带上文件路径。 */\nfunction logSkip(page: Page, reason: string): void {\n console.warn(`[AutoSummary] 跳过 ${pageLabel(page)}:${reason}`)\n}\n\n/** 判断页面是否已有非空 description。 */\nfunction hasExistingDescription(page: Page): boolean {\n const frontmatter = page.frontmatter as Record<string, unknown>\n const dataFrontmatter = page.data.frontmatter as Record<string, unknown>\n\n return [frontmatter.description, dataFrontmatter.description].some(\n (value) => typeof value === 'string' && value.trim().length > 0,\n )\n}\n\n/** 判断是否为需要替换的 description meta。 */\nfunction isTargetMeta(\n tag: HeadConfig,\n attribute: 'name' | 'property',\n value: string,\n): boolean {\n if (!Array.isArray(tag) || tag[0] !== 'meta') return false\n\n const attrs = tag[1] as Record<string, boolean | string> | undefined\n return attrs?.[attribute] === value\n}\n\n/** 写入 description / og:description,并移除页面内已有的同名标签。 */\nfunction upsertHead(page: Page, summary: string): void {\n const frontmatter = page.frontmatter as Record<string, unknown>\n const currentHead = Array.isArray(frontmatter.head)\n ? (frontmatter.head as HeadConfig[])\n : []\n\n const nextHead = currentHead.filter(\n (tag) => !isTargetMeta(tag, 'name', 'description')\n && !isTargetMeta(tag, 'property', 'og:description'),\n )\n\n nextHead.push(\n ['meta', { name: 'description', content: summary }],\n ['meta', { property: 'og:description', content: summary }],\n )\n\n frontmatter.head = nextHead\n\n // page.data 是客户端真正读取的对象;同步一份避免主题拿到旧的 frontmatter。\n const data = page.data as PageData & { summary?: string }\n const dataFrontmatter = data.frontmatter as Record<string, unknown>\n dataFrontmatter.head = nextHead\n}\n\n/** 把摘要写入 page.data、frontmatter.description 与 head。 */\nfunction writeSummary(page: Page, summary: string, insertToHead: boolean): void {\n const data = page.data as PageData & { summary?: string }\n data.summary = summary\n\n const frontmatter = page.frontmatter as Record<string, unknown>\n frontmatter.description = summary\n\n const dataFrontmatter = data.frontmatter as Record<string, unknown>\n dataFrontmatter.description = summary\n\n if (insertToHead) upsertHead(page, summary)\n}\n\n/** 处理单个页面。 */\nasync function processPage(\n page: Page,\n options: RequiredAutoSummaryOptions,\n stats: AutoSummaryStats,\n): Promise<void> {\n // 1. 页面过滤。\n if (options.filter) {\n let allowed = false\n try {\n allowed = options.filter(page) !== false\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n console.warn(`[AutoSummary] filter 执行失败,已跳过该页面:${message}`)\n }\n\n if (!allowed) {\n stats.filtered += 1\n logSkip(page, '被 filter 配置排除')\n return\n }\n }\n\n // 2. 已有 description 时默认跳过,避免覆盖人工撰写的 SEO 文案。\n if (hasExistingDescription(page) && !options.overwrite) {\n stats.existingDescription += 1\n logSkip(page, '已存在 description,且 overwrite=false')\n return\n }\n\n const content = typeof page.content === 'string' ? page.content : ''\n\n // 3. 优先使用手动分隔符之前的正文。\n const manual = getManualSummary(content, options.separator)\n let summary: string\n\n if (manual !== null) {\n if (!manual) {\n stats.tooShort += 1\n logSkip(page, '手动摘要分隔符之前没有可用正文')\n return\n }\n\n summary = fitSummary(manual, options.length)\n stats.manual += 1\n } else {\n // 4. 自动摘要前先判断正文长度,太短的文章不生成。\n const plainText = extractPlainText(content)\n if (isTextTooShort(plainText, options.minLength)) {\n stats.tooShort += 1\n logSkip(\n page,\n `正文仅 ${plainText.length} 字,少于 ${options.minLength} 字`,\n )\n return\n }\n\n if (options.strategy === 'ai') {\n const aiSummary = await generateAiSummary(content, options)\n if (aiSummary) {\n summary = fitSummary(aiSummary, options.length)\n } else {\n // 接口缺失或调用失败都会走到这里,保证站点构建不被外部服务阻塞。\n stats.aiFallback += 1\n summary = extractLocalSummary(content, options.length)\n }\n } else {\n summary = extractLocalSummary(content, options.length)\n }\n\n stats.generated += 1\n }\n\n // 5. 写入页面数据与 SEO 元信息。\n writeSummary(page, summary, options.insertToHead)\n stats.written += 1\n}\n\n/** 构建结束后在终端打印统计。 */\nfunction printStats(stats: AutoSummaryStats): void {\n const lines = [\n '',\n '[AutoSummary] 构建期摘要统计',\n ` 共处理篇数:${stats.total}`,\n ` 使用手动摘要:${stats.manual}`,\n ` 自动生成:${stats.generated}`,\n ` 因内容过短跳过:${stats.tooShort}`,\n ` 已有 description 跳过:${stats.existingDescription}`,\n ` 被 filter 排除:${stats.filtered}`,\n ]\n\n if (stats.aiFallback > 0) {\n lines.push(` AI 回退本地:${stats.aiFallback}`)\n }\n\n lines.push(` 实际写入 page.data.summary:${stats.written}`, '')\n\n console.log(lines.join('\\n'))\n}\n\n/**\n * AutoSummary 插件入口。\n *\n * 只返回 VuePress Node 端插件对象,不注册任何客户端配置,\n * 因此 apiKey 不会出现在浏览器产物中。\n */\nexport const autoSummaryPlugin = (options: AutoSummaryOptions = {}): Plugin => {\n const resolvedOptions = resolveOptions(options)\n const stats = createStats()\n\n return {\n name: 'plugin-autosummary',\n multiple: false,\n\n extendsPage: async (page) => {\n stats.total += 1\n await processPage(page, resolvedOptions, stats)\n },\n\n onGenerated: () => {\n printStats(stats)\n },\n }\n}\n\nexport default autoSummaryPlugin\n\nexport type {\n AutoSummaryOptions,\n PageDataWithSummary,\n SummarySource,\n SummaryStrategy,\n} from './types.js'\n"],"mappings":";AAMO,IAAM,6BAA6B;AAGnC,SAAS,cAAc,MAAsB;AAClD,SAAO,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACxC;AAGO,SAAS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,YAAY;AAE1B,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IAEV,aAAa,OAAO,SAAS;AAC3B,YAAM,SAAS;AACf,YAAM,YAAY,MAAM,iBAAiB,KAAK;AAAA,IAChD;AAAA,IAEA,aAAa,MAAM;AACjB,iBAAW,KAAK;AAAA,IAClB;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;","names":["title"]}
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "plugin-autosummary",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "VuePress 2 构建期自动生成文章摘要、结构化导读与 SEO description 的插件",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "sideEffects": false,
21
+ "scripts": {
22
+ "build": "tsup",
23
+ "dev": "tsup --watch",
24
+ "typecheck": "tsc --noEmit",
25
+ "test": "node tests/run.mjs",
26
+ "verify": "npm run typecheck && npm run build && npm test",
27
+ "release:npm": "node scripts/publish.mjs autosummary plugin-autosummary"
28
+ },
29
+ "keywords": [
30
+ "vuepress",
31
+ "vuepress2",
32
+ "vuepress-plugin",
33
+ "plugin",
34
+ "summary",
35
+ "extractive-summary",
36
+ "seo",
37
+ "description",
38
+ "og-description",
39
+ "reading-guide"
40
+ ],
41
+ "homepage": "https://github.com/techjiang/vuepress-plugin-autosummary#readme",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/techjiang/vuepress-plugin-autosummary.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/techjiang/vuepress-plugin-autosummary/issues"
48
+ },
49
+ "license": "MIT",
50
+ "author": {
51
+ "name": "科技酱",
52
+ "email": "official@tech.asoe.cn",
53
+ "url": "https://github.com/techjiang/"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "engines": {
59
+ "node": ">=18"
60
+ },
61
+ "peerDependencies": {
62
+ "vuepress": ">=2.0.0-rc.0 <3"
63
+ },
64
+ "devDependencies": {
65
+ "@types/node": "^20.17.0",
66
+ "tsup": "^8.3.0",
67
+ "typescript": "^5.7.0",
68
+ "vuepress": "^2.0.0-rc.33"
69
+ }
70
+ }