@tnotesjs/core 0.2.0 → 0.2.2

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.
Files changed (67) hide show
  1. package/config/ConfigManager.ts +137 -0
  2. package/config/constants.ts +121 -0
  3. package/config/index.ts +25 -0
  4. package/config/templates.ts +49 -0
  5. package/core/GitManager.ts +513 -0
  6. package/core/NoteIndexCache.ts +194 -0
  7. package/core/NoteManager.ts +407 -0
  8. package/core/ProcessManager.ts +180 -0
  9. package/core/ReadmeGenerator.ts +215 -0
  10. package/core/TocGenerator.ts +212 -0
  11. package/core/index.ts +11 -0
  12. package/dist/chunk-5QN44ES5.js +6050 -0
  13. package/dist/chunk-5Y5IYS6C.js +200 -0
  14. package/dist/cli/index.js +986 -0
  15. package/dist/index.js +8 -0
  16. package/dist/vitepress/config/index.js +1686 -0
  17. package/package.json +6 -2
  18. package/services/file-watcher/configChangeHandler.ts +64 -0
  19. package/services/file-watcher/eventScheduler.ts +179 -0
  20. package/services/file-watcher/folderChangeHandler.ts +325 -0
  21. package/services/file-watcher/fsWatcherAdapter.ts +128 -0
  22. package/services/file-watcher/globalUpdateCoordinator.ts +60 -0
  23. package/services/file-watcher/index.ts +7 -0
  24. package/services/file-watcher/internal.ts +79 -0
  25. package/services/file-watcher/readmeChangeHandler.ts +28 -0
  26. package/services/file-watcher/renameDetector.ts +120 -0
  27. package/services/file-watcher/service.ts +352 -0
  28. package/services/file-watcher/watchState.ts +194 -0
  29. package/services/git/index.ts +7 -0
  30. package/services/git/service.ts +114 -0
  31. package/services/index.ts +15 -0
  32. package/services/init-sub-repo/index.ts +2 -0
  33. package/services/init-sub-repo/initSubRepoLogic.test.ts +162 -0
  34. package/services/init-sub-repo/initSubRepoLogic.ts +304 -0
  35. package/services/init-sub-repo/service.ts +101 -0
  36. package/services/note/index.ts +7 -0
  37. package/services/note/service.ts +362 -0
  38. package/services/readme/index.ts +7 -0
  39. package/services/readme/service.ts +761 -0
  40. package/services/timestamp/index.ts +7 -0
  41. package/services/timestamp/service.ts +465 -0
  42. package/services/toc/index.ts +5 -0
  43. package/services/toc/moveTocInside.test.ts +73 -0
  44. package/services/toc/service.ts +759 -0
  45. package/services/vitepress/index.ts +7 -0
  46. package/services/vitepress/service.ts +339 -0
  47. package/utils/errorHandler.ts +174 -0
  48. package/utils/file.ts +17 -0
  49. package/utils/genHierarchicalSidebar.ts +69 -0
  50. package/utils/generateAnchor.ts +24 -0
  51. package/utils/getChangedIds.ts +35 -0
  52. package/utils/index.ts +71 -0
  53. package/utils/logger.ts +231 -0
  54. package/utils/markdown.ts +75 -0
  55. package/utils/migrateReadmeToToc.test.ts +111 -0
  56. package/utils/migrateReadmeToToc.ts +135 -0
  57. package/utils/parseArgs.ts +90 -0
  58. package/utils/parseReadmeCompletedNotes.test.ts +90 -0
  59. package/utils/parseReadmeCompletedNotes.ts +108 -0
  60. package/utils/portUtils.ts +113 -0
  61. package/utils/readmeHelpers.ts +190 -0
  62. package/utils/runCommand.ts +29 -0
  63. package/utils/tocHelpers.test.ts +278 -0
  64. package/utils/tocHelpers.ts +855 -0
  65. package/utils/tocNodeId.test.ts +60 -0
  66. package/utils/tocNodeId.ts +97 -0
  67. package/utils/validators.ts +102 -0
@@ -0,0 +1,1686 @@
1
+ import {
2
+ FileWatcherService,
3
+ NoteIndexCache,
4
+ NoteService,
5
+ RenameNoteCommand,
6
+ TocService,
7
+ UpdateNoteConfigCommand,
8
+ generateAnchor,
9
+ logger
10
+ } from "../../chunk-5QN44ES5.js";
11
+ import {
12
+ ConfigManager
13
+ } from "../../chunk-5Y5IYS6C.js";
14
+
15
+ // vitepress/config/index.ts
16
+ import fs3 from "fs";
17
+ import path5 from "path";
18
+ import { defineConfig } from "vitepress";
19
+
20
+ // vitepress/configs/constants.ts
21
+ function getIgnoreList(config) {
22
+ return [...config.ignore_dirs.map((dir) => `**/${dir}/**`)];
23
+ }
24
+ function getGithubPageUrl(config) {
25
+ return "https://" + config.author.toLowerCase() + ".github.io/" + config.repoName + "/";
26
+ }
27
+
28
+ // vitepress/configs/head.config.ts
29
+ function getHeadConfig(config, githubPageUrl) {
30
+ const head = [
31
+ [
32
+ "meta",
33
+ {
34
+ name: "keywords",
35
+ content: config.keywords.join(", ")
36
+ }
37
+ ],
38
+ ["meta", { name: "author", content: config.author }],
39
+ ["link", { rel: "canonical", href: githubPageUrl }],
40
+ ["link", { rel: "icon", href: githubPageUrl + "favicon.ico" }],
41
+ ["link", { rel: "preconnect", href: "https://fonts.googleapis.com" }]
42
+ ];
43
+ return head;
44
+ }
45
+
46
+ // vitepress/configs/markdown.config.ts
47
+ import fs from "fs";
48
+ import markdownItContainer from "markdown-it-container";
49
+ import mila from "markdown-it-link-attributes";
50
+ import markdownItTaskLists from "markdown-it-task-lists";
51
+ import path from "path";
52
+ function esc(s = "") {
53
+ return s.replace(
54
+ /[&<>"']/g,
55
+ (ch) => ({
56
+ "&": "&amp;",
57
+ "<": "&lt;",
58
+ ">": "&gt;",
59
+ '"': "&quot;",
60
+ "'": "&#39;"
61
+ })[ch]
62
+ );
63
+ }
64
+ var simpleMermaidMarkdown = (md) => {
65
+ const fence = md.renderer.rules.fence ? md.renderer.rules.fence.bind(md.renderer.rules) : () => "";
66
+ md.renderer.rules.fence = (tokens, index, options, env, slf) => {
67
+ const token = tokens[index];
68
+ if (token.info.trim() === "mermaid") {
69
+ try {
70
+ const key = `mermaid-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
71
+ const content = token.content;
72
+ return `<Mermaid id="${key}" graph="${encodeURIComponent(content)}" />`;
73
+ } catch (err) {
74
+ return `<pre>${err}</pre>`;
75
+ }
76
+ }
77
+ if (token.info.trim() === "mmd") {
78
+ tokens[index].info = "mermaid";
79
+ }
80
+ return fence(tokens, index, options, env, slf);
81
+ };
82
+ };
83
+ function configureMarkMapContainer(md) {
84
+ md.use(markdownItContainer, "markmap", {
85
+ marker: "`",
86
+ validate(params) {
87
+ const p = (params || "").trim();
88
+ return p.startsWith("markmap");
89
+ },
90
+ render() {
91
+ return "";
92
+ }
93
+ });
94
+ md.core.ruler.after("block", "tn_replace_markmap_container", (state) => {
95
+ const src = state.env.source || "";
96
+ const lines = src.split("\n");
97
+ const tokens = state.tokens;
98
+ for (let i = 0; i < tokens.length; i++) {
99
+ const t = tokens[i];
100
+ if (t.type === "container_markmap_open") {
101
+ let j = i + 1;
102
+ while (j < tokens.length && tokens[j].type !== "container_markmap_close")
103
+ j++;
104
+ if (j >= tokens.length) continue;
105
+ const open = t;
106
+ const startLine = open.map ? open.map[0] + 1 : null;
107
+ const endLine = open.map ? open.map[1] - 1 : null;
108
+ const params = {};
109
+ if (open.map && typeof open.map[0] === "number") {
110
+ const openLine = (lines[open.map[0]] || "").trim();
111
+ let paramPart = "";
112
+ const braceMatch = openLine.match(/\{([^}]*)\}/);
113
+ if (braceMatch) {
114
+ paramPart = braceMatch[1].trim();
115
+ } else {
116
+ const after = openLine.replace(/^`+\s*/, "");
117
+ if (after.startsWith("markmap")) {
118
+ paramPart = after.slice("markmap".length).trim();
119
+ }
120
+ }
121
+ if (paramPart) {
122
+ const tokenArr = paramPart.match(/"[^"]*"|'[^']*'|\S+/g) || [];
123
+ let startIdx = 0;
124
+ if (tokenArr.length > 0 && /^\d+$/.test(tokenArr[0])) {
125
+ params.initialExpandLevel = Number(tokenArr[0]);
126
+ startIdx = 1;
127
+ }
128
+ for (let k = startIdx; k < tokenArr.length; k++) {
129
+ const pair = tokenArr[k];
130
+ if (!pair) continue;
131
+ const m = pair.match(/^([^=:\s]+)\s*(=|:)\s*(.+)$/);
132
+ if (m) {
133
+ const key = m[1];
134
+ let val = m[3];
135
+ if (/^".*"$/.test(val) && val.length >= 2 || /^'.*'$/.test(val) && val.length >= 2) {
136
+ val = val.slice(1, -1);
137
+ } else if (/^\d+$/.test(val)) {
138
+ val = String(Number(val));
139
+ }
140
+ params[key] = val;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ let content = "";
146
+ if (startLine !== null && endLine !== null) {
147
+ for (let k = startLine; k <= endLine && k < lines.length; k++) {
148
+ content += lines[k] + "\n";
149
+ }
150
+ } else {
151
+ for (let k = i + 1; k < j; k++) {
152
+ content += tokens[k].content || "";
153
+ }
154
+ }
155
+ const firstNonEmptyLine = (content || "").split("\n").find((ln) => ln.trim() !== "") || "";
156
+ const refMatch = firstNonEmptyLine.trim().match(/^<<<\s*(.+)$/);
157
+ if (refMatch) {
158
+ const refRaw = refMatch[1].trim().replace(/^['"]|['"]$/g, "");
159
+ try {
160
+ const env = state.env || {};
161
+ const possibleRel = env.relativePath || env.path || env.filePath || env.file || "";
162
+ let refFullPath = refRaw;
163
+ if (!path.isAbsolute(refRaw)) {
164
+ if (possibleRel) {
165
+ const currentDir = path.dirname(possibleRel);
166
+ refFullPath = path.resolve(process.cwd(), currentDir, refRaw);
167
+ } else {
168
+ refFullPath = path.resolve(process.cwd(), refRaw);
169
+ }
170
+ } else {
171
+ refFullPath = refRaw;
172
+ }
173
+ const fileContent = fs.readFileSync(refFullPath, "utf-8");
174
+ content = fileContent;
175
+ } catch (err) {
176
+ const errorMsg = err instanceof Error ? err.message : String(err);
177
+ content = `Failed to load referenced file: ${esc(
178
+ String(refRaw)
179
+ )}
180
+
181
+ Error: ${esc(errorMsg)}`;
182
+ }
183
+ }
184
+ const encodedContent = encodeURIComponent(content.trim());
185
+ let propsStr = `content="${encodedContent}"`;
186
+ for (const [k, v] of Object.entries(params)) {
187
+ if (typeof v === "number" || /^\d+$/.test(String(v))) {
188
+ propsStr += ` :${k}="${v}"`;
189
+ } else {
190
+ const safe = String(v).replace(/"/g, "&quot;");
191
+ propsStr += ` ${k}="${safe}"`;
192
+ }
193
+ }
194
+ const html = `<MarkMap ${propsStr}></MarkMap>
195
+ `;
196
+ const htmlToken = new state.Token("html_block", "", 0);
197
+ htmlToken.content = html;
198
+ tokens.splice(i, j - i + 1, htmlToken);
199
+ }
200
+ }
201
+ return true;
202
+ });
203
+ }
204
+ function configureSwiperContainer(md) {
205
+ let __tn_swiper_uid = 0;
206
+ let __tn_rules_stack = [];
207
+ md.core.ruler.before("block", "tn_swiper_reset_uid", () => {
208
+ __tn_swiper_uid = 0;
209
+ __tn_rules_stack = [];
210
+ return true;
211
+ });
212
+ md.use(markdownItContainer, "swiper", {
213
+ render: (tokens, idx) => {
214
+ if (tokens[idx].nesting === 1) {
215
+ __tn_rules_stack.push({
216
+ image: md.renderer.rules.image,
217
+ pOpen: md.renderer.rules.paragraph_open,
218
+ pClose: md.renderer.rules.paragraph_close
219
+ });
220
+ md.renderer.rules.paragraph_open = () => "";
221
+ md.renderer.rules.paragraph_close = () => "";
222
+ md.renderer.rules.image = (tokens2, i) => {
223
+ const token = tokens2[i];
224
+ const src = token.attrGet("src") || "";
225
+ const alt = token.content || "";
226
+ const title = alt && alt.trim() ? alt : "img";
227
+ return `<div class="swiper-slide" data-title="${esc(
228
+ title
229
+ )}"><img src="${esc(src)}" alt="${esc(alt)}"></div>`;
230
+ };
231
+ const id = `tn-swiper-${++__tn_swiper_uid}`;
232
+ return `
233
+ <div class="tn-swiper" data-swiper-id="${id}">
234
+ <div class="tn-swiper-tabs"></div>
235
+ <div class="swiper-container">
236
+ <div class="swiper-wrapper">
237
+ `;
238
+ } else {
239
+ const prev = __tn_rules_stack.pop() || {
240
+ image: null,
241
+ pOpen: null,
242
+ pClose: null
243
+ };
244
+ md.renderer.rules.image = prev.image;
245
+ md.renderer.rules.paragraph_open = prev.pOpen;
246
+ md.renderer.rules.paragraph_close = prev.pClose;
247
+ return `
248
+ </div>
249
+ <!-- \u4E0B\u4E00\u9875\u6309\u94AE -->
250
+ <!-- <div class="swiper-button-next"></div> -->
251
+ <!-- \u4E0A\u4E00\u9875\u6309\u94AE -->
252
+ <!-- <div class="swiper-button-prev"></div> -->
253
+ <!-- \u5206\u9875\u5BFC\u822A -->
254
+ <!-- <div class="swiper-pagination"></div> -->
255
+ </div>
256
+ </div>
257
+ `;
258
+ }
259
+ }
260
+ });
261
+ }
262
+ function getMarkdownConfig() {
263
+ const markdown = {
264
+ lineNumbers: true,
265
+ math: true,
266
+ config(md) {
267
+ md.core.ruler.before("normalize", "save-source", (state) => {
268
+ state.env.source = state.src;
269
+ return true;
270
+ });
271
+ simpleMermaidMarkdown(md);
272
+ configureMarkMapContainer(md);
273
+ md.use(markdownItTaskLists);
274
+ md.use(mila, {
275
+ attrs: {
276
+ target: "_self",
277
+ rel: "noopener"
278
+ }
279
+ });
280
+ configureSwiperContainer(md);
281
+ },
282
+ anchor: {
283
+ slugify: generateAnchor
284
+ },
285
+ image: {
286
+ lazyLoading: true
287
+ }
288
+ };
289
+ return markdown;
290
+ }
291
+
292
+ // vitepress/configs/theme.config.ts
293
+ function getThemeConfig(config) {
294
+ const themeConfig = {
295
+ docFooter: {
296
+ prev: "\u4E0A\u4E00\u7BC7",
297
+ next: "\u4E0B\u4E00\u7BC7"
298
+ },
299
+ externalLinkIcon: true,
300
+ outline: {
301
+ level: [2, 3],
302
+ label: "\u76EE\u5F55"
303
+ },
304
+ nav: [
305
+ {
306
+ text: "\u{1F440} README",
307
+ link: "/README"
308
+ },
309
+ {
310
+ text: "Menus",
311
+ items: config.menuItems
312
+ }
313
+ ],
314
+ search: {
315
+ // 使用本地搜索(不依赖远程服务器)
316
+ provider: "local",
317
+ options: {
318
+ miniSearch: {
319
+ /**
320
+ * 控制如何对文档进行分词、字段提取等预处理
321
+ * @type {Pick<import('minisearch').Options, 'extractField' | 'tokenize' | 'processTerm'>}
322
+ */
323
+ options: {
324
+ // 自定义分词逻辑
325
+ tokenize: (text, language) => {
326
+ if (language === "zh") {
327
+ return text.match(/[\u4e00-\u9fa5]+|\S+/g) || [];
328
+ }
329
+ return text.split(/\s+/);
330
+ },
331
+ // 将所有词转为小写,确保大小写不敏感匹配
332
+ processTerm: (term) => term.toLowerCase()
333
+ },
334
+ /**
335
+ * 控制搜索时的行为(如模糊匹配、权重)
336
+ * @type {import('minisearch').SearchOptions}
337
+ * @default
338
+ * { fuzzy: 0.2, prefix: true, boost: { title: 4, text: 2, titles: 1 } }
339
+ */
340
+ searchOptions: {
341
+ fuzzy: 0.2,
342
+ // 模糊匹配阈值(0-1),允许拼写错误的阈值(数值越低越严格)
343
+ prefix: true,
344
+ // 是否启用前缀匹配(输入"jav"可匹配"javascript")
345
+ boost: {
346
+ title: 10,
347
+ // 文件名作为 h1 标题,权重最高
348
+ headings: 5,
349
+ // h2 - h6
350
+ text: 3,
351
+ // 正文内容索引
352
+ code: 1
353
+ // 代码块索引权重
354
+ }
355
+ }
356
+ },
357
+ /**
358
+ * 控制哪些 Markdown 内容参与本地搜索引擎索引
359
+ * @param {string} src 当前 Markdown 文件的原始内容(即 .md 文件中的文本)
360
+ * @param {import('vitepress').MarkdownEnv} env 包含当前页面环境信息的对象,比如 frontmatter、路径等
361
+ * @param {import('markdown-it-async')} md 一个 Markdown 渲染器实例,用来将 Markdown 转换为 HTML
362
+ */
363
+ async _render(src, env, md) {
364
+ const filePath = env.relativePath;
365
+ if (filePath.includes("TOC.md")) return "";
366
+ const notesIndex = filePath.indexOf("notes/");
367
+ let folderName = "";
368
+ if (notesIndex !== -1) {
369
+ const pathAfterNotes = filePath.slice(notesIndex + "notes/".length);
370
+ folderName = pathAfterNotes.split("/")[0];
371
+ }
372
+ const titleField = `# ${folderName}
373
+ `;
374
+ const html = md.render(titleField + "\n\n" + src, env);
375
+ return html;
376
+ }
377
+ }
378
+ },
379
+ // VitePress 只有 sidebar 非空才会渲染 sidebar 插槽,自定义侧边栏依赖这个外壳。
380
+ sidebar: [
381
+ {
382
+ text: "",
383
+ items: []
384
+ }
385
+ ],
386
+ socialLinks: config.socialLinks
387
+ };
388
+ return themeConfig;
389
+ }
390
+
391
+ // vitepress/plugins/buildProgressPlugin.ts
392
+ import {
393
+ existsSync,
394
+ readFileSync,
395
+ writeFileSync,
396
+ mkdirSync
397
+ } from "fs";
398
+ import { join } from "path";
399
+ var CACHE_DIR = join(process.cwd(), "node_modules", ".tnotes-progress");
400
+ var CACHE_FILE = join(CACHE_DIR, "build-cache.json");
401
+ function getCacheData() {
402
+ try {
403
+ if (existsSync(CACHE_FILE)) {
404
+ return JSON.parse(readFileSync(CACHE_FILE, "utf-8"));
405
+ }
406
+ } catch {
407
+ }
408
+ return { transformCount: 0, chunkCount: 0 };
409
+ }
410
+ function setCacheData(data) {
411
+ try {
412
+ if (!existsSync(CACHE_DIR)) {
413
+ mkdirSync(CACHE_DIR, { recursive: true });
414
+ }
415
+ writeFileSync(CACHE_FILE, JSON.stringify(data), "utf-8");
416
+ } catch {
417
+ }
418
+ }
419
+ var globalStartTime = 0;
420
+ var globalTransformCount = 0;
421
+ var globalChunkCount = 0;
422
+ var globalHasError = false;
423
+ var globalIsBuilding = false;
424
+ var globalOutDir = "";
425
+ var globalLastPercent = 0;
426
+ var globalLastLoggedPercent = -1;
427
+ var globalLastOutputTime = 0;
428
+ var globalTransformEndTime = 0;
429
+ var globalLastHookTime = 0;
430
+ var globalStallTimer = null;
431
+ var isTTY = !!(process.stdout.isTTY && process.stderr.isTTY);
432
+ var isCI = !!(process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.CIRCLECI || process.env.TRAVIS || process.env.JENKINS_URL);
433
+ var useSingleLineMode = isTTY && !isCI;
434
+ var originalStdoutWrite = null;
435
+ var originalStderrWrite = null;
436
+ function interceptOutput() {
437
+ if (originalStdoutWrite) return;
438
+ originalStdoutWrite = process.stdout.write.bind(process.stdout);
439
+ originalStderrWrite = process.stderr.write.bind(process.stderr);
440
+ const filter = (chunk) => {
441
+ const str = chunk.toString();
442
+ return str.includes("\u{1F528}") || str.includes("\u2705 \u6784\u5EFA\u6210\u529F") || str.includes("\u274C \u6784\u5EFA\u5931\u8D25") || str.includes("\u{1F4C1}") || str.includes("\u{1F4CA}") || str.includes("\u{1F4E6}") || str.includes("\u23F1\uFE0F") || str.includes("\x1B[2K");
443
+ };
444
+ process.stdout.write = ((chunk, encodingOrCallback, callback) => {
445
+ if (filter(chunk)) {
446
+ return originalStdoutWrite(chunk, encodingOrCallback, callback);
447
+ }
448
+ if (typeof encodingOrCallback === "function") encodingOrCallback();
449
+ else if (callback) callback();
450
+ return true;
451
+ });
452
+ process.stderr.write = ((chunk, encodingOrCallback, callback) => {
453
+ const str = chunk.toString();
454
+ if (filter(chunk) || str.toLowerCase().includes("error")) {
455
+ return originalStderrWrite(chunk, encodingOrCallback, callback);
456
+ }
457
+ if (typeof encodingOrCallback === "function") encodingOrCallback();
458
+ else if (callback) callback();
459
+ return true;
460
+ });
461
+ }
462
+ function restoreOutput() {
463
+ if (originalStdoutWrite) {
464
+ process.stdout.write = originalStdoutWrite;
465
+ originalStdoutWrite = null;
466
+ }
467
+ if (originalStderrWrite) {
468
+ process.stderr.write = originalStderrWrite;
469
+ originalStderrWrite = null;
470
+ }
471
+ }
472
+ function renderProgress(percent, transforms, chunks, width, complete, incomplete, isFinal = false) {
473
+ if (!originalStderrWrite) return;
474
+ if (!useSingleLineMode && !isFinal) {
475
+ const currentPercent = Math.floor(percent * 100);
476
+ const currentBucket = Math.floor(currentPercent / 10) * 10;
477
+ const now = Date.now();
478
+ if (currentBucket <= globalLastLoggedPercent || now - globalLastOutputTime < 500) {
479
+ return;
480
+ }
481
+ globalLastLoggedPercent = currentBucket;
482
+ globalLastOutputTime = now;
483
+ }
484
+ const filled = Math.floor(percent * width);
485
+ const empty = width - filled;
486
+ const bar = complete.repeat(filled) + incomplete.repeat(empty);
487
+ const percentStr = (percent * 100).toFixed(0).padStart(3, " ");
488
+ const elapsed = ((Date.now() - globalStartTime) / 1e3).toFixed(1);
489
+ const prefix = useSingleLineMode ? "\r\x1B[2K" : "";
490
+ const ending = isFinal || !useSingleLineMode ? "\n" : "";
491
+ const line = `${prefix}Building [${bar}] ${percentStr}% | Transforms: ${transforms} | Chunks: ${chunks} | Time: ${elapsed}s${ending}`;
492
+ originalStderrWrite(line);
493
+ }
494
+ function buildProgressPlugin(options = {}) {
495
+ const { width = 40, complete = "\u2588", incomplete = "\u2591" } = options;
496
+ const cache = getCacheData();
497
+ const hasCache = cache.transformCount > 0;
498
+ return {
499
+ name: "tnotes-build-progress",
500
+ enforce: "pre",
501
+ apply: "build",
502
+ config(config, { command }) {
503
+ if (command === "build") {
504
+ config.logLevel = "silent";
505
+ if (!globalIsBuilding) {
506
+ globalIsBuilding = true;
507
+ globalStartTime = Date.now();
508
+ globalTransformCount = 0;
509
+ globalChunkCount = 0;
510
+ globalHasError = false;
511
+ globalLastPercent = 0;
512
+ globalLastLoggedPercent = -1;
513
+ globalLastOutputTime = 0;
514
+ globalTransformEndTime = 0;
515
+ globalLastHookTime = Date.now();
516
+ globalOutDir = config.build?.outDir || "dist";
517
+ interceptOutput();
518
+ globalStallTimer = setInterval(() => {
519
+ if (!globalIsBuilding || globalLastPercent <= 0 || globalLastPercent >= 0.98)
520
+ return;
521
+ const now = Date.now();
522
+ if (now - globalLastHookTime < 2e3) return;
523
+ const remaining = 0.98 - globalLastPercent;
524
+ globalLastPercent += remaining * 0.02;
525
+ const transformsStr = hasCache ? `${globalTransformCount}/${cache.transformCount * 2}` : `${globalTransformCount}`;
526
+ const chunksStr = hasCache ? `${globalChunkCount}/${cache.chunkCount * 2}` : `${globalChunkCount}`;
527
+ renderProgress(
528
+ globalLastPercent,
529
+ transformsStr,
530
+ chunksStr,
531
+ width,
532
+ complete,
533
+ incomplete
534
+ );
535
+ }, 1e3);
536
+ }
537
+ }
538
+ },
539
+ transform(_code, _id) {
540
+ globalTransformCount++;
541
+ globalLastHookTime = Date.now();
542
+ const transformWeight = hasCache && cache.transformEndRatio != null ? Math.max(0.1, Math.min(0.85, cache.transformEndRatio * 0.98)) : 0.85;
543
+ if (hasCache) {
544
+ const totalTransforms = cache.transformCount * 2;
545
+ globalLastPercent = Math.min(
546
+ transformWeight,
547
+ globalTransformCount / totalTransforms * transformWeight
548
+ );
549
+ } else {
550
+ const k = 500;
551
+ globalLastPercent = Math.min(
552
+ transformWeight,
553
+ transformWeight * globalTransformCount / (globalTransformCount + k)
554
+ );
555
+ }
556
+ const transformsStr = hasCache ? `${globalTransformCount}/${cache.transformCount * 2}` : `${globalTransformCount}`;
557
+ const chunksStr = hasCache ? `${globalChunkCount}/${cache.chunkCount * 2}` : `${globalChunkCount}`;
558
+ renderProgress(
559
+ globalLastPercent,
560
+ transformsStr,
561
+ chunksStr,
562
+ width,
563
+ complete,
564
+ incomplete
565
+ );
566
+ return null;
567
+ },
568
+ renderChunk() {
569
+ globalChunkCount++;
570
+ globalLastHookTime = Date.now();
571
+ if (!globalTransformEndTime) {
572
+ globalTransformEndTime = Date.now();
573
+ }
574
+ const transformWeight = hasCache && cache.transformEndRatio != null ? Math.max(0.1, Math.min(0.85, cache.transformEndRatio * 0.98)) : 0.85;
575
+ const chunkWeight = 0.98 - transformWeight;
576
+ if (hasCache) {
577
+ const totalChunks = cache.chunkCount * 2;
578
+ globalLastPercent = Math.min(
579
+ 0.98,
580
+ transformWeight + globalChunkCount / totalChunks * chunkWeight
581
+ );
582
+ } else {
583
+ globalLastPercent = Math.max(globalLastPercent, transformWeight);
584
+ globalLastPercent = Math.min(0.98, globalLastPercent + 5e-5);
585
+ }
586
+ const transformsStr = hasCache ? `${globalTransformCount}/${cache.transformCount * 2}` : `${globalTransformCount}`;
587
+ const chunksStr = hasCache ? `${globalChunkCount}/${cache.chunkCount * 2}` : `${globalChunkCount}`;
588
+ renderProgress(
589
+ globalLastPercent,
590
+ transformsStr,
591
+ chunksStr,
592
+ width,
593
+ complete,
594
+ incomplete
595
+ );
596
+ return null;
597
+ },
598
+ buildEnd(err) {
599
+ if (err) {
600
+ globalHasError = true;
601
+ }
602
+ },
603
+ closeBundle() {
604
+ setTimeout(() => {
605
+ if (!globalIsBuilding) return;
606
+ if (globalStallTimer) {
607
+ clearInterval(globalStallTimer);
608
+ globalStallTimer = null;
609
+ }
610
+ const elapsed = ((Date.now() - globalStartTime) / 1e3).toFixed(1);
611
+ const totalTransforms = hasCache ? cache.transformCount * 2 : globalTransformCount;
612
+ const totalChunks = hasCache ? cache.chunkCount * 2 : globalChunkCount;
613
+ const transformsStr = `${totalTransforms}/${totalTransforms}`;
614
+ const chunksStr = `${totalChunks}/${totalChunks}`;
615
+ renderProgress(
616
+ 1,
617
+ transformsStr,
618
+ chunksStr,
619
+ width,
620
+ complete,
621
+ incomplete,
622
+ true
623
+ );
624
+ restoreOutput();
625
+ if (!globalHasError) {
626
+ const totalTime = Date.now() - globalStartTime;
627
+ const transformTime = globalTransformEndTime ? globalTransformEndTime - globalStartTime : totalTime;
628
+ setCacheData({
629
+ transformCount: Math.floor(globalTransformCount / 2),
630
+ chunkCount: Math.floor(globalChunkCount / 2),
631
+ transformEndRatio: transformTime / totalTime
632
+ });
633
+ console.log(`\u{1F528} Rollup \u6253\u5305\u5B8C\u6210`);
634
+ console.log(` \u{1F4C1} \u8F93\u51FA\u76EE\u5F55: ${globalOutDir}`);
635
+ console.log(` \u23F1\uFE0F \u8017\u65F6: ${elapsed}s`);
636
+ console.log(` \u23F3 VitePress \u6B63\u5728\u6E32\u67D3\u9875\u9762...`);
637
+ } else {
638
+ console.log(`
639
+ \u274C \u6784\u5EFA\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u9519\u8BEF\u4FE1\u606F`);
640
+ }
641
+ globalIsBuilding = false;
642
+ }, 500);
643
+ }
644
+ };
645
+ }
646
+
647
+ // vitepress/plugins/fileWatcherBridgePlugin.ts
648
+ var RENAME_EVENT = "tnotes:note-renamed";
649
+ var BROADCAST_PATH = "/__tnotes_broadcast_rename";
650
+ function fileWatcherBridgePlugin() {
651
+ return {
652
+ name: "tnotes-file-watcher-bridge",
653
+ apply: "serve",
654
+ configureServer(server) {
655
+ server.middlewares.use((req, res, next) => {
656
+ const url = req.url ?? "";
657
+ const isBroadcast = url === BROADCAST_PATH || url.endsWith(BROADCAST_PATH);
658
+ if (!isBroadcast || req.method !== "POST") {
659
+ return next();
660
+ }
661
+ let body = "";
662
+ req.on("data", (chunk) => {
663
+ body += chunk.toString();
664
+ });
665
+ req.on("end", () => {
666
+ try {
667
+ const data = JSON.parse(body || "{}");
668
+ server.ws.send({ type: "custom", event: RENAME_EVENT, data });
669
+ res.statusCode = 204;
670
+ res.end();
671
+ } catch (error) {
672
+ res.statusCode = 400;
673
+ res.end(
674
+ error instanceof Error ? error.message : "Bad rename payload"
675
+ );
676
+ }
677
+ });
678
+ });
679
+ }
680
+ };
681
+ }
682
+
683
+ // vitepress/plugins/getNoteByConfigIdPlugin.ts
684
+ function getNoteByConfigIdPlugin() {
685
+ return {
686
+ name: "tnotes-get-note-by-config-id",
687
+ configureServer(server) {
688
+ server.middlewares.use(async (req, res, next) => {
689
+ if (req.url?.startsWith("/__tnotes_get_note?") && req.method === "GET") {
690
+ try {
691
+ const url = new URL(req.url, `http://${req.headers.host}`);
692
+ const configId = url.searchParams.get("configId");
693
+ if (!configId) {
694
+ res.statusCode = 400;
695
+ res.setHeader("Content-Type", "application/json");
696
+ res.end(
697
+ JSON.stringify({
698
+ success: false,
699
+ error: "Missing configId parameter"
700
+ })
701
+ );
702
+ return;
703
+ }
704
+ const noteIndexCache = NoteIndexCache.getInstance();
705
+ if (!noteIndexCache.isInitialized()) {
706
+ res.statusCode = 503;
707
+ res.setHeader("Content-Type", "application/json");
708
+ res.end(
709
+ JSON.stringify({
710
+ success: false,
711
+ error: "Service not initialized"
712
+ })
713
+ );
714
+ return;
715
+ }
716
+ const noteItem = noteIndexCache.getByConfigId(configId);
717
+ if (!noteItem) {
718
+ res.statusCode = 200;
719
+ res.setHeader("Content-Type", "application/json");
720
+ res.end(
721
+ JSON.stringify({
722
+ success: true,
723
+ found: false,
724
+ data: null
725
+ })
726
+ );
727
+ return;
728
+ }
729
+ res.statusCode = 200;
730
+ res.setHeader("Content-Type", "application/json");
731
+ res.end(
732
+ JSON.stringify({
733
+ success: true,
734
+ found: true,
735
+ data: {
736
+ noteIndex: noteItem.noteIndex,
737
+ folderName: noteItem.folderName,
738
+ // 构建笔记的完整 URL(包含 README)
739
+ url: `/notes/${encodeURIComponent(
740
+ noteItem.folderName
741
+ )}/README`
742
+ }
743
+ })
744
+ );
745
+ logger.debug(
746
+ `\u67E5\u8BE2\u7B14\u8BB0: configId=${configId}, noteIndex=${noteItem.noteIndex}`
747
+ );
748
+ } catch (error) {
749
+ logger.error("\u67E5\u8BE2\u7B14\u8BB0\u5931\u8D25:", error);
750
+ res.statusCode = 500;
751
+ res.setHeader("Content-Type", "application/json");
752
+ res.end(
753
+ JSON.stringify({
754
+ success: false,
755
+ error: error instanceof Error ? error.message : String(error)
756
+ })
757
+ );
758
+ }
759
+ } else {
760
+ next();
761
+ }
762
+ });
763
+ }
764
+ };
765
+ }
766
+
767
+ // vitepress/plugins/localSearchReindexPlugin.ts
768
+ import path4 from "path";
769
+
770
+ // vitepress/plugins/localSearchIndexBuilder.ts
771
+ import MiniSearch from "minisearch";
772
+ import fs2 from "fs/promises";
773
+ import path3 from "path";
774
+ import {
775
+ createMarkdownRenderer,
776
+ resolvePages
777
+ } from "vitepress";
778
+
779
+ // vitepress/plugins/localSearchReindexLogic.ts
780
+ import path2 from "path";
781
+ function slash(value) {
782
+ return value.replace(/\\/g, "/");
783
+ }
784
+ var NOTE_README_RE = /(?:^|[\\/])notes[\\/](\d{4}\.[^\\/]+)[\\/]README\.md$/i;
785
+ function isNoteReadmePath(filePath, ignoreDirNames = []) {
786
+ const normalized = filePath.replace(/\\/g, "/");
787
+ const match = NOTE_README_RE.exec(normalized);
788
+ if (!match) return false;
789
+ const folderName = match[1];
790
+ if (!folderName) return false;
791
+ return !ignoreDirNames.some((dir) => folderName === dir);
792
+ }
793
+ function getDocIdFromFile(input) {
794
+ const absoluteFile = path2.isAbsolute(input.absoluteOrRelativeFile) ? input.absoluteOrRelativeFile : path2.join(input.srcDir, input.absoluteOrRelativeFile);
795
+ let relFile = slash(path2.relative(input.srcDir, absoluteFile));
796
+ if (input.rewrites?.[relFile]) {
797
+ relFile = input.rewrites[relFile];
798
+ }
799
+ let id = slash(path2.posix.join(input.base, relFile));
800
+ id = id.replace(/(^|\/)index\.md$/, "$1");
801
+ id = id.replace(/\.md$/, input.cleanUrls ? "" : ".html");
802
+ return id;
803
+ }
804
+
805
+ // vitepress/plugins/localSearchIndexBuilder.ts
806
+ var headingRegex = /<h(\d*).*?>(.*?<a.*? href="#.*?".*?>.*?<\/a>)<\/h\1>/gi;
807
+ var headingContentRegex = /(.*?)<a.*? href="#(.*?)".*?>.*?<\/a>/i;
808
+ function slash2(value) {
809
+ return value.replace(/\\/g, "/");
810
+ }
811
+ function clearHtmlTags(str) {
812
+ return str.replace(/<[^>]*>/g, "");
813
+ }
814
+ function getSearchableText(content) {
815
+ return clearHtmlTags(content);
816
+ }
817
+ function* splitPageIntoSections(html) {
818
+ const result = html.split(headingRegex);
819
+ result.shift();
820
+ let parentTitles = [];
821
+ for (let i = 0; i < result.length; i += 3) {
822
+ const level = parseInt(result[i], 10) - 1;
823
+ const heading = result[i + 1];
824
+ const headingResult = headingContentRegex.exec(heading);
825
+ const title = clearHtmlTags(headingResult?.[1] ?? "").trim();
826
+ const anchor = headingResult?.[2] ?? "";
827
+ const content = result[i + 2];
828
+ if (!title || !content) continue;
829
+ let titles = parentTitles.slice(0, level);
830
+ titles[level] = title;
831
+ titles = titles.filter(Boolean);
832
+ yield { anchor, titles, text: getSearchableText(content) };
833
+ if (level === 0) {
834
+ parentTitles = [title];
835
+ } else {
836
+ parentTitles[level] = title;
837
+ }
838
+ }
839
+ }
840
+ function getLocaleForPath(site, page) {
841
+ const normalizedPage = slash2(page);
842
+ for (const [localePath, localeConfig] of Object.entries(site.locales ?? {})) {
843
+ const prefix = localePath.replace(/\\/g, "/");
844
+ if (prefix === "root") continue;
845
+ const normalizedPrefix = prefix.endsWith("/") ? prefix : `${prefix}/`;
846
+ if (normalizedPage.startsWith(normalizedPrefix)) {
847
+ return localePath;
848
+ }
849
+ if (localeConfig?.lang && normalizedPage === prefix.replace(/\/$/, "")) {
850
+ return localePath;
851
+ }
852
+ }
853
+ return "root";
854
+ }
855
+ async function createLocalSearchMarkdownRenderer(siteConfig) {
856
+ return createMarkdownRenderer(
857
+ siteConfig.srcDir,
858
+ siteConfig.markdown,
859
+ siteConfig.site.base,
860
+ siteConfig.logger
861
+ );
862
+ }
863
+ async function renderPageHtml(siteConfig, md, absoluteFile) {
864
+ if (!await fs2.stat(absoluteFile).catch(() => null)) return "";
865
+ const srcDir = siteConfig.srcDir;
866
+ const relativePath = slash2(path3.relative(srcDir, absoluteFile));
867
+ const env = {
868
+ path: absoluteFile,
869
+ relativePath,
870
+ cleanUrls: siteConfig.cleanUrls ?? false,
871
+ frontmatter: {}
872
+ };
873
+ const options = siteConfig.site.themeConfig?.search?.options ?? {};
874
+ const mdRaw = await fs2.readFile(absoluteFile, "utf-8");
875
+ if (options._render) {
876
+ return await options._render(mdRaw, env, md);
877
+ }
878
+ const html = md.render(mdRaw, env);
879
+ return env.frontmatter?.search === false ? "" : html;
880
+ }
881
+ async function indexPage(siteConfig, md, page, index) {
882
+ const absoluteFile = path3.join(siteConfig.srcDir, page);
883
+ const fileId = getDocIdFromFile({
884
+ srcDir: siteConfig.srcDir,
885
+ base: siteConfig.site.base,
886
+ cleanUrls: siteConfig.cleanUrls ?? false,
887
+ rewrites: siteConfig.rewrites.map,
888
+ absoluteOrRelativeFile: absoluteFile
889
+ });
890
+ const html = await renderPageHtml(siteConfig, md, absoluteFile);
891
+ const sections = splitPageIntoSections(html);
892
+ for (const section of sections) {
893
+ if (!section || !(section.text || section.titles)) break;
894
+ const { anchor, text, titles } = section;
895
+ const id = anchor ? [fileId, anchor].join("#") : fileId;
896
+ if (index.has(id)) index.discard(id);
897
+ index.add({
898
+ id,
899
+ text,
900
+ title: titles[titles.length - 1],
901
+ titles: titles.slice(0, -1)
902
+ });
903
+ }
904
+ }
905
+ async function buildLocalSearchIndexSnapshot(siteConfig, md) {
906
+ const { pages } = await resolvePages(
907
+ siteConfig.srcDir,
908
+ siteConfig.userConfig,
909
+ siteConfig.logger
910
+ );
911
+ const options = siteConfig.site.themeConfig?.search?.options ?? {};
912
+ const indexByLocale = /* @__PURE__ */ new Map();
913
+ for (const page of pages) {
914
+ const locale = getLocaleForPath(siteConfig.site, page);
915
+ let index = indexByLocale.get(locale);
916
+ if (!index) {
917
+ index = new MiniSearch({
918
+ fields: ["title", "titles", "text"],
919
+ storeFields: ["title", "titles"],
920
+ ...options.miniSearch?.options
921
+ });
922
+ indexByLocale.set(locale, index);
923
+ }
924
+ await indexPage(siteConfig, md, page, index);
925
+ }
926
+ const snapshot = /* @__PURE__ */ new Map();
927
+ for (const [locale, index] of indexByLocale) {
928
+ snapshot.set(locale, JSON.stringify(JSON.stringify(index)));
929
+ }
930
+ return { snapshot, pageCount: pages.length };
931
+ }
932
+
933
+ // vitepress/plugins/localSearchReindexPatch.ts
934
+ function patchVPNavBarSearch(code) {
935
+ if (code.includes("localSearchIndexBridge")) return null;
936
+ if (!code.includes("VPLocalSearchBox")) return null;
937
+ let next = code.replace(
938
+ /<script lang="ts" setup>\r?\n/,
939
+ `<script lang="ts" setup>
940
+ import { searchBoxRemountKey } from '@tnotesjs/core/vitepress/client/localSearchIndexBridge'
941
+ `
942
+ );
943
+ next = next.replace(
944
+ /<VPLocalSearchBox\r?\n\s+v-if="showSearch"\r?\n\s+@close="showSearch = false"\r?\n\s+\/>/,
945
+ `<VPLocalSearchBox
946
+ v-if="showSearch"
947
+ :key="searchBoxRemountKey"
948
+ @close="showSearch = false"
949
+ />`
950
+ );
951
+ return next === code ? null : next;
952
+ }
953
+
954
+ // vitepress/plugins/localSearchReindexPlugin.ts
955
+ var LOCAL_SEARCH_INDEX_REQUEST_PATH = "/@localSearchIndex";
956
+ var LOCAL_SEARCH_INDEX_ID = "@localSearchIndex";
957
+ var SEARCH_REINDEX_HTTP_PATH = "/__tnotes_search_reindex";
958
+ var SEARCH_INDEX_HMR_EVENT = "tnotes:search-index-updated";
959
+ var REBUILD_DEBOUNCE_MS = 400;
960
+ var VP_NAV_BAR_SEARCH = /vitepress[/\\]dist[/\\]client[/\\]theme-default[/\\]components[/\\]VPNavBarSearch\.vue$/;
961
+ var reindexController = null;
962
+ var indexSnapshot = null;
963
+ var snapshotRevision = 0;
964
+ var DEBUG = process.env.TNOTES_DEBUG_SEARCH_REINDEX === "1";
965
+ function debugLog(message, detail) {
966
+ if (!DEBUG) return;
967
+ if (detail === void 0) {
968
+ console.log(`[tnotes:search-reindex] ${message}`);
969
+ return;
970
+ }
971
+ console.log(`[tnotes:search-reindex] ${message}`, detail);
972
+ }
973
+ function logInfo(message) {
974
+ console.warn(`[tnotes:search-reindex] ${message}`);
975
+ }
976
+ function normalizeId(id) {
977
+ return id.replace(/\\/g, "/");
978
+ }
979
+ function getVitePressSiteConfig(server) {
980
+ return server.config.vitepress ?? null;
981
+ }
982
+ function isLocalSearchEnabled(server) {
983
+ return server.config.plugins.some(
984
+ (entry) => entry.name === "vitepress:local-search" && typeof entry.load === "function"
985
+ );
986
+ }
987
+ function normalizeLocalSearchModuleId(id) {
988
+ return id.split("?")[0];
989
+ }
990
+ function getLocaleFromIndexModuleId(id) {
991
+ const normalized = normalizeLocalSearchModuleId(id);
992
+ if (normalized === LOCAL_SEARCH_INDEX_REQUEST_PATH) return null;
993
+ if (!normalized.startsWith(LOCAL_SEARCH_INDEX_REQUEST_PATH)) return null;
994
+ return normalized.slice(LOCAL_SEARCH_INDEX_REQUEST_PATH.length) || null;
995
+ }
996
+ function getSearchIndexModuleIds(snapshot) {
997
+ const ids = [LOCAL_SEARCH_INDEX_REQUEST_PATH];
998
+ for (const locale of snapshot.keys()) {
999
+ ids.push(`${LOCAL_SEARCH_INDEX_REQUEST_PATH}${locale}`);
1000
+ }
1001
+ return ids;
1002
+ }
1003
+ function notifySearchIndexUpdated(server, snapshot, revision) {
1004
+ const moduleIds = getSearchIndexModuleIds(snapshot);
1005
+ const updates = [];
1006
+ for (const moduleId of moduleIds) {
1007
+ server.moduleGraph.onFileChange(moduleId);
1008
+ const mod = server.moduleGraph.getModuleById(moduleId);
1009
+ if (mod) {
1010
+ server.moduleGraph.invalidateModule(mod);
1011
+ updates.push({
1012
+ acceptedPath: mod.url,
1013
+ path: mod.url,
1014
+ timestamp: Date.now(),
1015
+ type: "js-update"
1016
+ });
1017
+ continue;
1018
+ }
1019
+ debugLog(`HMR module not loaded yet: ${moduleId}`);
1020
+ }
1021
+ if (updates.length > 0) {
1022
+ server.ws.send({ type: "update", updates });
1023
+ debugLog("HMR pushed", updates.map((item) => item.path));
1024
+ } else {
1025
+ debugLog("HMR skipped: no loaded search index modules");
1026
+ }
1027
+ server.ws.send({
1028
+ type: "custom",
1029
+ event: SEARCH_INDEX_HMR_EVENT,
1030
+ data: { revision }
1031
+ });
1032
+ debugLog("custom HMR event sent", { revision });
1033
+ }
1034
+ function renderSnapshotLoad(id, snapshot) {
1035
+ const normalizedId = normalizeLocalSearchModuleId(id);
1036
+ if (normalizedId === LOCAL_SEARCH_INDEX_REQUEST_PATH) {
1037
+ const records = [];
1038
+ for (const locale2 of snapshot.keys()) {
1039
+ records.push(
1040
+ `${JSON.stringify(locale2)}: () => import('${LOCAL_SEARCH_INDEX_ID}${locale2}')`
1041
+ );
1042
+ }
1043
+ return `export default {${records.join(",")}}`;
1044
+ }
1045
+ const locale = getLocaleFromIndexModuleId(id);
1046
+ if (locale !== null) {
1047
+ const payload = snapshot.get(locale) ?? JSON.stringify({});
1048
+ return `export default ${payload}`;
1049
+ }
1050
+ return null;
1051
+ }
1052
+ function createDebouncer(delayMs) {
1053
+ let timer = null;
1054
+ let pendingReason = "";
1055
+ return (reason, task) => {
1056
+ pendingReason = reason;
1057
+ if (timer) clearTimeout(timer);
1058
+ timer = setTimeout(async () => {
1059
+ timer = null;
1060
+ const reasonToRun = pendingReason;
1061
+ pendingReason = "";
1062
+ try {
1063
+ await task();
1064
+ } catch (error) {
1065
+ console.error(
1066
+ `[tnotes:search-reindex] rebuild failed (${reasonToRun})`,
1067
+ error
1068
+ );
1069
+ }
1070
+ }, delayMs);
1071
+ };
1072
+ }
1073
+ function matchesSearchReindexPath(url) {
1074
+ return url === SEARCH_REINDEX_HTTP_PATH || url.endsWith(SEARCH_REINDEX_HTTP_PATH);
1075
+ }
1076
+ function scheduleNoteSearchReindex(reason = "external") {
1077
+ if (!reindexController) {
1078
+ logInfo(`schedule ignored (plugin not ready): ${reason}`);
1079
+ return;
1080
+ }
1081
+ reindexController.schedule(reason);
1082
+ }
1083
+ function localSearchReindexPlugin() {
1084
+ return {
1085
+ name: "tnotes-local-search-reindex",
1086
+ apply: "serve",
1087
+ enforce: "pre",
1088
+ resolveId(source) {
1089
+ if (!source.startsWith(LOCAL_SEARCH_INDEX_ID)) return null;
1090
+ const clean = source.split("?")[0];
1091
+ if (clean === source) return null;
1092
+ return `/${clean}`;
1093
+ },
1094
+ transform(code, id) {
1095
+ const normalizedId = normalizeId(id);
1096
+ if (VP_NAV_BAR_SEARCH.test(normalizedId)) {
1097
+ return patchVPNavBarSearch(code);
1098
+ }
1099
+ return null;
1100
+ },
1101
+ load(id) {
1102
+ if (!indexSnapshot || !id.startsWith(LOCAL_SEARCH_INDEX_REQUEST_PATH)) {
1103
+ return null;
1104
+ }
1105
+ return renderSnapshotLoad(id, indexSnapshot);
1106
+ },
1107
+ configureServer(server) {
1108
+ server.middlewares.use((req, res, next) => {
1109
+ const url = req.url ?? "";
1110
+ if (!matchesSearchReindexPath(url) || req.method !== "POST") {
1111
+ return next();
1112
+ }
1113
+ let body = "";
1114
+ req.on("data", (chunk) => {
1115
+ body += chunk.toString();
1116
+ });
1117
+ req.on("end", () => {
1118
+ try {
1119
+ const data = JSON.parse(body || "{}");
1120
+ scheduleNoteSearchReindex(data.reason || "bridge:http");
1121
+ res.statusCode = 204;
1122
+ res.end();
1123
+ } catch (error) {
1124
+ res.statusCode = 400;
1125
+ res.end(
1126
+ error instanceof Error ? error.message : "Bad search reindex payload"
1127
+ );
1128
+ }
1129
+ });
1130
+ });
1131
+ return async () => {
1132
+ indexSnapshot = null;
1133
+ snapshotRevision = 0;
1134
+ if (!isLocalSearchEnabled(server)) {
1135
+ reindexController = null;
1136
+ logInfo("vitepress:local-search not found, reindex disabled");
1137
+ return;
1138
+ }
1139
+ const siteConfig = getVitePressSiteConfig(server);
1140
+ if (!siteConfig) {
1141
+ reindexController = null;
1142
+ logInfo("server.config.vitepress missing, reindex disabled");
1143
+ return;
1144
+ }
1145
+ ConfigManager.init({ rootPath: process.cwd() });
1146
+ const ignoreDirNames = ConfigManager.getInstance().getAll().ignore_dirs ?? [];
1147
+ const md = await createLocalSearchMarkdownRenderer(siteConfig);
1148
+ const debouncedRebuild = createDebouncer(REBUILD_DEBOUNCE_MS);
1149
+ async function rebuildFullIndex(reason) {
1150
+ const startedAt = Date.now();
1151
+ snapshotRevision += 1;
1152
+ debugLog(`rebuild start (${reason}) rev=${snapshotRevision}`);
1153
+ const { snapshot, pageCount } = await buildLocalSearchIndexSnapshot(
1154
+ siteConfig,
1155
+ md
1156
+ );
1157
+ indexSnapshot = snapshot;
1158
+ notifySearchIndexUpdated(server, indexSnapshot, snapshotRevision);
1159
+ logInfo(
1160
+ `rebuild done (${reason}) rev=${snapshotRevision} pages=${pageCount} locales=${indexSnapshot.size} elapsed=${Date.now() - startedAt}ms`
1161
+ );
1162
+ }
1163
+ reindexController = {
1164
+ schedule(reason) {
1165
+ debugLog(`scheduled (${reason})`);
1166
+ debouncedRebuild(reason, () => rebuildFullIndex(reason));
1167
+ }
1168
+ };
1169
+ const onWatcherEvent = (absoluteFile, event) => {
1170
+ if (!isNoteReadmePath(absoluteFile, ignoreDirNames)) return;
1171
+ scheduleNoteSearchReindex(
1172
+ `watcher:${event}:${path4.basename(absoluteFile)}`
1173
+ );
1174
+ };
1175
+ server.watcher.on("add", (file) => onWatcherEvent(file, "add"));
1176
+ server.watcher.on("change", (file) => onWatcherEvent(file, "change"));
1177
+ server.watcher.on("unlink", (file) => onWatcherEvent(file, "unlink"));
1178
+ };
1179
+ }
1180
+ };
1181
+ }
1182
+
1183
+ // vitepress/plugins/renameNotePlugin.ts
1184
+ function renameNotePlugin() {
1185
+ const renameCommand = new RenameNoteCommand();
1186
+ return {
1187
+ name: "tnotes-rename-note",
1188
+ configureServer(server) {
1189
+ server.middlewares.use(async (req, res, next) => {
1190
+ if (req.url === "/__tnotes_rename_note" && req.method === "POST") {
1191
+ let body = "";
1192
+ req.on("data", (chunk) => {
1193
+ body += chunk.toString();
1194
+ });
1195
+ req.on("end", async () => {
1196
+ try {
1197
+ const { noteIndex, newTitle } = JSON.parse(body);
1198
+ if (!noteIndex || !newTitle) {
1199
+ res.statusCode = 400;
1200
+ res.end("Missing noteIndex or newTitle");
1201
+ return;
1202
+ }
1203
+ const startTime = Date.now();
1204
+ await renameCommand.renameNote({ noteIndex, newTitle });
1205
+ const duration = Date.now() - startTime;
1206
+ const newFolderName = `${noteIndex}. ${newTitle.trim()}`;
1207
+ const newUrl = `/notes/${encodeURIComponent(
1208
+ newFolderName
1209
+ )}/README`;
1210
+ res.statusCode = 200;
1211
+ res.setHeader("Content-Type", "application/json");
1212
+ res.end(
1213
+ JSON.stringify({
1214
+ success: true,
1215
+ duration,
1216
+ newTitle,
1217
+ newFolderName,
1218
+ newUrl,
1219
+ message: "\u91CD\u547D\u540D\u5B8C\u6210"
1220
+ })
1221
+ );
1222
+ } catch (error) {
1223
+ res.statusCode = 500;
1224
+ res.end(error instanceof Error ? error.message : "Rename failed");
1225
+ }
1226
+ });
1227
+ } else {
1228
+ next();
1229
+ }
1230
+ });
1231
+ }
1232
+ };
1233
+ }
1234
+
1235
+ // vitepress/plugins/sidebarStructurePlugin.ts
1236
+ async function readJsonBody(req) {
1237
+ let body = "";
1238
+ await new Promise((resolve, reject) => {
1239
+ req.on("data", (chunk) => {
1240
+ body += chunk.toString();
1241
+ });
1242
+ req.on("end", resolve);
1243
+ req.on("error", reject);
1244
+ });
1245
+ return body ? JSON.parse(body) : {};
1246
+ }
1247
+ function sendJson(res, statusCode, payload) {
1248
+ res.statusCode = statusCode;
1249
+ res.setHeader("Content-Type", "application/json");
1250
+ res.end(JSON.stringify(payload));
1251
+ }
1252
+ function normalizePathname(url) {
1253
+ return (url || "").split("?")[0];
1254
+ }
1255
+ function normalizeCount(value) {
1256
+ const count = Number(value ?? 1);
1257
+ if (!Number.isInteger(count) || count < 1 || count > 100) {
1258
+ throw new Error("count must be an integer between 1 and 100");
1259
+ }
1260
+ return count;
1261
+ }
1262
+ function getCreatedNotePayload(notes) {
1263
+ return notes.map((note) => ({
1264
+ index: note.index,
1265
+ dirName: note.dirName,
1266
+ link: `/notes/${encodeURIComponent(note.dirName)}/README`
1267
+ }));
1268
+ }
1269
+ function buildNoteReadmeLink(note) {
1270
+ return `/notes/${encodeURIComponent(note.dirName)}/README`;
1271
+ }
1272
+ function resolveDeleteRedirectUrl(noteService, previousNoteIndex) {
1273
+ if (!previousNoteIndex) return "/";
1274
+ const previousNote = noteService.getNoteByIndex(previousNoteIndex);
1275
+ if (!previousNote) return "/";
1276
+ return buildNoteReadmeLink(previousNote);
1277
+ }
1278
+ async function withSuspendedWatcher(task) {
1279
+ const watcher = FileWatcherService.getInstance();
1280
+ try {
1281
+ watcher?.suspend();
1282
+ return await task();
1283
+ } finally {
1284
+ watcher?.unsuspend();
1285
+ }
1286
+ }
1287
+ function sidebarStructurePlugin() {
1288
+ const noteService = NoteService.getInstance();
1289
+ const tocService = TocService.getInstance();
1290
+ async function createNotes(count) {
1291
+ const notes = [];
1292
+ const usedIndexes = /* @__PURE__ */ new Set();
1293
+ for (const note of noteService.getAllNotes()) {
1294
+ const index = parseInt(note.index, 10);
1295
+ if (!isNaN(index)) {
1296
+ usedIndexes.add(index);
1297
+ }
1298
+ }
1299
+ for (let i = 0; i < count; i++) {
1300
+ const note = await noteService.createNote({
1301
+ title: "new",
1302
+ usedIndexes
1303
+ });
1304
+ const index = parseInt(note.index, 10);
1305
+ if (!isNaN(index)) {
1306
+ usedIndexes.add(index);
1307
+ }
1308
+ notes.push(note);
1309
+ }
1310
+ return notes;
1311
+ }
1312
+ async function refreshTocAndSidebar() {
1313
+ await tocService.regenerateSidebar();
1314
+ }
1315
+ return {
1316
+ name: "tnotes-sidebar-structure",
1317
+ configureServer(server) {
1318
+ server.middlewares.use(async (req, res, next) => {
1319
+ const pathname = normalizePathname(req.url);
1320
+ const handledPaths = /* @__PURE__ */ new Set([
1321
+ "/__tnotes_sidebar_create_note",
1322
+ "/__tnotes_sidebar_create_notes",
1323
+ "/__tnotes_sidebar_create_folder",
1324
+ "/__tnotes_sidebar_delete_note",
1325
+ "/__tnotes_sidebar_delete_entry",
1326
+ "/__tnotes_sidebar_rename_folder",
1327
+ "/__tnotes_sidebar_reorder"
1328
+ ]);
1329
+ if (!handledPaths.has(pathname)) {
1330
+ next();
1331
+ return;
1332
+ }
1333
+ if (req.method !== "POST") {
1334
+ sendJson(res, 405, { success: false, message: "Method Not Allowed" });
1335
+ return;
1336
+ }
1337
+ try {
1338
+ const data = await readJsonBody(req);
1339
+ const result = await withSuspendedWatcher(async () => {
1340
+ if (pathname === "/__tnotes_sidebar_delete_note") {
1341
+ const noteIndex = String(data.noteIndex || "");
1342
+ if (!noteIndex) throw new Error("Missing noteIndex");
1343
+ const previousNoteIndex = await tocService.getPreviousNoteIndexBeforeDelete(noteIndex);
1344
+ await tocService.deleteNoteFromToc(noteIndex);
1345
+ await noteService.deleteNote(noteIndex);
1346
+ await refreshTocAndSidebar();
1347
+ scheduleNoteSearchReindex("api:delete-note");
1348
+ return {
1349
+ success: true,
1350
+ sidebarChanged: true,
1351
+ redirectUrl: resolveDeleteRedirectUrl(
1352
+ noteService,
1353
+ previousNoteIndex
1354
+ ),
1355
+ redirectNoteIndex: previousNoteIndex,
1356
+ deletedNoteIndexes: [noteIndex],
1357
+ message: "\u7B14\u8BB0\u5DF2\u5220\u9664"
1358
+ };
1359
+ }
1360
+ if (pathname === "/__tnotes_sidebar_delete_entry") {
1361
+ const tocLineIndex = Number(data.tocLineIndex);
1362
+ if (!Number.isInteger(tocLineIndex) || tocLineIndex < 0) {
1363
+ throw new Error("Missing tocLineIndex");
1364
+ }
1365
+ const currentNoteIndex = String(data.currentNoteIndex || "");
1366
+ const previousNoteIndex = await tocService.getPreviousNoteIndexBeforeEntryDelete(
1367
+ tocLineIndex
1368
+ );
1369
+ const inSubtree = currentNoteIndex && await tocService.isNoteInTocEntrySubtree(
1370
+ tocLineIndex,
1371
+ currentNoteIndex
1372
+ );
1373
+ const deletedNoteIndexes = await tocService.deleteTocEntryCascade(tocLineIndex);
1374
+ await refreshTocAndSidebar();
1375
+ scheduleNoteSearchReindex("api:delete-entry");
1376
+ return {
1377
+ success: true,
1378
+ sidebarChanged: true,
1379
+ redirectUrl: inSubtree ? resolveDeleteRedirectUrl(noteService, previousNoteIndex) : void 0,
1380
+ redirectNoteIndex: inSubtree ? previousNoteIndex : null,
1381
+ deletedNoteIndexes,
1382
+ message: "\u5DF2\u5220\u9664"
1383
+ };
1384
+ }
1385
+ if (pathname === "/__tnotes_sidebar_rename_folder") {
1386
+ const tocLineIndex = Number(data.tocLineIndex);
1387
+ const newTitle = String(data.newTitle || "");
1388
+ if (!Number.isInteger(tocLineIndex) || tocLineIndex < 0) {
1389
+ throw new Error("Missing tocLineIndex");
1390
+ }
1391
+ await tocService.renameFolderInToc(tocLineIndex, newTitle);
1392
+ await refreshTocAndSidebar();
1393
+ return {
1394
+ success: true,
1395
+ sidebarChanged: true,
1396
+ message: "\u76EE\u5F55\u5DF2\u91CD\u547D\u540D"
1397
+ };
1398
+ }
1399
+ if (pathname === "/__tnotes_sidebar_reorder") {
1400
+ if (data.node_uuid && data.action === "prependChild" && !data.target_uuid) {
1401
+ await tocService.prependToRootByNodeId(String(data.node_uuid));
1402
+ await refreshTocAndSidebar();
1403
+ return {
1404
+ success: true,
1405
+ sidebarChanged: true,
1406
+ message: "\u6392\u5E8F\u5DF2\u66F4\u65B0"
1407
+ };
1408
+ }
1409
+ if (data.node_uuid && data.target_uuid && (data.action === "moveAfter" || data.action === "prependChild")) {
1410
+ if (data.action === "moveAfter") {
1411
+ await tocService.moveAfterByNodeId(
1412
+ String(data.node_uuid),
1413
+ String(data.target_uuid)
1414
+ );
1415
+ } else {
1416
+ await tocService.prependChildByNodeId(
1417
+ String(data.node_uuid),
1418
+ String(data.target_uuid)
1419
+ );
1420
+ }
1421
+ await refreshTocAndSidebar();
1422
+ return {
1423
+ success: true,
1424
+ sidebarChanged: true,
1425
+ message: "\u6392\u5E8F\u5DF2\u66F4\u65B0"
1426
+ };
1427
+ }
1428
+ const dragTocLineIndex = Number(data.dragTocLineIndex);
1429
+ if (!Number.isInteger(dragTocLineIndex) || dragTocLineIndex < 0) {
1430
+ throw new Error("Missing dragTocLineIndex");
1431
+ }
1432
+ const placement = data.targetType === "group" || data.placement === "inside" ? "inside" : data.placement === "after" ? "after" : "before";
1433
+ if (data.targetTocLineIndex !== void 0 && data.targetTocLineIndex !== null) {
1434
+ await tocService.moveTocEntryByLineIndex(dragTocLineIndex, {
1435
+ targetTocLineIndex: Number(data.targetTocLineIndex),
1436
+ placement
1437
+ });
1438
+ } else if (Array.isArray(data.targetFolderPath) && data.targetFolderPath.length > 0) {
1439
+ await tocService.moveTocEntryByLineIndex(dragTocLineIndex, {
1440
+ targetType: "folder",
1441
+ targetFolderPath: data.targetFolderPath.map(String),
1442
+ placement
1443
+ });
1444
+ } else {
1445
+ const targetNoteIndex = String(
1446
+ data.targetNoteIndex || data.targetGroupNoteIndex || ""
1447
+ );
1448
+ if (!targetNoteIndex) throw new Error("Missing targetNoteIndex");
1449
+ await tocService.moveTocEntryByLineIndex(dragTocLineIndex, {
1450
+ targetType: "note",
1451
+ targetNoteIndex,
1452
+ placement
1453
+ });
1454
+ }
1455
+ await refreshTocAndSidebar();
1456
+ return {
1457
+ success: true,
1458
+ sidebarChanged: true,
1459
+ message: "\u6392\u5E8F\u5DF2\u66F4\u65B0"
1460
+ };
1461
+ }
1462
+ if (pathname === "/__tnotes_sidebar_create_folder") {
1463
+ const parentTocLineIndex = Number(data.parentTocLineIndex);
1464
+ const title = String(data.title || "");
1465
+ if (!Number.isInteger(parentTocLineIndex) || parentTocLineIndex < 0) {
1466
+ throw new Error("Missing parentTocLineIndex");
1467
+ }
1468
+ await tocService.insertFolderUnderParent(
1469
+ parentTocLineIndex,
1470
+ title
1471
+ );
1472
+ await refreshTocAndSidebar();
1473
+ return {
1474
+ success: true,
1475
+ sidebarChanged: true,
1476
+ message: "\u76EE\u5F55\u5DF2\u521B\u5EFA"
1477
+ };
1478
+ }
1479
+ const count = normalizeCount(data.count);
1480
+ const notes = await createNotes(count);
1481
+ if (data.targetNoteIndex) {
1482
+ const placement = data.placement === "after" ? "after" : "before";
1483
+ await tocService.insertNotesAroundNote(
1484
+ String(data.targetNoteIndex),
1485
+ notes,
1486
+ placement
1487
+ );
1488
+ } else if (data.parentTocLineIndex !== void 0 && data.parentTocLineIndex !== null) {
1489
+ await tocService.insertNotesUnderTocLine(
1490
+ Number(data.parentTocLineIndex),
1491
+ notes
1492
+ );
1493
+ } else if (Array.isArray(data.parentFolderPath) && data.parentFolderPath.length > 0) {
1494
+ await tocService.insertNotesUnderFolder(
1495
+ data.parentFolderPath.map(String),
1496
+ notes
1497
+ );
1498
+ } else if (data.parentNoteIndex) {
1499
+ await tocService.insertNotesUnderParent(
1500
+ String(data.parentNoteIndex),
1501
+ notes
1502
+ );
1503
+ } else {
1504
+ for (const note of notes) {
1505
+ await tocService.appendNoteToToc(note.index);
1506
+ }
1507
+ }
1508
+ await refreshTocAndSidebar();
1509
+ scheduleNoteSearchReindex("api:create-notes");
1510
+ return {
1511
+ success: true,
1512
+ sidebarChanged: true,
1513
+ createdNotes: getCreatedNotePayload(notes),
1514
+ message: "\u7B14\u8BB0\u5DF2\u521B\u5EFA"
1515
+ };
1516
+ });
1517
+ sendJson(res, 200, result);
1518
+ } catch (error) {
1519
+ console.error("\u4FA7\u8FB9\u680F\u7ED3\u6784\u64CD\u4F5C\u5931\u8D25:", error);
1520
+ sendJson(res, 500, {
1521
+ success: false,
1522
+ message: error instanceof Error ? error.message : String(error)
1523
+ });
1524
+ }
1525
+ });
1526
+ }
1527
+ };
1528
+ }
1529
+
1530
+ // vitepress/plugins/updateConfigPlugin.ts
1531
+ function updateConfigPlugin() {
1532
+ let updateCommand;
1533
+ return {
1534
+ name: "tnotes-update-config",
1535
+ configureServer(server) {
1536
+ updateCommand = new UpdateNoteConfigCommand();
1537
+ server.middlewares.use(async (req, res, next) => {
1538
+ if (req.url === "/__tnotes_update_config" && req.method === "POST") {
1539
+ let body = "";
1540
+ req.on("data", (chunk) => {
1541
+ body += chunk.toString();
1542
+ });
1543
+ req.on("end", async () => {
1544
+ try {
1545
+ const data = JSON.parse(body);
1546
+ const { noteIndex, config } = data;
1547
+ if (!noteIndex || !config) {
1548
+ res.statusCode = 400;
1549
+ res.end("Missing noteIndex or config");
1550
+ return;
1551
+ }
1552
+ await updateCommand.updateConfig({
1553
+ noteIndex,
1554
+ config: {
1555
+ done: config.done,
1556
+ enableDiscussions: config.enableDiscussions,
1557
+ description: config.description
1558
+ }
1559
+ });
1560
+ res.statusCode = 200;
1561
+ res.setHeader("Content-Type", "application/json");
1562
+ res.end(JSON.stringify({ success: true }));
1563
+ } catch (error) {
1564
+ console.error("\u66F4\u65B0\u914D\u7F6E\u5931\u8D25:", error);
1565
+ res.statusCode = 500;
1566
+ res.end(error instanceof Error ? error.message : String(error));
1567
+ }
1568
+ });
1569
+ } else {
1570
+ next();
1571
+ }
1572
+ });
1573
+ }
1574
+ };
1575
+ }
1576
+
1577
+ // vitepress/config/index.ts
1578
+ function defineNotesConfig(overrides = {}) {
1579
+ const rootPath = process.cwd();
1580
+ ConfigManager.init({ rootPath });
1581
+ const config = ConfigManager.getInstance().getAll();
1582
+ const { repoName } = config;
1583
+ const IGNORE_LIST = getIgnoreList(config);
1584
+ const GITHUB_PAGE_URL = getGithubPageUrl(config);
1585
+ const {
1586
+ transformPageData: overrideTransformPageData,
1587
+ vite: overrideVite,
1588
+ ...restOverrides
1589
+ } = overrides;
1590
+ return defineConfig({
1591
+ appearance: "dark",
1592
+ base: "/" + repoName + "/",
1593
+ cleanUrls: true,
1594
+ description: repoName,
1595
+ head: getHeadConfig(config, GITHUB_PAGE_URL),
1596
+ ignoreDeadLinks: true,
1597
+ lang: "zh-Hans",
1598
+ lastUpdated: false,
1599
+ markdown: getMarkdownConfig(),
1600
+ sitemap: {
1601
+ hostname: GITHUB_PAGE_URL,
1602
+ lastmodDateOnly: false
1603
+ },
1604
+ themeConfig: getThemeConfig(config),
1605
+ title: repoName,
1606
+ srcExclude: IGNORE_LIST,
1607
+ vite: {
1608
+ plugins: [
1609
+ buildProgressPlugin(),
1610
+ updateConfigPlugin(),
1611
+ renameNotePlugin(),
1612
+ sidebarStructurePlugin(),
1613
+ getNoteByConfigIdPlugin(),
1614
+ fileWatcherBridgePlugin(),
1615
+ localSearchReindexPlugin(),
1616
+ ...overrideVite?.plugins || []
1617
+ ],
1618
+ server: {
1619
+ // 显式同时监听 IPv4 / IPv6,避免 Node 18+ 在 Windows 下偶发只绑定 ::1
1620
+ // 导致 Chrome 解析 localhost → 127.0.0.1 时连接被拒、页面一直 pending。
1621
+ // host: true,
1622
+ watch: {
1623
+ ignored: IGNORE_LIST
1624
+ },
1625
+ ...overrideVite?.server
1626
+ },
1627
+ css: {
1628
+ preprocessorOptions: {
1629
+ scss: {
1630
+ silenceDeprecations: ["legacy-js-api"]
1631
+ }
1632
+ },
1633
+ ...overrideVite?.css
1634
+ },
1635
+ build: {
1636
+ chunkSizeWarningLimit: 1e3,
1637
+ ...overrideVite?.build
1638
+ },
1639
+ define: {
1640
+ __TNOTES_REPO_NAME__: JSON.stringify(config.repoName),
1641
+ __TNOTES_AUTHOR__: JSON.stringify(config.author),
1642
+ __TNOTES_IGNORE_DIRS__: JSON.stringify(config.ignore_dirs),
1643
+ __TNOTES_ROOT_ITEM__: JSON.stringify(config.root_item),
1644
+ ...overrideVite?.define
1645
+ },
1646
+ resolve: {
1647
+ dedupe: ["vue", "vitepress"],
1648
+ ...overrideVite?.resolve
1649
+ },
1650
+ optimizeDeps: {
1651
+ include: [
1652
+ // VitePress 内部 CJS 依赖 —— 需要 Vite 预构建为 ESM
1653
+ "vitepress > @vscode/markdown-it-katex",
1654
+ "vitepress > @braintree/sanitize-url",
1655
+ "vitepress > dayjs",
1656
+ "vitepress > dayjs/plugin/utc",
1657
+ "vitepress > dayjs/plugin/localizedFormat"
1658
+ ],
1659
+ ...overrideVite?.optimizeDeps
1660
+ }
1661
+ },
1662
+ transformPageData(pageData, ctx) {
1663
+ if (/^notes\/\d{4}/.test(pageData.relativePath)) {
1664
+ const fullPath = path5.resolve(rootPath, pageData.relativePath);
1665
+ try {
1666
+ const raw = fs3.readFileSync(fullPath, "utf-8");
1667
+ pageData.frontmatter.rawContent = Buffer.from(raw, "utf-8").toString(
1668
+ "base64"
1669
+ );
1670
+ } catch {
1671
+ pageData.frontmatter.rawContent = null;
1672
+ }
1673
+ }
1674
+ if (typeof overrideTransformPageData === "function") {
1675
+ return overrideTransformPageData(pageData, ctx);
1676
+ }
1677
+ },
1678
+ router: {
1679
+ prefetchLinks: false
1680
+ },
1681
+ ...restOverrides
1682
+ });
1683
+ }
1684
+ export {
1685
+ defineNotesConfig
1686
+ };