vite-plugin-refresh-guard 0.2.2 → 0.3.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # 更新日志
2
2
 
3
+ ## v0.3.1 (2026-10-18)
4
+
5
+ - **组件依赖纯净化 (`UpdateCard.vue`)**:
6
+ 优化 `UpdateCard.vue` 的 Props 声明与要点解析器为 SFC 内联实现,消除对外部相对路径文件的类型与函数引用,避免在跨包/无 Node fs 环境的某些 Vue 编译管道(如纯客户端编译)中报 `compileScript No fs option provided` 错误。
7
+
8
+ ## v0.3.0 (2026-10-18)
9
+
10
+ - **全量更新日志导出 (`allVersions`)**:
11
+ 虚拟模块 `virtual:refresh-guard-changelog` 除了 `latestVersion`/`latestContent` 外,新增 `allVersions: Array<{ version: string, date: string | null, content: string }>`。前端站内更新中心可直接引用,无需自写后端接口读盘。
12
+ 解析器兼容主流 Keep a Changelog 格式:`## [1.2.0] - 2026-10-18`、`## v1.2.0 (2026-10-18)`、`## 1.2.0`。
13
+ - **静态 CHANGELOG 运行时拉取模式 (`mode: 'fetch'`)**:
14
+ 插件配置支持 `changelog: { mode: 'fetch', outFile?: string, url?: string }`,构建时自动将本地 CHANGELOG 写入 `dist` 静态资源目录。
15
+ 运行时 `UpdateChecker` 及 `useVersionCheck` 支持 `changelog: { mode: 'fetch', url: '/CHANGELOG.md' }`,在发现新版本时自动异步 fetch 并解析,触发 `changelog-loaded` 事件,状态暴露于 `checker.changelog`。
16
+ 导出通用纯函数 `parseChangelog`、`extractBulletPoints` 与 `fetchChangelog`。
17
+ - **新版本功能通知卡片组件 (`UpdateCard`)**:
18
+ 新增开箱即用的新功能概览卡片,提供 Vue (`vite-plugin-refresh-guard/vue/UpdateCard.vue`) 与 React (`vite-plugin-refresh-guard/react/UpdateCard`) 原生支持。
19
+ 自动从 Markdown 正文提取列表要点(bullet points);支持版本徽标、日期展示、最大条数限制(超出折叠并提示 "+N 项更多改进")、一键刷新与查看完整日志链接;支持浮动(floating)与行内嵌入(inline)双布局及深浅色主题自适应。
20
+
3
21
  ## v0.2.2 (2026-10-09)
4
22
 
5
23
  **只动 npm 元数据,一行运行期代码没改** —— 目的是让插件在「版本更新提示」这个品类里被搜到。
package/README.en.md CHANGED
@@ -128,6 +128,7 @@ interface VersionCheckerOptions {
128
128
  autoRefreshDelay?: number // toast-auto only, default 1200ms
129
129
  refreshCooldown?: number // min ms between forced refreshes, default 90s — guards against reload loops
130
130
  guardChunkErrors?: boolean // force-refresh once on a stale-chunk load failure, default true
131
+ changelog?: string | boolean | { mode?: 'bake' | 'fetch', url?: string } // runtime changelog options
131
132
  onUpdateAvailable?: (info) => void | boolean // return false to take over the UI yourself
132
133
  onBeforeRefresh?: () => void // flush analytics etc. right before location.reload()
133
134
  }
@@ -140,22 +141,75 @@ interface RefreshGuardPluginOptions {
140
141
  version?: string // default: read from package.json
141
142
  includeCommit?: boolean // default true; silently omitted outside a git repo
142
143
  outFile?: string // default 'version.json'
143
- changelog?: string | false // default 'CHANGELOG.md'; false disables the virtual module
144
+ changelog?: string | false | {
145
+ mode?: 'bake' | 'fetch' // 'bake' bakes into virtual module (default); 'fetch' copies to dist for runtime fetch
146
+ file?: string // local changelog file path, default 'CHANGELOG.md'
147
+ outFile?: string // output filename in dist, default 'CHANGELOG.md'
148
+ url?: string // runtime fetch URL, default '/CHANGELOG.md'
149
+ }
144
150
  }
145
151
  ```
146
152
 
147
- ## Changelog display (optional, decoupled from the refresh decision)
153
+ ## Changelog Display (Full export and Runtime fetch)
148
154
 
149
155
  ```ts
150
- import { latestVersion, latestContent } from 'virtual:refresh-guard-changelog'
156
+ import { latestVersion, latestContent, allVersions } from 'virtual:refresh-guard-changelog'
151
157
  ```
152
158
 
153
- Parses `## vX.Y.Z (date)` headings (same format as Keep a Changelog / most auto-generated
154
- changelogs) out of your `CHANGELOG.md` and exposes the latest section's version and markdown
155
- body. This is independent of the refresh-trigger logic on purpose — showing "what's new" and
156
- deciding "when do we reload" are different product decisions, and coupling them (as several
157
- of the projects this package was extracted from originally did) is how you end up with two
158
- mechanisms fighting each other.
159
+ - **Latest & Full History**: `latestVersion` and `latestContent` provide the newest version title and markdown body; `allVersions: Array<{ version, date, content }>` parses all historical version sections, enabling in-app changelog centers without custom backend APIs.
160
+ - **Runtime Fetch Mode**: Configure `refreshGuard({ changelog: { mode: 'fetch' } })` to emit `dist/CHANGELOG.md` at build time. The client can automatically fetch and parse updates at runtime (`useVersionCheck` exposes `changelog` and `fetchChangelog()`).
161
+ - **Bullet Extraction Utility**: `extractBulletPoints(markdown)` automatically extracts list items from markdown text.
162
+
163
+ ## Feature Notification Card (UpdateCard)
164
+
165
+ Need a rich feature notification card instead of a plain toast notice? Drop in `UpdateCard`:
166
+
167
+ - **Auto Bullet Extraction**: Automatically parses list items (`- `, `* `, `1. `) from Markdown content into clean bullet points.
168
+ - **Dual Layout**: `layout="floating"` for a smooth slide-in bottom-right notification card, or `layout="inline"` to embed in a dashboard/header.
169
+ - **Interactive**: Version badge, release date, max item truncation (with "+N more improvements"), one-click refresh button, and "view full changelog" link.
170
+
171
+ **Vue**
172
+
173
+ ```vue
174
+ <script setup lang="ts">
175
+ import { useVersionCheck } from 'vite-plugin-refresh-guard/vue'
176
+ import UpdateCard from 'vite-plugin-refresh-guard/vue/UpdateCard.vue'
177
+ import { latestContent, latestVersion } from 'virtual:refresh-guard-changelog'
178
+
179
+ const { hasUpdate, latestInfo, applyUpdate } = useVersionCheck(__REFRESH_GUARD_VERSION__)
180
+ </script>
181
+
182
+ <template>
183
+ <UpdateCard
184
+ :visible="hasUpdate"
185
+ :version="latestInfo?.version || latestVersion"
186
+ :content="latestContent"
187
+ view-more-url="/#/changelog"
188
+ @refresh="applyUpdate"
189
+ />
190
+ </template>
191
+ ```
192
+
193
+ **React**
194
+
195
+ ```tsx
196
+ import { useVersionCheck } from 'vite-plugin-refresh-guard/react'
197
+ import { UpdateCard } from 'vite-plugin-refresh-guard/react/UpdateCard'
198
+ import { latestContent } from 'virtual:refresh-guard-changelog'
199
+
200
+ function App() {
201
+ const { hasUpdate, latestInfo, applyUpdate } = useVersionCheck(__REFRESH_GUARD_VERSION__)
202
+ return (
203
+ <UpdateCard
204
+ visible={hasUpdate}
205
+ version={latestInfo?.version}
206
+ content={latestContent}
207
+ viewMoreUrl="/#/changelog"
208
+ onRefresh={applyUpdate}
209
+ />
210
+ )
211
+ }
212
+ ```
159
213
 
160
214
  ## Styling
161
215
 
package/README.md CHANGED
@@ -142,6 +142,7 @@ interface VersionCheckerOptions {
142
142
  autoRefreshDelay?: number // 仅 toast-auto 用,默认 1200ms
143
143
  refreshCooldown?: number // 两次强制刷新之间的最短间隔,默认 90 秒——防止刷新死循环
144
144
  guardChunkErrors?: boolean // 旧 chunk 加载失败时强刷一次,默认 true
145
+ changelog?: string | boolean | { mode?: 'bake' | 'fetch', url?: string } // 运行时拉取 changelog
145
146
  onUpdateAvailable?: (info) => void | boolean // 返回 false 可以自己接管 UI
146
147
  onBeforeRefresh?: () => void // 真正 location.reload() 前调用,适合在这里补埋点
147
148
  }
@@ -154,17 +155,75 @@ interface RefreshGuardPluginOptions {
154
155
  version?: string // 默认读 package.json
155
156
  includeCommit?: boolean // 默认 true;非 git 仓库时静默省略,不报错
156
157
  outFile?: string // 默认 'version.json'
157
- changelog?: string | false // 默认 'CHANGELOG.md';false 关闭虚拟模块
158
+ changelog?: string | false | {
159
+ mode?: 'bake' | 'fetch' // 'bake' 构建期烘焙进虚拟模块(默认);'fetch' 复制到 dist 供运行时拉取
160
+ file?: string // 本地 CHANGELOG 路径,默认 'CHANGELOG.md'
161
+ outFile?: string // 产物文件名,默认 'CHANGELOG.md'
162
+ url?: string // 运行时拉取 URL,默认 '/CHANGELOG.md'
163
+ }
158
164
  }
159
165
  ```
160
166
 
161
- ## 更新日志展示(可选,跟"要不要刷新"这个决定解耦)
167
+ ## 更新日志展示(全量导出与运行时拉取)
162
168
 
163
169
  ```ts
164
- import { latestVersion, latestContent } from 'virtual:refresh-guard-changelog'
170
+ import { latestVersion, latestContent, allVersions } from 'virtual:refresh-guard-changelog'
165
171
  ```
166
172
 
167
- 从你的 `CHANGELOG.md` 里解析 `## vX.Y.Z (date)` 这种格式的标题(跟 Keep a Changelog 及大多数自动生成的更新日志一致),暴露最新一条的版本号和 markdown 正文。这个功能故意跟"什么时候刷新"的逻辑解耦——"展示更新了什么"和"什么时候该刷新"是两个不同的产品决策,本包最初就是从几个把这两件事强行绑死在一起的项目里抽出来的,绑死的下场就是两套机制互相打架。
173
+ - **最新版与历史全量**:`latestVersion` 与 `latestContent` 提供最新版本的版本号与正文;`allVersions: Array<{ version, date, content }>` 解析了 `CHANGELOG.md` 中所有历史版本块,前端更新中心/日志大盘页面可直接渲染,无需后端写文件读取接口。
174
+ - **运行时动态拉取模式**:配置 `refreshGuard({ changelog: { mode: 'fetch' } })`,构建时自动把 CHANGELOG 写入 `dist`。客户端可在检测到更新时自动拉取最新静态文件(`useVersionCheck` 返回的 `changelog` 对象与 `fetchChangelog()` 方法),服务器只需同步静态 markdown,无需重复构建。
175
+ - **要点提取工具**:导出纯函数 `extractBulletPoints(markdown)`,自动从正文中提炼列表项。
176
+
177
+ ## 新功能通知卡片组件(UpdateCard)
178
+
179
+ 想要更丰富的"功能更新卡片"而不是简单的文字提示条?引入 `UpdateCard`,开箱即用:
180
+
181
+ - **自动要点提炼**:自动识别并提取 Markdown 正文中的更新条目(`- ` / `* ` / `1. ` 等),以整洁的 Bullet 列表展示。
182
+ - **双布局支持**:默认 `layout="floating"` 右下角平滑滑入浮动卡片;也可设为 `layout="inline"` 嵌入到仪表盘或大盘通知栏。
183
+ - **闭环交互**:带版本号与发布日期徽标、最多展示条数限制(超出提示 "+N 项更多改进")、一键刷新按钮与"查看完整更新日志"跳转外链。
184
+
185
+ **Vue**
186
+
187
+ ```vue
188
+ <script setup lang="ts">
189
+ import { useVersionCheck } from 'vite-plugin-refresh-guard/vue'
190
+ import UpdateCard from 'vite-plugin-refresh-guard/vue/UpdateCard.vue'
191
+ import { latestContent, latestVersion } from 'virtual:refresh-guard-changelog'
192
+
193
+ const { hasUpdate, latestInfo, applyUpdate } = useVersionCheck(__REFRESH_GUARD_VERSION__)
194
+ </script>
195
+
196
+ <template>
197
+ <UpdateCard
198
+ :visible="hasUpdate"
199
+ :version="latestInfo?.version || latestVersion"
200
+ :content="latestContent"
201
+ view-more-url="/#/changelog"
202
+ @refresh="applyUpdate"
203
+ />
204
+ </template>
205
+ ```
206
+
207
+ **React**
208
+
209
+ ```tsx
210
+ import { useVersionCheck } from 'vite-plugin-refresh-guard/react'
211
+ import { UpdateCard } from 'vite-plugin-refresh-guard/react/UpdateCard'
212
+ import { latestContent } from 'virtual:refresh-guard-changelog'
213
+
214
+ function App() {
215
+ const { hasUpdate, latestInfo, applyUpdate } = useVersionCheck(__REFRESH_GUARD_VERSION__)
216
+ return (
217
+ <UpdateCard
218
+ visible={hasUpdate}
219
+ version={latestInfo?.version}
220
+ content={latestContent}
221
+ viewMoreUrl="/#/changelog"
222
+ onRefresh={applyUpdate}
223
+ />
224
+ )
225
+ }
226
+ ```
168
227
 
169
228
  ## 样式定制
170
229
 
package/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: refresh-guard
3
- description: "vite-plugin-refresh-guard 的 agent 接入手册。给 Vite 前端项目加'检测新版本部署→通知→刷新'机制,三档强度可选(静默自动刷新 / toast提示+短延迟自动刷新 / 弹窗阻断必须手动点击),核心逻辑框架无关,Vue/React 各有一份薄适配层,另附一个独立可选的 CHANGELOG.md 展示层。在 Vite 项目里需要处理'部署新版本后用户还在用旧代码/旧chunk 404 白屏'问题,或者想把项目里手写的一次性 version-check 脚本换成可维护的通用方案时用这个。"
3
+ description: "vite-plugin-refresh-guard 的 agent 接入手册。给 Vite 前端项目加'检测新版本部署→通知→刷新'机制,三档强度可选(静默自动刷新 / toast提示+短延迟自动刷新 / 弹窗阻断必须手动点击),核心逻辑框架无关,Vue/React 各有一份薄适配层,另附全量/最新 CHANGELOG 虚拟模块、运行时拉取模式与开箱即用的新功能卡片组件 UpdateCard。在 Vite 项目里需要处理'部署新版本后用户还在用旧代码/旧chunk 404 白屏'问题,或者想把项目里手写的一次性 version-check 脚本换成可维护的通用方案时用这个。"
4
4
  version: 0.1.0
5
5
  ---
6
6
 
@@ -47,6 +47,7 @@ export default defineConfig({ plugins: [refreshGuard()] })
47
47
  - **不要**在 `mode: 'modal-blocking'` 的弹窗外面又加一个背景点击关闭——设计上就是不可关闭的,加了等于白做这一档
48
48
  - **不要**绕开 `checker.applyUpdate()` 直接手写 `location.reload()`——会跳过 `refreshCooldown` 防抖,遇到 `version.json` 缓存配置有问题时容易刷新死循环
49
49
  - **不要**把"版本更新提示"和"CHANGELOG 展示"强行绑死成一套逻辑——这俩是两码事(一个决定"要不要刷新",一个决定"给用户看什么"),本包故意拆成独立的 `virtual:refresh-guard-changelog` 虚拟模块,各用各的,不想要 changelog 就在插件配置里 `changelog: false`
50
+ - 如果想要更丰富的"功能更新卡片"(含版本号、自动从 Markdown 提取要点、一键刷新与完整日志外链),直接引入 `UpdateCard`(`vite-plugin-refresh-guard/vue/UpdateCard.vue` 或 `vite-plugin-refresh-guard/react/UpdateCard`),不要手写一套卡片弹窗
50
51
  - 项目里如果已经有 `vite-plugin-pwa` 的 `autoUpdate` 在跑,别再叠加本包的 `interval` 轮询去做同一件"静默刷新"的事——两套机制同时静默触发过,历史上就出过"到底是谁刷新的"排查不清的问题,选一个就好
51
52
 
52
53
  ## 参考实现来源
@@ -1,3 +1,7 @@
1
+ import {
2
+ fetchChangelog
3
+ } from "./chunk-JLHX4WLS.js";
4
+
1
5
  // src/core/checker.ts
2
6
  var DEFAULTS = {
3
7
  versionUrl: "/version.json",
@@ -18,6 +22,7 @@ var UpdateChecker = class {
18
22
  this.listeners = /* @__PURE__ */ new Map();
19
23
  this._hasUpdate = false;
20
24
  this._latestInfo = null;
25
+ this._changelog = null;
21
26
  this.visibilityHandler = () => {
22
27
  if (document.visibilityState === "visible") void this.checkNow();
23
28
  };
@@ -37,6 +42,29 @@ var UpdateChecker = class {
37
42
  get latestInfo() {
38
43
  return this._latestInfo;
39
44
  }
45
+ get changelog() {
46
+ return this._changelog;
47
+ }
48
+ /**
49
+ * 运行时拉取并解析 CHANGELOG 文件。
50
+ * 若配置了 `changelog: { mode: 'fetch', url: '...' }`,在发现新版本时会自动触发;
51
+ * 业务层也可主动调用此方法拉取完整历史日志列表。
52
+ */
53
+ async fetchChangelog(customUrl) {
54
+ const rawOpt = this.opts.changelog;
55
+ let url = "/CHANGELOG.md";
56
+ if (customUrl) {
57
+ url = customUrl;
58
+ } else if (typeof rawOpt === "string") {
59
+ url = rawOpt;
60
+ } else if (rawOpt && typeof rawOpt === "object" && rawOpt.url) {
61
+ url = rawOpt.url;
62
+ }
63
+ const result = await fetchChangelog(url);
64
+ this._changelog = result;
65
+ this.emit("changelog-loaded", result);
66
+ return result;
67
+ }
40
68
  start() {
41
69
  if (typeof window === "undefined") return;
42
70
  if (this.opts.interval > 0) {
@@ -82,6 +110,11 @@ var UpdateChecker = class {
82
110
  if (this._hasUpdate) return;
83
111
  this._hasUpdate = true;
84
112
  this._latestInfo = info;
113
+ const rawChangelog = this.opts.changelog;
114
+ const shouldFetch = rawChangelog && (typeof rawChangelog === "string" || typeof rawChangelog === "object" && rawChangelog.mode === "fetch");
115
+ if (shouldFetch) {
116
+ void this.fetchChangelog();
117
+ }
85
118
  const suppress = this.opts.onUpdateAvailable?.(info) === false;
86
119
  this.emit("update-available", info);
87
120
  if (suppress) return;
@@ -106,8 +139,8 @@ var UpdateChecker = class {
106
139
  this.listeners.get(event).add(listener);
107
140
  return () => this.listeners.get(event)?.delete(listener);
108
141
  }
109
- emit(event, info) {
110
- this.listeners.get(event)?.forEach((cb) => cb(info));
142
+ emit(event, data) {
143
+ this.listeners.get(event)?.forEach((cb) => cb(data));
111
144
  }
112
145
  };
113
146
 
@@ -0,0 +1,67 @@
1
+ // src/core/changelog.ts
2
+ function extractBulletPoints(content) {
3
+ if (!content || typeof content !== "string") return [];
4
+ const lines = content.split("\n");
5
+ const bullets = [];
6
+ for (const line of lines) {
7
+ const trimmed = line.trim();
8
+ const m = trimmed.match(/^(?:[-*+•]|\d+\.)\s+(.+)$/);
9
+ if (m && m[1]) {
10
+ const text = m[1].trim();
11
+ if (text) {
12
+ bullets.push(text);
13
+ }
14
+ }
15
+ }
16
+ return bullets;
17
+ }
18
+ function parseChangelog(markdown) {
19
+ if (!markdown || typeof markdown !== "string") {
20
+ return { latestVersion: null, latestContent: "", allVersions: [] };
21
+ }
22
+ const sections = markdown.split(/^##\s+/m);
23
+ if (sections.length <= 1) {
24
+ return { latestVersion: null, latestContent: "", allVersions: [] };
25
+ }
26
+ const allVersions = [];
27
+ for (let i = 1; i < sections.length; i++) {
28
+ const sec = sections[i];
29
+ const firstNewline = sec.indexOf("\n");
30
+ const headerLine = (firstNewline === -1 ? sec : sec.slice(0, firstNewline)).trim();
31
+ const content = (firstNewline === -1 ? "" : sec.slice(firstNewline + 1)).trim();
32
+ const m = headerLine.match(/^\[?(v?[\d.]+)\]?(?:\s*[-–—(]\s*([\d\w.-]+)\s*\)?)?/i);
33
+ if (m && m[1]) {
34
+ allVersions.push({
35
+ version: m[1],
36
+ date: m[2] || null,
37
+ content
38
+ });
39
+ }
40
+ }
41
+ return {
42
+ latestVersion: allVersions[0]?.version ?? null,
43
+ latestContent: allVersions[0]?.content ?? "",
44
+ allVersions
45
+ };
46
+ }
47
+ async function fetchChangelog(url = "/CHANGELOG.md", init) {
48
+ if (typeof window === "undefined" && typeof fetch === "undefined") {
49
+ return { latestVersion: null, latestContent: "", allVersions: [] };
50
+ }
51
+ try {
52
+ const resp = await fetch(url, { cache: "no-store", ...init });
53
+ if (!resp.ok) {
54
+ return { latestVersion: null, latestContent: "", allVersions: [] };
55
+ }
56
+ const text = await resp.text();
57
+ return parseChangelog(text);
58
+ } catch {
59
+ return { latestVersion: null, latestContent: "", allVersions: [] };
60
+ }
61
+ }
62
+
63
+ export {
64
+ extractBulletPoints,
65
+ parseChangelog,
66
+ fetchChangelog
67
+ };
package/dist/client.d.ts CHANGED
@@ -6,4 +6,12 @@ declare module 'virtual:refresh-guard-changelog' {
6
6
  export const latestVersion: string | null
7
7
  /** Markdown body of that version's section (unprocessed), or '' if none/disabled. */
8
8
  export const latestContent: string
9
+ /** All parsed version entries from your changelog file in chronological order. */
10
+ export const allVersions: Array<{
11
+ version: string
12
+ date: string | null
13
+ content: string
14
+ }>
15
+ /** Configured static changelog URL when mode is 'fetch', or undefined */
16
+ export const changelogUrl: string | undefined
9
17
  }
@@ -0,0 +1,34 @@
1
+ export interface ChangelogVersionEntry {
2
+ /** 版本号,例如 "v1.5.0" 或 "1.5.0" */
3
+ version: string;
4
+ /** 发布日期,如 "2026-10-18";若未标明日期的版本块则为 null */
5
+ date: string | null;
6
+ /** 该版本块对应的 Markdown 正文(已剔除首行版本标题) */
7
+ content: string;
8
+ }
9
+ export interface ParsedChangelog {
10
+ /** 最新版本的版本号,如 "v1.5.0";无有效版本时为 null */
11
+ latestVersion: string | null;
12
+ /** 最新版本的正文 Markdown 内容 */
13
+ latestContent: string;
14
+ /** CHANGELOG 中按顺序解析的所有历史版本列表 */
15
+ allVersions: ChangelogVersionEntry[];
16
+ }
17
+ /**
18
+ * 提取 markdown 中的更新要点(bullet points),自动跳过分类标题,去除前缀符号
19
+ */
20
+ export declare function extractBulletPoints(content: string): string[];
21
+ /**
22
+ * 通用 CHANGELOG 解析函数(环境无关,可在 Node 构建期或浏览器运行时执行)
23
+ * 兼容以下所有主流 Keep a Changelog 标题写法:
24
+ * - `## v1.2.0 (2026-08-13)`
25
+ * - `## 1.2.0 (2026-08-13)`
26
+ * - `## [1.165.0] - 2026-10-18`
27
+ * - `## [v1.165.0] - 2026-10-18`
28
+ * - `## 1.2.0`
29
+ */
30
+ export declare function parseChangelog(markdown: string): ParsedChangelog;
31
+ /**
32
+ * 运行时拉取并解析 CHANGELOG 静态文件
33
+ */
34
+ export declare function fetchChangelog(url?: string, init?: RequestInit): Promise<ParsedChangelog>;
@@ -1,4 +1,7 @@
1
- import type { UpdateEvent, UpdateListener, VersionCheckerOptions, VersionInfo } from './types';
1
+ import type { UpdateEvent, UpdateListener, VersionCheckerOptions, VersionInfo, ParsedChangelog } from './types';
2
+ import { fetchChangelog, parseChangelog, extractBulletPoints } from './changelog';
3
+ export { fetchChangelog, parseChangelog, extractBulletPoints };
4
+ export type { ParsedChangelog, ChangelogVersionEntry } from './changelog';
2
5
  /**
3
6
  * Framework-agnostic engine: polls (or is told about) a new version, decides whether to refresh
4
7
  * based on `mode`, and guards against reload loops / stale-chunk white-screens. Vue/React
@@ -12,12 +15,20 @@ export declare class UpdateChecker {
12
15
  private listeners;
13
16
  private _hasUpdate;
14
17
  private _latestInfo;
18
+ private _changelog;
15
19
  private visibilityHandler;
16
20
  private chunkErrorHandler;
17
21
  /** @param currentVersion The version baked into *this* running build (e.g. `__APP_VERSION__` from your Vite define, or package.json version). */
18
22
  constructor(currentVersion: string, options?: VersionCheckerOptions);
19
23
  get hasUpdate(): boolean;
20
24
  get latestInfo(): VersionInfo | null;
25
+ get changelog(): ParsedChangelog | null;
26
+ /**
27
+ * 运行时拉取并解析 CHANGELOG 文件。
28
+ * 若配置了 `changelog: { mode: 'fetch', url: '...' }`,在发现新版本时会自动触发;
29
+ * 业务层也可主动调用此方法拉取完整历史日志列表。
30
+ */
31
+ fetchChangelog(customUrl?: string): Promise<ParsedChangelog>;
21
32
  start(): void;
22
33
  stop(): void;
23
34
  /** Fetch versionUrl now and react if it differs from the running build. Returns whether an update was found. */
@@ -11,6 +11,57 @@ export interface ChangelogInfo {
11
11
  /** Rendered body for that version's section (markdown, unprocessed) */
12
12
  content: string;
13
13
  }
14
+ export interface ChangelogVersionEntry {
15
+ /** 版本号,例如 "v1.5.0" 或 "1.5.0" */
16
+ version: string;
17
+ /** 发布日期,如 "2026-10-18";若未标明日期的版本块则为 null */
18
+ date: string | null;
19
+ /** 该版本块对应的 Markdown 正文(已剔除首行版本标题) */
20
+ content: string;
21
+ }
22
+ export interface ParsedChangelog {
23
+ /** 最新版本的版本号,如 "v1.5.0";无有效版本时为 null */
24
+ latestVersion: string | null;
25
+ /** 最新版本的正文 Markdown 内容 */
26
+ latestContent: string;
27
+ /** CHANGELOG 中按顺序解析的所有历史版本列表 */
28
+ allVersions: ChangelogVersionEntry[];
29
+ }
30
+ export interface ChangelogFetchOptions {
31
+ /** 模式:'fetch' 表示从远程 URL 拉取 changelog markdown 文件 */
32
+ mode?: 'bake' | 'fetch';
33
+ /** 运行时拉取的目标 URL。默认:'/CHANGELOG.md' */
34
+ url?: string;
35
+ }
36
+ export type ChangelogOption = string | boolean | ChangelogFetchOptions;
37
+ export interface UpdateCardProps {
38
+ /** 控制卡片显隐。默认:true */
39
+ visible?: boolean;
40
+ /** 显式版本号,如 "v1.2.0" */
41
+ version?: string | null;
42
+ /** 版本发布日期,如 "2026-10-18" */
43
+ date?: string | null;
44
+ /** 更新日志正文(Markdown 字符串)。若未显式指定 bulletPoints,将自动提炼其中的列表项 */
45
+ content?: string | null;
46
+ /** 手工指定的更新要点列表 */
47
+ bulletPoints?: string[];
48
+ /** 最多展示的 bullet 要点条数。默认:4 */
49
+ maxBullets?: number;
50
+ /** 卡片标题。默认:"✨ 新版本上线" */
51
+ title?: string;
52
+ /** "查看完整更新日志 / 查看更多" 的外链 URL 或跳转目标。若传入则显示查看更多链接 */
53
+ viewMoreUrl?: string;
54
+ /** "查看更多" 按钮或链接文案。默认:"查看完整更新日志" */
55
+ viewMoreText?: string;
56
+ /** "立即刷新" 按钮文案。默认:"立即刷新" */
57
+ refreshText?: string;
58
+ /** 是否允许关闭/暂不更新。默认:true */
59
+ closable?: boolean;
60
+ /** 卡片布局:'floating'(右下角浮动卡片)或 'inline'(流式嵌入)。默认:'floating' */
61
+ layout?: 'floating' | 'inline';
62
+ /** 显式指定深色/浅色外观。null/undefined 则跟随系统的 prefers-color-scheme */
63
+ dark?: boolean | null;
64
+ }
14
65
  export interface VersionCheckerOptions {
15
66
  /** Where to fetch version info from. Default: '/version.json' (see the Vite plugin, which emits this file at build time). */
16
67
  versionUrl?: string;
@@ -39,6 +90,13 @@ export interface VersionCheckerOptions {
39
90
  * dynamic-import rejection pattern. Default: true.
40
91
  */
41
92
  guardChunkErrors?: boolean;
93
+ /**
94
+ * Changelog configuration:
95
+ * - `{ mode: 'fetch', url: '/CHANGELOG.md' }`: fetch and parse changelog from static URL when an update is found
96
+ * - string: custom URL to fetch changelog from (shorthand for `{ mode: 'fetch', url: ... }`)
97
+ * - false: disable changelog handling
98
+ */
99
+ changelog?: ChangelogOption;
42
100
  /**
43
101
  * Called whenever a new version is first detected, before any built-in UI/refresh behavior runs.
44
102
  * Return `false` to suppress the built-in reaction entirely and drive your own UI instead —
@@ -48,5 +106,5 @@ export interface VersionCheckerOptions {
48
106
  /** Called immediately before the actual page refresh happens (any mode). Good place to flush analytics, etc. */
49
107
  onBeforeRefresh?: () => void;
50
108
  }
51
- export type UpdateEvent = 'update-available' | 'refreshing';
52
- export type UpdateListener = (info: VersionInfo | null) => void;
109
+ export type UpdateEvent = 'update-available' | 'refreshing' | 'changelog-loaded';
110
+ export type UpdateListener = (data: any) => void;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,17 @@
1
1
  import type { Plugin } from 'vite';
2
+ import { parseChangelog, extractBulletPoints, fetchChangelog, type ParsedChangelog, type ChangelogVersionEntry } from './core/changelog';
3
+ export { parseChangelog, extractBulletPoints, fetchChangelog };
4
+ export type { ParsedChangelog, ChangelogVersionEntry };
5
+ export interface ChangelogPluginOptions {
6
+ /** 模式:'bake'(默认:构建期解析并烘焙进 bundle)或 'fetch'(构建期复制文件并在运行时异步拉取) */
7
+ mode?: 'bake' | 'fetch';
8
+ /** 本地 CHANGELOG 文件路径(相对于项目 root)。默认:'CHANGELOG.md' */
9
+ file?: string;
10
+ /** 运行时或构建产物中 CHANGELOG 的文件名/路径。默认:'CHANGELOG.md' */
11
+ outFile?: string;
12
+ /** 运行时拉取的目标 URL。默认:'/CHANGELOG.md' */
13
+ url?: string;
14
+ }
2
15
  export interface RefreshGuardPluginOptions {
3
16
  /** Version string to bake into version.json and the `__REFRESH_GUARD_VERSION__` define. Default: read from the project's package.json. */
4
17
  version?: string;
@@ -7,21 +20,17 @@ export interface RefreshGuardPluginOptions {
7
20
  /** Filename for the emitted version manifest, relative to the build output dir. Default: 'version.json'. */
8
21
  outFile?: string;
9
22
  /**
10
- * Path (relative to project root) to a changelog file to expose via `import { latestVersion, latestContent } from 'virtual:refresh-guard-changelog'`.
11
- * Expects `## vX.Y.Z (date)` section headings, same format as Keep a Changelog. Default: 'CHANGELOG.md'. Set to `false` to disable the virtual module entirely.
23
+ * Path (relative to project root) to a changelog file to expose via `import { latestVersion, latestContent, allVersions } from 'virtual:refresh-guard-changelog'`.
24
+ * Expects `## vX.Y.Z (date)` or `## [X.Y.Z] - date` section headings, standard Keep a Changelog.
25
+ * Default: 'CHANGELOG.md'. Set to `false` to disable the virtual module entirely.
26
+ * Can also be an object: `{ mode: 'fetch', url: '/CHANGELOG.md' }` for runtime fetching.
12
27
  */
13
- changelog?: string | false;
28
+ changelog?: string | false | ChangelogPluginOptions;
14
29
  }
15
30
  /**
16
- * 读取 CHANGELOG 最新版本的版本号与正文(导出供测试复用;接入方不需要直接用)。
31
+ * 读取并解析 CHANGELOG(返回最新版本号、最新正文及所有历史版本列表)。
17
32
  */
18
- export declare function readChangelog(root: string, changelogOption: string | false | undefined): {
19
- latestVersion: null;
20
- latestContent: string;
21
- } | {
22
- latestVersion: string;
23
- latestContent: string;
24
- };
33
+ export declare function readChangelog(root: string, changelogOption: string | false | ChangelogPluginOptions | undefined): ParsedChangelog;
25
34
  /**
26
35
  * Vite plugin half of refresh-guard: bakes the current build's version into your bundle
27
36
  * (as `__REFRESH_GUARD_VERSION__`) and emits a `version.json` manifest that the runtime
package/dist/index.js CHANGED
@@ -1,3 +1,9 @@
1
+ import {
2
+ extractBulletPoints,
3
+ fetchChangelog,
4
+ parseChangelog
5
+ } from "./chunk-JLHX4WLS.js";
6
+
1
7
  // src/index.ts
2
8
  import { execSync } from "child_process";
3
9
  import { existsSync, readFileSync } from "fs";
@@ -5,15 +11,14 @@ import { resolve } from "path";
5
11
  var VIRTUAL_ID = "virtual:refresh-guard-changelog";
6
12
  var RESOLVED_VIRTUAL_ID = "\0" + VIRTUAL_ID;
7
13
  function readChangelog(root, changelogOption) {
8
- if (changelogOption === false) return { latestVersion: null, latestContent: "" };
9
- const path = resolve(root, changelogOption || "CHANGELOG.md");
10
- if (!existsSync(path)) return { latestVersion: null, latestContent: "" };
14
+ if (changelogOption === false) {
15
+ return { latestVersion: null, latestContent: "", allVersions: [] };
16
+ }
17
+ const relPath = typeof changelogOption === "string" ? changelogOption : typeof changelogOption === "object" && changelogOption.file ? changelogOption.file : "CHANGELOG.md";
18
+ const path = resolve(root, relPath);
19
+ if (!existsSync(path)) return { latestVersion: null, latestContent: "", allVersions: [] };
11
20
  const md = readFileSync(path, "utf-8");
12
- const heading = md.match(/^##\s+(v?[\d.]+)/m);
13
- if (!heading) return { latestVersion: null, latestContent: "" };
14
- const sections = md.split(/^## /m);
15
- const body = sections.length > 1 ? sections[1].replace(/^v?[\d.]+\s*(?:\(.*?\))?\s*\n?/, "").trim() : "";
16
- return { latestVersion: heading[1], latestContent: body };
21
+ return parseChangelog(md);
17
22
  }
18
23
  function refreshGuard(options = {}) {
19
24
  let config;
@@ -40,7 +45,8 @@ function refreshGuard(options = {}) {
40
45
  },
41
46
  configResolved(resolvedConfig) {
42
47
  config = resolvedConfig;
43
- changelogPath = options.changelog === false ? "" : resolve(config.root, options.changelog || "CHANGELOG.md");
48
+ const relFile = typeof options.changelog === "string" ? options.changelog : typeof options.changelog === "object" && options.changelog?.file ? options.changelog.file : "CHANGELOG.md";
49
+ changelogPath = options.changelog === false ? "" : resolve(config.root, relFile);
44
50
  if (options.includeCommit !== false) {
45
51
  try {
46
52
  commit = execSync("git rev-parse --short HEAD", { cwd: config.root, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
@@ -55,9 +61,12 @@ function refreshGuard(options = {}) {
55
61
  load(id) {
56
62
  if (id !== RESOLVED_VIRTUAL_ID) return;
57
63
  if (changelogPath) this.addWatchFile(changelogPath);
58
- const { latestVersion, latestContent } = readChangelog(config.root, options.changelog);
64
+ const { latestVersion, latestContent, allVersions } = readChangelog(config.root, options.changelog);
65
+ const changelogUrl = typeof options.changelog === "object" && options.changelog !== null ? options.changelog.url || "/" + (options.changelog.outFile || "CHANGELOG.md") : void 0;
59
66
  return `export const latestVersion = ${JSON.stringify(latestVersion)};
60
67
  export const latestContent = ${JSON.stringify(latestContent)};
68
+ export const allVersions = ${JSON.stringify(allVersions)};
69
+ export const changelogUrl = ${JSON.stringify(changelogUrl)};
61
70
  `;
62
71
  },
63
72
  /**
@@ -98,12 +107,22 @@ export const latestContent = ${JSON.stringify(latestContent)};
98
107
  fileName: options.outFile || "version.json",
99
108
  source: JSON.stringify(manifest, null, 2)
100
109
  });
110
+ if (typeof options.changelog === "object" && options.changelog !== null && options.changelog.mode === "fetch" && changelogPath && existsSync(changelogPath)) {
111
+ this.emitFile({
112
+ type: "asset",
113
+ fileName: options.changelog.outFile || "CHANGELOG.md",
114
+ source: readFileSync(changelogPath, "utf-8")
115
+ });
116
+ }
101
117
  }
102
118
  };
103
119
  }
104
120
  var index_default = refreshGuard;
105
121
  export {
106
122
  index_default as default,
123
+ extractBulletPoints,
124
+ fetchChangelog,
125
+ parseChangelog,
107
126
  readChangelog,
108
127
  refreshGuard
109
128
  };