@tnotesjs/core 0.2.1 → 0.3.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.
Files changed (86) hide show
  1. package/README.md +0 -1
  2. package/config/ConfigManager.ts +137 -0
  3. package/config/constants.ts +121 -0
  4. package/config/defaultConfig.ts +33 -4
  5. package/config/index.ts +31 -0
  6. package/config/templates.ts +49 -0
  7. package/core/GitManager.ts +513 -0
  8. package/core/NoteIndexCache.ts +200 -0
  9. package/core/NoteManager.ts +395 -0
  10. package/core/ProcessManager.ts +180 -0
  11. package/core/ReadmeGenerator.ts +215 -0
  12. package/core/TocGenerator.ts +212 -0
  13. package/core/index.ts +11 -0
  14. package/dist/{chunk-5Y5IYS6C.js → chunk-UJG3UU5X.js} +21 -5
  15. package/dist/{chunk-5QN44ES5.js → chunk-XCWFZLER.js} +48 -368
  16. package/dist/cli/index.js +26 -78
  17. package/dist/index.js +1 -1
  18. package/dist/vitepress/config/index.js +2 -2
  19. package/package.json +5 -2
  20. package/services/file-watcher/configChangeHandler.ts +64 -0
  21. package/services/file-watcher/eventScheduler.ts +179 -0
  22. package/services/file-watcher/folderChangeHandler.ts +325 -0
  23. package/services/file-watcher/fsWatcherAdapter.ts +128 -0
  24. package/services/file-watcher/globalUpdateCoordinator.ts +60 -0
  25. package/services/file-watcher/index.ts +7 -0
  26. package/services/file-watcher/internal.ts +79 -0
  27. package/services/file-watcher/readmeChangeHandler.ts +28 -0
  28. package/services/file-watcher/renameDetector.ts +120 -0
  29. package/services/file-watcher/service.ts +352 -0
  30. package/services/file-watcher/watchState.ts +194 -0
  31. package/services/git/index.ts +7 -0
  32. package/services/git/service.ts +114 -0
  33. package/services/index.ts +14 -0
  34. package/services/init-sub-repo/index.ts +2 -0
  35. package/services/init-sub-repo/initSubRepoLogic.test.ts +162 -0
  36. package/services/init-sub-repo/initSubRepoLogic.ts +303 -0
  37. package/services/init-sub-repo/service.ts +101 -0
  38. package/services/note/index.ts +7 -0
  39. package/services/note/service.ts +361 -0
  40. package/services/readme/index.ts +7 -0
  41. package/services/readme/service.ts +761 -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/types/config.ts +0 -3
  48. package/types/note.ts +0 -2
  49. package/utils/errorHandler.ts +174 -0
  50. package/utils/file.ts +17 -0
  51. package/utils/genHierarchicalSidebar.ts +69 -0
  52. package/utils/generateAnchor.ts +24 -0
  53. package/utils/getChangedIds.ts +35 -0
  54. package/utils/index.ts +71 -0
  55. package/utils/logger.ts +231 -0
  56. package/utils/markdown.ts +75 -0
  57. package/utils/migrateReadmeToToc.test.ts +111 -0
  58. package/utils/migrateReadmeToToc.ts +135 -0
  59. package/utils/parseArgs.ts +90 -0
  60. package/utils/parseReadmeCompletedNotes.test.ts +90 -0
  61. package/utils/parseReadmeCompletedNotes.ts +108 -0
  62. package/utils/portUtils.ts +113 -0
  63. package/utils/readmeHelpers.ts +190 -0
  64. package/utils/runCommand.ts +29 -0
  65. package/utils/tocHelpers.test.ts +278 -0
  66. package/utils/tocHelpers.ts +855 -0
  67. package/utils/tocNodeId.test.ts +60 -0
  68. package/utils/tocNodeId.ts +97 -0
  69. package/utils/validators.ts +102 -0
  70. package/vitepress/assets/icons/icon__cursor.svg +4 -0
  71. package/vitepress/assets/icons/index.ts +1 -0
  72. package/vitepress/components/Layout/AboutPanel.vue +0 -24
  73. package/vitepress/components/Layout/DocBeforeControls.vue +6 -14
  74. package/vitepress/components/Layout/DocFooter.vue +3 -3
  75. package/vitepress/components/Layout/Layout.vue +0 -30
  76. package/vitepress/components/Layout/composables/useVSCodeIntegration.ts +20 -11
  77. package/vitepress/components/Layout/homeReadme.data.ts +0 -48
  78. package/vitepress/components/MarkMap/MarkMap.vue +6 -13
  79. package/vitepress/components/Settings/Settings.vue +76 -73
  80. package/vitepress/components/SidebarCard/FolderTreeItems.vue +16 -6
  81. package/vitepress/components/SidebarCard/SidebarCard.vue +21 -27
  82. package/vitepress/components/composables/useLocalIde.ts +83 -0
  83. package/vitepress/components/constants.ts +5 -6
  84. package/vitepress/components/utils/vscodePaths.test.ts +22 -0
  85. package/vitepress/components/utils/vscodePaths.ts +24 -2
  86. package/vitepress/theme/styles/doc-layout.scss +4 -4
package/dist/cli/index.js CHANGED
@@ -19,7 +19,6 @@ import {
19
19
  ROOT_TOC_PATH,
20
20
  ReadmeService,
21
21
  RenameNoteCommand,
22
- TimestampService,
23
22
  TocService,
24
23
  UpdateNoteConfigCommand,
25
24
  VitepressService,
@@ -42,11 +41,12 @@ import {
42
41
  runCommand,
43
42
  validatePort,
44
43
  validateTopic
45
- } from "../chunk-5QN44ES5.js";
44
+ } from "../chunk-XCWFZLER.js";
46
45
  import {
47
46
  ConfigManager,
48
- getConfigManager
49
- } from "../chunk-5Y5IYS6C.js";
47
+ getConfigManager,
48
+ stripDeprecatedRootItemFields
49
+ } from "../chunk-UJG3UU5X.js";
50
50
 
51
51
  // commands/update/UpdateCommand.ts
52
52
  import { existsSync, readFileSync, writeFileSync } from "fs";
@@ -121,6 +121,9 @@ var UpdateCommand = class extends BaseCommand {
121
121
  completed_notes_count: fixed
122
122
  };
123
123
  delete config.root_item.completed_notes_count_last_month;
124
+ stripDeprecatedRootItemFields(
125
+ config.root_item
126
+ );
124
127
  writeFileSync(ROOT_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
125
128
  if (!this.quiet) {
126
129
  const filledCount = Object.keys(fixed).length - _countsBeforeFix;
@@ -192,7 +195,6 @@ var PushCommand = class extends BaseCommand {
192
195
  super("push");
193
196
  this.gitManager = new GitManager(ROOT_DIR_PATH);
194
197
  this.gitService = new GitService();
195
- this.timestampService = new TimestampService();
196
198
  }
197
199
  async run() {
198
200
  try {
@@ -214,18 +216,6 @@ var PushCommand = class extends BaseCommand {
214
216
  const commitMessage = this.gitService.generateCommitMessage();
215
217
  await runCommand("git add -A", ROOT_DIR_PATH);
216
218
  await runCommand(`git commit -m "${commitMessage}"`, ROOT_DIR_PATH);
217
- this.logger.info("\u4FEE\u590D\u7B14\u8BB0\u65F6\u95F4\u6233...");
218
- await this.timestampService.fixAllTimestamps(false);
219
- const afterFixStatus = await runCommand(
220
- "git -c core.quotePath=false status --porcelain",
221
- ROOT_DIR_PATH
222
- );
223
- const hasTimestampChanges = afterFixStatus.split(/\r?\n/).filter(Boolean).some((line) => line.includes(".tnotes.json"));
224
- if (hasTimestampChanges) {
225
- this.logger.info("\u5C06\u65F6\u95F4\u6233\u53D8\u66F4\u5408\u5E76\u5230 commit...");
226
- await runCommand("git add -u", ROOT_DIR_PATH);
227
- await runCommand("git commit --amend --no-edit", ROOT_DIR_PATH);
228
- }
229
219
  } else {
230
220
  this.logger.info(`\u68C0\u6D4B\u5230 ${status.ahead} \u4E2A\u672A\u63A8\u9001\u7684\u63D0\u4EA4\uFF0C\u76F4\u63A5\u63A8\u9001...`);
231
221
  }
@@ -539,37 +529,6 @@ var InitTocCommand = class extends BaseCommand {
539
529
  }
540
530
  };
541
531
 
542
- // commands/maintenance/FixTimestampsCommand.ts
543
- var FixTimestampsCommand = class extends BaseCommand {
544
- constructor() {
545
- super("fix-timestamps");
546
- this.timestampService = new TimestampService();
547
- }
548
- async run() {
549
- this.logger.info("\u5F00\u59CB\u4FEE\u590D\u6240\u6709\u7B14\u8BB0\u7684\u65F6\u95F4\u6233...");
550
- this.logger.info("\u{1F4CC} \u6B64\u64CD\u4F5C\u4F1A\u5C06\u6240\u6709\u65F6\u95F4\u6233\u66F4\u65B0\u4E3A git \u771F\u5B9E\u65F6\u95F4");
551
- this.logger.info("");
552
- const result = await this.timestampService.fixAllTimestamps(true);
553
- this.logger.info("");
554
- this.logger.info("\u{1F4CA} \u4FEE\u590D\u7EDF\u8BA1:");
555
- this.logger.info(
556
- ` - \u6839\u914D\u7F6E\u6587\u4EF6: ${result.rootConfigFixed ? "\u5DF2\u4FEE\u590D" : "\u65E0\u9700\u4FEE\u590D"}`
557
- );
558
- this.logger.info(` - \u603B\u7B14\u8BB0\u6570: ${result.total}`);
559
- this.logger.info(` - \u5DF2\u4FEE\u590D: ${result.fixed}`);
560
- this.logger.info(` - \u8DF3\u8FC7: ${result.skipped}`);
561
- this.logger.info("");
562
- if (result.fixed > 0 || result.rootConfigFixed) {
563
- this.logger.success(
564
- `\u2705 \u6210\u529F\u4FEE\u590D ${result.fixed} \u4E2A\u7B14\u8BB0${result.rootConfigFixed ? " + \u6839\u914D\u7F6E\u6587\u4EF6" : ""}\u7684\u65F6\u95F4\u6233\uFF01`
565
- );
566
- this.logger.info("\u{1F4A1} \u63D0\u793A: \u8FD0\u884C pnpm tn:push \u63D0\u4EA4\u66F4\u6539");
567
- } else {
568
- this.logger.success("\u2705 \u6240\u6709\u65F6\u95F4\u6233\u5747\u5DF2\u6B63\u786E\uFF01");
569
- }
570
- }
571
- };
572
-
573
532
  // commands/misc/HelpCommand.ts
574
533
  var COMMAND_CATEGORIES = {
575
534
  \u5F00\u53D1\u548C\u6784\u5EFA: [COMMAND_NAMES.DEV, COMMAND_NAMES.BUILD, COMMAND_NAMES.PREVIEW],
@@ -581,7 +540,7 @@ var COMMAND_CATEGORIES = {
581
540
  "Git \u64CD\u4F5C": [COMMAND_NAMES.PUSH, COMMAND_NAMES.PULL],
582
541
  "\u8FC1\u79FB\uFF08v0.2.x \u8FC7\u6E21\uFF09": [COMMAND_NAMES.INIT_TOC],
583
542
  \u521D\u59CB\u5316: [COMMAND_NAMES.INIT_SUB_REPO],
584
- \u5176\u4ED6: [COMMAND_NAMES.FIX_TIMESTAMPS, COMMAND_NAMES.HELP]
543
+ \u5176\u4ED6: [COMMAND_NAMES.HELP]
585
544
  };
586
545
  var COMMAND_OPTIONS_INFO = {
587
546
  [COMMAND_OPTIONS.QUIET]: {
@@ -783,13 +742,14 @@ var UpdateCompletedCountCommand = class extends BaseCommand {
783
742
  const configContent = readFileSync4(ROOT_CONFIG_PATH, "utf-8");
784
743
  const config = JSON.parse(configContent);
785
744
  this.logger.info("\u5F00\u59CB\u66F4\u65B0\u5B8C\u6210\u7B14\u8BB0\u6570\u91CF\u5386\u53F2\u8BB0\u5F55...");
786
- const completedNotesCountHistory = await this.getCompletedNotesCountHistory(
787
- config.root_item.created_at ?? Date.now()
788
- );
745
+ const completedNotesCountHistory = await this.getCompletedNotesCountHistory();
789
746
  config.root_item = {
790
747
  ...config.root_item,
791
748
  completed_notes_count: completedNotesCountHistory
792
749
  };
750
+ stripDeprecatedRootItemFields(
751
+ config.root_item
752
+ );
793
753
  writeFileSync3(ROOT_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
794
754
  const duration = Date.now() - startTime;
795
755
  const monthKeys = Object.keys(completedNotesCountHistory);
@@ -812,10 +772,9 @@ var UpdateCompletedCountCommand = class extends BaseCommand {
812
772
  * 1. 计算最近12个月的范围(当前月份往前推11个月)
813
773
  * 2. 遍历这12个月,从 Git 历史中读取 TOC.md(回退 README.md)
814
774
  * 3. 解析获取完成笔记数量
815
- * 4. 如果知识库创建时间在这12个月内,之前的月份补0
816
- * 5. 返回对象 { '25.01': 0, '25.02': 1, ..., '25.12': 15 }
775
+ * 4. 返回对象 { '25.01': 0, '25.02': 1, ..., '25.12': 15 }
817
776
  */
818
- async getCompletedNotesCountHistory(createdAt) {
777
+ async getCompletedNotesCountHistory() {
819
778
  try {
820
779
  const now = /* @__PURE__ */ new Date();
821
780
  const currentYear = now.getFullYear();
@@ -826,9 +785,6 @@ var UpdateCompletedCountCommand = class extends BaseCommand {
826
785
  firstYear = currentYear - 1;
827
786
  firstMonth = 12 + firstMonth;
828
787
  }
829
- const createdDate = new Date(createdAt);
830
- const createdYear = createdDate.getFullYear();
831
- const createdMonth = createdDate.getMonth();
832
788
  const result = {};
833
789
  let prevCount = 0;
834
790
  for (let i = 0; i < 12; i++) {
@@ -837,25 +793,18 @@ var UpdateCompletedCountCommand = class extends BaseCommand {
837
793
  const yearShort = String(targetYear).slice(-2);
838
794
  const monthStr = String(targetMonth + 1).padStart(2, "0");
839
795
  const key = `${yearShort}.${monthStr}`;
840
- const isBeforeCreation = targetYear < createdYear || targetYear === createdYear && targetMonth < createdMonth;
841
- if (isBeforeCreation) {
842
- result[key] = 0;
843
- prevCount = 0;
844
- this.logger.info(`\u2713 ${key}: 0 \u7BC7\uFF08\u65E9\u4E8E\u521B\u5EFA\u65F6\u95F4\uFF09`);
845
- } else {
846
- try {
847
- const count = await this.getMonthCompletedCount(
848
- targetYear,
849
- targetMonth,
850
- prevCount
851
- );
852
- result[key] = count;
853
- prevCount = count;
854
- this.logger.info(`\u2713 ${key}: ${count} \u7BC7`);
855
- } catch (error) {
856
- result[key] = prevCount;
857
- this.logger.warn(`${key}: \u65E0\u6570\u636E\uFF0C\u4F7F\u7528 ${prevCount}\uFF08\u4E0A\u6708\u503C\uFF09`);
858
- }
796
+ try {
797
+ const count = await this.getMonthCompletedCount(
798
+ targetYear,
799
+ targetMonth,
800
+ prevCount
801
+ );
802
+ result[key] = count;
803
+ prevCount = count;
804
+ this.logger.info(`\u2713 ${key}: ${count} \u7BC7`);
805
+ } catch (error) {
806
+ result[key] = prevCount;
807
+ this.logger.warn(`${key}: \u65E0\u6570\u636E\uFF0C\u4F7F\u7528 ${prevCount}\uFF08\u4E0A\u6708\u503C\uFF09`);
859
808
  }
860
809
  }
861
810
  return result;
@@ -919,7 +868,6 @@ var commandFactories = {
919
868
  "build": () => new BuildCommand(),
920
869
  "create-notes": () => new CreateNoteCommand(),
921
870
  "dev": () => new DevCommand(),
922
- "fix-timestamps": () => new FixTimestampsCommand(),
923
871
  "init-sub-repo": () => new InitSubRepoCommand(),
924
872
  "init-toc": () => new InitTocCommand(),
925
873
  "help": () => new HelpCommand(),
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ConfigManager,
3
3
  getConfigManager
4
- } from "./chunk-5Y5IYS6C.js";
4
+ } from "./chunk-UJG3UU5X.js";
5
5
  export {
6
6
  ConfigManager,
7
7
  getConfigManager
@@ -7,10 +7,10 @@ import {
7
7
  UpdateNoteConfigCommand,
8
8
  generateAnchor,
9
9
  logger
10
- } from "../../chunk-5QN44ES5.js";
10
+ } from "../../chunk-XCWFZLER.js";
11
11
  import {
12
12
  ConfigManager
13
- } from "../../chunk-5Y5IYS6C.js";
13
+ } from "../../chunk-UJG3UU5X.js";
14
14
 
15
15
  // vitepress/config/index.ts
16
16
  import fs3 from "fs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnotesjs/core",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "TNotes 知识库核心框架 —— 基于 VitePress 的笔记管理系统",
5
5
  "type": "module",
6
6
  "packageManager": "pnpm@10.17.1",
@@ -22,7 +22,10 @@
22
22
  "./vitepress/*": "./vitepress/*"
23
23
  },
24
24
  "files": [
25
- "config/defaultConfig.ts",
25
+ "config/",
26
+ "core/",
27
+ "services/",
28
+ "utils/",
26
29
  "dist/",
27
30
  "templates/",
28
31
  "vitepress/",
@@ -0,0 +1,64 @@
1
+ /**
2
+ * services/file-watcher/configChangeHandler.ts
3
+ *
4
+ * 配置变更处理
5
+ */
6
+
7
+ import type { WatchEvent } from './internal'
8
+ import type { WatchState } from './watchState'
9
+ import type { NoteIndexCache } from '../../core/NoteIndexCache'
10
+ import type { Logger } from '../../utils'
11
+ import type { NoteService } from '../note/service'
12
+
13
+ interface ConfigChangeHandlerConfig {
14
+ /** 监听状态管理器 */
15
+ state: WatchState
16
+ /** 笔记服务实例 */
17
+ noteService: NoteService
18
+ /** 笔记索引缓存实例 */
19
+ noteIndexCache: NoteIndexCache
20
+ /** 日志记录器 */
21
+ logger: Logger
22
+ }
23
+
24
+ export class ConfigChangeHandler {
25
+ constructor(private config: ConfigChangeHandlerConfig) {}
26
+
27
+ async handle(events: WatchEvent[]): Promise<string[]> {
28
+ if (events.length === 0) return []
29
+ const changedIndexes: string[] = []
30
+
31
+ const { state, noteService, noteIndexCache, logger } = this.config
32
+
33
+ for (const change of events) {
34
+ // 忽略由 API 主动写入的更新,避免重复触发
35
+ if (noteService.shouldIgnoreConfigChange(change.path)) {
36
+ logger.debug(`忽略 API 写入的配置文件: ${change.path}`)
37
+ continue
38
+ }
39
+
40
+ const snapshot = state.readConfigSnapshot(change.path)
41
+ if (!snapshot) continue
42
+
43
+ const cached = state.getConfigSnapshot(change.path)
44
+ state.setConfigSnapshot(change.path, snapshot)
45
+ noteIndexCache.updateConfig(change.noteIndex, snapshot)
46
+
47
+ if (!cached) continue
48
+
49
+ const statusChanged = cached.done !== snapshot.done
50
+ const otherChanged =
51
+ cached.enableDiscussions !== snapshot.enableDiscussions ||
52
+ cached.description !== snapshot.description
53
+
54
+ if (statusChanged) {
55
+ changedIndexes.push(change.noteIndex)
56
+ logger.info(`检测到配置状态变化: done(${cached.done}→${snapshot.done})`)
57
+ } else if (otherChanged) {
58
+ logger.info('检测到配置非状态字段变化,已刷新缓存(无需全局更新)')
59
+ }
60
+ }
61
+
62
+ return changedIndexes
63
+ }
64
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * services/file-watcher/eventScheduler.ts
3
+ *
4
+ * 事件调度:防抖 + 批量检测 + 队列
5
+ */
6
+
7
+ import type { WatchEvent } from './internal'
8
+
9
+ /** 默认防抖延迟(毫秒) */
10
+ const DEFAULT_DEBOUNCE_MS = 1000
11
+
12
+ /**
13
+ * 默认批量更新检测窗口(毫秒)
14
+ *
15
+ * - 如果在窗口时间内检测到超过阈值个文件变更,则判定为批量更新
16
+ * - 暂定是 1s 内 3 个文件变更的阈值,正常编写笔记的情况下,1s 内不会超过 3 个文件同时变更,通常不会误判
17
+ * - 当批量更新的行为被检测到之后,会暂停监听服务(窗口 + 缓冲时间)后再恢复
18
+ */
19
+ const DEFAULT_BATCH_WINDOW_MS = 1000
20
+
21
+ /** 默认批量更新阈值(文件数) */
22
+ const DEFAULT_BATCH_THRESHOLD = 3
23
+
24
+ /** 默认批量更新安全缓冲(毫秒) */
25
+ const DEFAULT_BATCH_BUFFER_MS = 2000
26
+
27
+ interface EventSchedulerConfig {
28
+ /** 防抖延迟(毫秒),默认 1000 */
29
+ debounceMs?: number
30
+ /** 批量更新检测窗口(毫秒),默认 1000 */
31
+ batchWindowMs?: number
32
+ /** 批量更新阈值(文件数),默认 3 */
33
+ batchThreshold?: number
34
+ /** 批量更新安全缓冲(毫秒),默认 2000 */
35
+ batchBufferMs?: number
36
+ /** 当事件队列需要刷新处理时的回调函数 */
37
+ onFlush: (events: WatchEvent[]) => void
38
+ /** 检测到批量更新时暂停监听服务的回调函数 */
39
+ onPauseForBatch: () => void
40
+ /** 批量更新结束后恢复监听服务的回调函数 */
41
+ onResumeAfterBatch: () => void
42
+ /** 重新初始化调度器的回调函数 */
43
+ reinit: () => void
44
+ }
45
+
46
+ export class EventScheduler {
47
+ /** 待处理的文件变更事件队列 */
48
+ private pendingEvents: Map<string, WatchEvent> = new Map()
49
+
50
+ /** 防抖定时器 */
51
+ private updateTimer: NodeJS.Timeout | null = null
52
+
53
+ /** 批量更新恢复定时器 */
54
+ private batchResumeTimer: NodeJS.Timeout | null = null
55
+
56
+ /** 记录最近的变更时间戳 */
57
+ private recentChanges: number[] = []
58
+
59
+ /** 标记是否正在更新,避免循环触发 - 类似一把更新行为锁 */
60
+ private isUpdating = false
61
+
62
+ private readonly debounceMs: number
63
+ private readonly batchWindowMs: number
64
+ private readonly batchThreshold: number
65
+ private readonly batchBufferMs: number
66
+
67
+ constructor(private config: EventSchedulerConfig) {
68
+ this.debounceMs = config.debounceMs ?? DEFAULT_DEBOUNCE_MS
69
+ this.batchWindowMs = config.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS
70
+ this.batchThreshold = config.batchThreshold ?? DEFAULT_BATCH_THRESHOLD
71
+ this.batchBufferMs = config.batchBufferMs ?? DEFAULT_BATCH_BUFFER_MS
72
+ }
73
+
74
+ /**
75
+ * 设置更新状态锁,用于防止在执行耗时更新操作时被新的文件变更事件打断
76
+ *
77
+ * @param flag - true 表示正在更新(锁定),false 表示更新完成(解锁)
78
+ */
79
+ setUpdating(flag: boolean) {
80
+ this.isUpdating = flag
81
+ }
82
+
83
+ /**
84
+ * 获取当前是否处于更新锁定状态
85
+ *
86
+ * @returns true 表示正在执行更新操作(事件处理被暂停),false 表示空闲可处理新事件
87
+ */
88
+ getUpdating() {
89
+ return this.isUpdating
90
+ }
91
+
92
+ /**
93
+ * 将文件变更事件加入待处理队列,并启动防抖定时器
94
+ *
95
+ * - 若同一文件路径的事件已存在,则忽略重复事件(去重)
96
+ * - 每次新事件都会重置防抖计时器,确保在变更停止后才触发处理
97
+ *
98
+ * @param event 文件变更事件
99
+ */
100
+ enqueue(event: WatchEvent) {
101
+ // 事件去重:同一路径的变更只保留一次,降低抖动
102
+ if (this.pendingEvents.has(event.path)) return
103
+ this.pendingEvents.set(event.path, event)
104
+ if (this.updateTimer) clearTimeout(this.updateTimer)
105
+ this.updateTimer = setTimeout(() => this.flush(), this.debounceMs)
106
+ }
107
+
108
+ /**
109
+ * 立即触发事件队列的处理(防抖到期或手动调用)
110
+ *
111
+ * - 若当前正在更新(isUpdating 为 true),则跳过以避免重复处理
112
+ * - 清空待处理事件队列,并通过 onFlush 回调交由上层服务处理
113
+ * - 处理开始后会锁定更新状态,防止处理过程中被新事件打断
114
+ */
115
+ flush() {
116
+ if (this.isUpdating) return
117
+ if (this.pendingEvents.size === 0) return
118
+ const events = Array.from(this.pendingEvents.values())
119
+ this.pendingEvents.clear()
120
+ this.isUpdating = true
121
+ this.config.onFlush(events)
122
+ }
123
+
124
+ /**
125
+ * 记录当前变更时间并检测是否触发批量更新模式
126
+ *
127
+ * - 维护一个滑动时间窗口(BATCH_UPDATE_WINDOW_MS)内的变更记录
128
+ * - 若短时间内(1秒内)变更次数达到阈值(BATCH_UPDATE_THRESHOLD = 3),则判定为批量操作
129
+ * - 触发批量模式后:
130
+ * 1. 清空当前待处理事件队列,避免重复处理
131
+ * 2. 锁定更新状态(isUpdating = true)
132
+ * 3. 暂停监听服务,并在延迟(窗口 + 缓冲时间)后自动恢复
133
+ *
134
+ * @param now 当前时间戳(默认使用 Date.now())
135
+ * @returns true 表示已触发批量更新模式,false 表示仍处于普通监听模式
136
+ */
137
+ recordChangeAndDetectBatch(now: number = Date.now()): boolean {
138
+ // 记录近期变更时间戳,用于检测“短时间高频”场景并切换到批量模式
139
+ this.recentChanges.push(now)
140
+ this.recentChanges = this.recentChanges.filter(
141
+ (t) => now - t < this.batchWindowMs,
142
+ )
143
+
144
+ if (this.recentChanges.length < this.batchThreshold) return false
145
+
146
+ this.pendingEvents.clear()
147
+ this.recentChanges = []
148
+ this.isUpdating = true
149
+ this.config.onPauseForBatch()
150
+
151
+ this.batchResumeTimer = setTimeout(() => {
152
+ // 批量结束后重建状态并恢复监听
153
+ this.batchResumeTimer = null
154
+ this.isUpdating = false
155
+ this.config.reinit()
156
+ this.config.onResumeAfterBatch()
157
+ }, this.batchWindowMs + this.batchBufferMs)
158
+
159
+ return true
160
+ }
161
+
162
+ /**
163
+ * 清理所有定时器,释放资源
164
+ *
165
+ * 在服务停止时调用,防止定时器在服务销毁后仍然触发回调
166
+ */
167
+ clearTimers(): void {
168
+ if (this.updateTimer) {
169
+ clearTimeout(this.updateTimer)
170
+ this.updateTimer = null
171
+ }
172
+ if (this.batchResumeTimer) {
173
+ clearTimeout(this.batchResumeTimer)
174
+ this.batchResumeTimer = null
175
+ }
176
+ this.pendingEvents.clear()
177
+ this.recentChanges = []
178
+ }
179
+ }