mm_scanner 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/scanner.js CHANGED
@@ -2,16 +2,21 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
- const { normalizeKey, normalizeExt, buildCacheKey } = require('./path_util');
6
- const { DEFAULT_CONFIG, createConfig } = require('./scanner_config');
5
+ const { watcherAdmin, admin: watcher_admin } = require('mm_watcher');
6
+ const { normalizeKey, normalizeExt, buildCacheKey, createItem } = require('./path_util');
7
+ const { DEFAULT_CONFIG } = require('./scanner_config');
7
8
  const { walkDir } = require('./fs_util');
8
9
  const { diffItems } = require('./diff_util');
9
10
  const cache_store = require('./cache_store');
10
- const Watcher = require('./watcher');
11
+
12
+ /* 监听事件防抖窗口,与 mm_watcher 默认值一致 */
13
+ const WATCH_DEBOUNCE = 100;
11
14
 
12
15
  /**
13
16
  * 目录扫描器
14
- * @description 按扩展名递归扫描目录并缓存文件元信息,支持按 key、扩展名、目录检索,支持目录监听热更新
17
+ * @description 按扩展名递归扫描目录并缓存文件元信息,支持按 key、扩展名、目录检索,
18
+ * 支持通过 watcherAdmin 共享监听器实现文件变化热更新,
19
+ * 每个实例自行维护扫描结果并写回共享缓存
15
20
  */
16
21
  class Scanner {
17
22
  /**
@@ -27,15 +32,39 @@ class Scanner {
27
32
  #dirs = [];
28
33
  /** 本次扫描对应的缓存键 */
29
34
  #cache_key = null;
30
- /** 本实例的目录监听器 */
35
+ /** 本实例使用的共享监听器(watcherAdmin 按缓存键缓存) */
31
36
  #watcher = null;
37
+ /** 本实例注册到监听器上的事件处理器,未监听时为 null */
38
+ #handlers = null;
39
+ /** 外部变更回调 */
40
+ #callback = null;
32
41
 
33
42
  /**
34
43
  * 创建扫描器实例
35
44
  * @param {{ extensions?: string[], ignore?: string[] }} [config] - 扫描器配置
36
45
  */
37
46
  constructor(config = {}) {
38
- this.config = createConfig(Scanner.config, config);
47
+ this.config = {
48
+ extensions: [...Scanner.config.extensions],
49
+ ignore: [...Scanner.config.ignore],
50
+ };
51
+ this.setConfig(config);
52
+ }
53
+
54
+ /**
55
+ * 设置扫描配置
56
+ * @description 逐项校验并合并进当前配置:extensions 仅接受非空数组并补点转小写后整体替换,
57
+ * ignore 仅接受数组并按并集追加(默认忽略目录始终生效);非法或缺省项保留当前配置
58
+ * @param {{ extensions?: string[], ignore?: string[] }} [config] - 扫描器配置
59
+ * @returns {void}
60
+ */
61
+ setConfig(config = {}) {
62
+ if (Array.isArray(config.extensions) && config.extensions.length) {
63
+ this.config.extensions = config.extensions.map(normalizeExt);
64
+ }
65
+ if (Array.isArray(config.ignore)) {
66
+ this.config.ignore = [...new Set([...this.config.ignore, ...config.ignore])];
67
+ }
39
68
  }
40
69
 
41
70
  /* -------- 私有 -------- */
@@ -125,12 +154,132 @@ class Scanner {
125
154
  }
126
155
 
127
156
  /**
128
- * 懒创建本实例的目录监听器
157
+ * 标记缓存进入监听状态并清空时间戳校验记录
158
+ * @returns {void}
159
+ */
160
+ #markWatched() {
161
+ const cache = cache_store.readCache(this.#cache_key);
162
+ if (!cache) return;
163
+ cache.watched = true;
164
+ cache.dir_mtimes = [];
165
+ cache.file_mtimes = [];
166
+ }
167
+
168
+ /**
169
+ * 解除缓存监听标记并重建时间戳校验记录
129
170
  * @returns {void}
130
171
  */
131
- #ensureWatcher() {
132
- if (!this.#watcher) {
133
- this.#watcher = new Watcher(this.#cache_key, (items, dirs) => this.#fill(items, dirs));
172
+ #markUnwatched() {
173
+ const cache = cache_store.readCache(this.#cache_key);
174
+ if (!cache) return;
175
+ cache.watched = false;
176
+ cache_store.captureMtimes(cache);
177
+ }
178
+
179
+ /**
180
+ * 摘除本实例注册到监听器上的全部事件处理器
181
+ * @returns {void}
182
+ */
183
+ #detachHandlers() {
184
+ if (this.#watcher && this.#handlers) {
185
+ this.#watcher.off('add', this.#handlers.add);
186
+ this.#watcher.off('set', this.#handlers.set);
187
+ this.#watcher.off('del', this.#handlers.del);
188
+ this.#watcher.off('reload', this.#handlers.reload);
189
+ }
190
+ this.#handlers = null;
191
+ this.#watcher = null;
192
+ }
193
+
194
+ /**
195
+ * 判断相对路径是否为本实例关心的文件
196
+ * @description 目录段命中本实例忽略配置或扩展名不在白名单内均视为不关心;
197
+ * 共享监听器只按目录监听,配置过滤统一由实例自行完成
198
+ * @param {string} rel_path 规范化后的相对路径
199
+ * @returns {boolean} 本实例关心返回 true
200
+ */
201
+ #isConcerned(rel_path) {
202
+ const parts = rel_path.split('/');
203
+ for (let i = 0; i < parts.length - 1; i++) {
204
+ if (this.config.ignore.includes(parts[i])) return false;
205
+ }
206
+ const ext = path.extname(parts[parts.length - 1]).toLowerCase();
207
+ return this.config.extensions.includes(ext);
208
+ }
209
+
210
+ /**
211
+ * 处理文件新增或修改事件:更新本实例条目、写回缓存并通知回调
212
+ * @description 本实例忽略目录与白名单外的扩展名直接丢弃;
213
+ * stat 失败时按删除处理;条目已存在视为 change,否则视为 add
214
+ * @param {string} rel_path 相对路径
215
+ * @returns {void}
216
+ */
217
+ #onFileEvent(rel_path) {
218
+ const key = normalizeKey(rel_path);
219
+ if (!this.#isConcerned(key)) return;
220
+
221
+ const abs_path = path.join(this.#base_dir, key);
222
+ const item = createItem(this.#base_dir, abs_path);
223
+
224
+ let stat = null;
225
+ try {
226
+ stat = fs.statSync(abs_path);
227
+ } catch {
228
+ stat = null;
229
+ }
230
+ if (!stat || !stat.isFile()) {
231
+ this.#onDelEvent(rel_path);
232
+ return;
233
+ }
234
+ const type = this.#files.has(item.key) ? 'change' : 'add';
235
+ this.#files.set(item.key, item);
236
+ this.#writeCache();
237
+ this.#notify([{ type, key: item.key, item }]);
238
+ }
239
+
240
+ /**
241
+ * 处理文件删除事件:移除本实例条目、写回缓存并通知回调
242
+ * @description 本实例不关心的路径(忽略目录、白名单外扩展名)直接丢弃;
243
+ * 关心的路径未命中条目时无法精确增量,退化为全量重建兜底
244
+ * @param {string} rel_path 相对路径
245
+ * @returns {void}
246
+ */
247
+ #onDelEvent(rel_path) {
248
+ const key = normalizeKey(rel_path);
249
+ if (!this.#isConcerned(key)) return;
250
+
251
+ const old = this.#files.get(key);
252
+ if (!old) {
253
+ this.#onReloadEvent();
254
+ return;
255
+ }
256
+ this.#files.delete(key);
257
+ this.#writeCache();
258
+ this.#notify([{ type: 'unlink', key, item: old }]);
259
+ }
260
+
261
+ /**
262
+ * 处理目录级重载事件:全量重扫本实例并以差异通知回调
263
+ * @returns {void}
264
+ */
265
+ #onReloadEvent() {
266
+ const before = [...this.#files.values()];
267
+ this.#walkAndFill();
268
+ this.#writeCache();
269
+ this.#notify(diffItems(before, this.getAll()));
270
+ }
271
+
272
+ /**
273
+ * 把变更列表交给外部回调
274
+ * @param {Array<{ type: string, key: string, item: object }>} changes 变更列表,type 为 add/change/unlink
275
+ * @returns {void}
276
+ */
277
+ #notify(changes) {
278
+ if (!this.#callback || !changes.length) return;
279
+ try {
280
+ this.#callback(changes.map((one) => ({ ...one, item: { ...one.item } })));
281
+ } catch (error) {
282
+ console.error('[scanner] watch 回调执行失败:', error);
134
283
  }
135
284
  }
136
285
 
@@ -169,9 +318,7 @@ class Scanner {
169
318
  if (!fs.existsSync(resolved)) throw new Error(`[scanner] 目录不存在: ${resolved}`);
170
319
  if (!fs.statSync(resolved).isDirectory()) throw new Error(`[scanner] 不是目录: ${resolved}`);
171
320
 
172
- if (Array.isArray(options.extensions) || Array.isArray(options.ignore)) {
173
- this.config = createConfig(this.config, options);
174
- }
321
+ this.setConfig(options);
175
322
 
176
323
  this.#base_dir = resolved;
177
324
  this.#cache_key = buildCacheKey(resolved, this.config.extensions, this.config.ignore);
@@ -265,52 +412,87 @@ class Scanner {
265
412
  /** 当前支持的扩展名列表 */
266
413
  get extensions() { return [...this.config.extensions]; }
267
414
 
268
- /** 重新扫描(开发环境热更新用) */
415
+ /**
416
+ * 重新扫描(开发环境热更新用)
417
+ * @description 只重建本实例的扫描结果并写回缓存、触发本实例回调;
418
+ * 其他实例不受通知,其监听会随真实文件事件自行收敛
419
+ * @returns {Scanner} 当前实例
420
+ */
269
421
  rescan = () => {
270
422
  if (!this.#base_dir) throw new Error('[scanner] 尚未初始化,无法 rescan');
271
- const cache = cache_store.readCache(this.#cache_key);
272
- const before = cache ? cache.items : [];
423
+ const before = [...this.#files.values()];
273
424
  this.#walkAndFill();
274
425
  this.#writeCache();
275
- Watcher.sync(this.#cache_key, diffItems(before, this.getAll()));
426
+ this.#notify(diffItems(before, this.getAll()));
276
427
  return this;
277
428
  };
278
429
 
279
430
  /**
280
- * 开启目录监听,文件增删改时增量维护缓存并同步到本实例
281
- * @description 监听期间不再按时间戳校验缓存;不支持递归监听的环境会静默降级
431
+ * 开启文件监听,文件增删改时更新本实例扫描结果、写回缓存并触发回调
432
+ * @description 共享监听器以基目录为作用域经 watcherAdmin 缓存,同目录多实例复用同一底层句柄;
433
+ * 监听器只声明监听哪个目录,忽略目录与扩展名白名单由本实例在事件处理中自行过滤;
434
+ * 重复调用只更新回调;不支持递归监听的环境会静默降级
282
435
  * @param {(changes: Array<{ type: string, key: string, item: object }>) => void} [callback] 变更回调,type 为 add/change/unlink
283
436
  * @returns {Scanner} 当前实例
284
437
  */
285
438
  watch = (callback) => {
286
439
  this.#ensureReady();
287
- this.#ensureWatcher();
288
- this.#watcher.start(callback);
440
+ if (typeof callback === 'function') this.#callback = callback;
441
+ if (this.watching) return this;
442
+ if (this.#handlers) this.#detachHandlers();
443
+
444
+ const watcher = watcherAdmin(this.#base_dir, {
445
+ target: this.#base_dir,
446
+ debounce: WATCH_DEBOUNCE,
447
+ });
448
+ this.#watcher = watcher;
449
+ this.#handlers = {
450
+ add: (rel_path) => this.#onFileEvent(rel_path),
451
+ set: (rel_path) => this.#onFileEvent(rel_path),
452
+ del: (rel_path) => this.#onDelEvent(rel_path),
453
+ reload: () => this.#onReloadEvent(),
454
+ };
455
+ watcher.on('add', this.#handlers.add);
456
+ watcher.on('set', this.#handlers.set);
457
+ watcher.on('del', this.#handlers.del);
458
+ watcher.on('reload', this.#handlers.reload);
459
+
460
+ if (!watcher.listen()) {
461
+ this.#detachHandlers();
462
+ return this;
463
+ }
464
+ this.#markWatched();
289
465
  return this;
290
466
  };
291
467
 
292
468
  /**
293
- * 关闭本实例的目录监听并注销变更回调,最后一个实例关闭后停止监听
469
+ * 关闭本实例的变更回调与事件订阅
470
+ * @description 只摘除本实例的处理器,共享监听器保留(其他实例可能仍在监听),
471
+ * 统一由 Scanner.clearCache() 释放全部监听器
294
472
  * @returns {Scanner} 当前实例
295
473
  */
296
474
  unwatch = () => {
297
- if (this.#watcher) this.#watcher.dispose();
475
+ this.#detachHandlers();
476
+ this.#callback = null;
477
+ this.#markUnwatched();
298
478
  return this;
299
479
  };
300
480
 
301
481
  /**
302
- * 清空全部扫描缓存
482
+ * 释放全部共享监听器并清空扫描缓存
303
483
  * @returns {void}
304
484
  */
305
485
  static clearCache = () => {
306
- Watcher.closeAll();
486
+ for (const watcher of watcher_admin.maps.values()) {
487
+ watcher.dispose();
488
+ }
307
489
  cache_store.clear();
308
490
  };
309
491
 
310
492
  get size() { return this.#files.size; }
311
493
  get baseDir() { return this.#base_dir; }
312
494
  /** 当前实例是否处于监听状态 */
313
- get watching() { return !!this.#watcher && this.#watcher.active; }
495
+ get watching() { return !!(this.#handlers && this.#watcher && this.#watcher.active); }
314
496
  }
315
497
 
316
498
  /* 导出类 */
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- const { normalizeExt } = require('./path_util');
4
-
5
3
  /* 默认忽略的常见目录(版本控制、依赖、IDE 配置),始终生效,用户配置在其后追加 */
6
4
  const DEFAULT_IGNORE_DIRS = ['.git', '.svn', '.hg', 'node_modules', '.idea', '.vscode'];
7
5
 
@@ -13,24 +11,4 @@ const DEFAULT_CONFIG = {
13
11
  ignore: DEFAULT_IGNORE_DIRS,
14
12
  };
15
13
 
16
- /**
17
- * 合并默认配置与用户配置
18
- * @description 扩展名为空时回退默认;忽略目录为默认列表与用户列表的并集(默认项始终生效)
19
- * @param {{ extensions: string[], ignore: string[] }} default_config - 默认配置
20
- * @param {{ extensions?: string[], ignore?: string[] }} config - 用户配置
21
- * @returns {{ extensions: string[], ignore: string[] }} 规范化后的配置
22
- */
23
- function createConfig(default_config, config) {
24
- const extensions =
25
- Array.isArray(config.extensions) && config.extensions.length
26
- ? config.extensions
27
- : default_config.extensions;
28
- const user_ignore = Array.isArray(config.ignore) ? config.ignore : [];
29
-
30
- return {
31
- extensions: extensions.map(normalizeExt),
32
- ignore: [...new Set([...default_config.ignore, ...user_ignore])],
33
- };
34
- }
35
-
36
- module.exports = { DEFAULT_CONFIG, createConfig };
14
+ module.exports = { DEFAULT_CONFIG };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mm_scanner",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "目录扫描器,按扩展名递归扫描目录并缓存文件元信息,支持按 key、扩展名、目录检索文件路径,默认忽略 .git/node_modules 等常见目录,支持目录监听热更新,并再导出 mm_watcher 的 Watcher 供单文件监听使用。",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,9 +35,8 @@
35
35
  "prepublishOnly": "npm test"
36
36
  },
37
37
  "dependencies": {
38
- "chokidar": "^3.6.0",
39
38
  "mm_corejs": "^1.1.5",
40
- "mm_watcher": "^2.2.0"
39
+ "mm_watcher": "^3.0.0"
41
40
  },
42
41
  "devDependencies": {
43
42
  "jest": "^30.5.2"
@@ -1,109 +0,0 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const { createItem } = require('./path_util');
5
- const { walkDir } = require('./fs_util');
6
- const { diffItems } = require('./diff_util');
7
-
8
- /**
9
- * 缓存条目增量维护
10
- * @description 依据监听器分类后的变更事件精确更新缓存条目,无法精确定位时全量重扫兜底
11
- */
12
- class CacheUpdater {
13
- /**
14
- * 按监听变更事件更新单个路径
15
- * @param {object} cache 缓存项
16
- * @param {{ type: string, path: string }} event 变更事件,type 为 add/set/del
17
- * @param {Array<object>} changes 变更收集器
18
- * @returns {boolean} del 事件未命中缓存条目时返回 false,需要全量刷新
19
- */
20
- applyChange(cache, event, changes) {
21
- const item = createItem(cache.dir, path.join(cache.dir, event.path));
22
-
23
- if (event.type === 'del') {
24
- return this._delItem(cache, item.key, changes);
25
- }
26
-
27
- if (!cache.extensions.includes(item.ext)) {
28
- this._delSameName(cache, item, changes);
29
- return true;
30
- }
31
-
32
- const added = this._addItem(cache, item);
33
- changes.push({ type: added ? 'add' : 'change', key: item.key, item: { ...item } });
34
- return true;
35
- }
36
-
37
- /**
38
- * 全量重扫缓存对应的目录
39
- * @param {object} cache 缓存项
40
- * @param {Array<object>} changes 变更收集器
41
- * @returns {void}
42
- */
43
- refreshCache(cache, changes) {
44
- const before = cache.items;
45
- const files = new Map();
46
- const dirs = [];
47
- walkDir(cache.dir, cache.dir, cache, files, dirs);
48
- const after = [...files.values()];
49
- cache.items = after;
50
- cache.dirs = dirs;
51
- cache.time = Date.now();
52
-
53
- const diff = diffItems(before, after);
54
- for (let i = 0; i < diff.length; i++) changes.push(diff[i]);
55
- }
56
-
57
- /**
58
- * 向缓存中新增或更新一个文件条目
59
- * @param {object} cache 缓存项
60
- * @param {{ key: string, absPath: string, relPath: string, dir: string, name: string, ext: string }} item 文件条目
61
- * @returns {boolean} 新增返回 true,覆盖已有条目返回 false
62
- * @private
63
- */
64
- _addItem(cache, item) {
65
- const index = cache.items.findIndex((one) => one.key === item.key);
66
- if (index >= 0) {
67
- cache.items[index] = item;
68
- return false;
69
- }
70
- cache.items.push(item);
71
- return true;
72
- }
73
-
74
- /**
75
- * 从缓存中移除指定条目并记录变更
76
- * @param {object} cache 缓存项
77
- * @param {string} key 条目键
78
- * @param {Array<object>} changes 变更收集器
79
- * @returns {boolean} 是否移除成功
80
- * @private
81
- */
82
- _delItem(cache, key, changes) {
83
- const index = cache.items.findIndex((one) => one.key === key);
84
- if (index < 0) return false;
85
- const [item] = cache.items.splice(index, 1);
86
- changes.push({ type: 'unlink', key, item: { ...item } });
87
- return true;
88
- }
89
-
90
- /**
91
- * 移除同目录同文件名但扩展名不同的条目
92
- * @description 文件改名后扩展名不再受支持时,需要清掉旧条目
93
- * @param {object} cache 缓存项
94
- * @param {{ key: string, dir: string, name: string }} item 当前文件条目
95
- * @param {Array<object>} changes 变更收集器
96
- * @returns {void}
97
- * @private
98
- */
99
- _delSameName(cache, item, changes) {
100
- for (let i = cache.items.length - 1; i >= 0; i--) {
101
- const one = cache.items[i];
102
- if (one.key === item.key || one.dir !== item.dir || one.name !== item.name) continue;
103
- this._delItem(cache, one.key, changes);
104
- }
105
- }
106
- }
107
-
108
- /* 导出单例 */
109
- module.exports = new CacheUpdater();
@@ -1,92 +0,0 @@
1
- 'use strict';
2
-
3
- const cache_store = require('./cache_store');
4
- const { SYNC, NOTIFY } = require('./symbols');
5
-
6
- /**
7
- * 监听器登记表
8
- * @description 同一缓存键下的多个 Watcher 共享一个目录监听器
9
- */
10
- class InstanceRegistry {
11
- /** 缓存键 -> Set<Watcher> */
12
- #instances = new Map();
13
-
14
- /**
15
- * 登记监听中的实例
16
- * @param {string} key 缓存键
17
- * @param {object} instance 监听器实例
18
- * @returns {void}
19
- */
20
- add(key, instance) {
21
- let set = this.#instances.get(key);
22
- if (!set) {
23
- set = new Set();
24
- this.#instances.set(key, set);
25
- }
26
- set.add(instance);
27
- }
28
-
29
- /**
30
- * 注销监听中的实例
31
- * @param {string} key 缓存键
32
- * @param {object} instance 监听器实例
33
- * @returns {boolean} 最后一个实例被注销返回 true
34
- */
35
- del(key, instance) {
36
- const set = this.#instances.get(key);
37
- if (!set) return false;
38
- set.delete(instance);
39
- if (set.size === 0) {
40
- this.#instances.delete(key);
41
- return true;
42
- }
43
- return false;
44
- }
45
-
46
- /**
47
- * 判断实例是否处于监听状态
48
- * @param {string} key 缓存键
49
- * @param {object} instance 监听器实例
50
- * @returns {boolean} 已登记返回 true
51
- */
52
- has(key, instance) {
53
- const set = this.#instances.get(key);
54
- return !!(set && set.has(instance));
55
- }
56
-
57
- /**
58
- * 移除指定缓存键下的全部实例登记
59
- * @param {string} key 缓存键
60
- * @returns {void}
61
- */
62
- remove(key) {
63
- this.#instances.delete(key);
64
- }
65
-
66
- /**
67
- * 清空全部实例登记
68
- * @returns {void}
69
- */
70
- clear() {
71
- this.#instances.clear();
72
- }
73
-
74
- /**
75
- * 把缓存的最新条目与变更同步到监听中的实例
76
- * @param {string} key 缓存键
77
- * @param {Array<object>} changes 变更列表
78
- * @returns {void}
79
- */
80
- sync(key, changes) {
81
- const cache = cache_store.readCache(key);
82
- const set = this.#instances.get(key);
83
- if (!cache || !set) return;
84
- for (const instance of set) {
85
- instance[SYNC](cache.items, cache.dirs);
86
- instance[NOTIFY](changes);
87
- }
88
- }
89
- }
90
-
91
- /* 导出单例 */
92
- module.exports = new InstanceRegistry();
package/lib/symbols.js DELETED
@@ -1,8 +0,0 @@
1
- 'use strict';
2
-
3
- /* 内部同步方法名,仅供监听器调用 */
4
- const SYNC = Symbol('mm_scanner.sync');
5
- /* 内部回调方法名,仅供监听器调用 */
6
- const NOTIFY = Symbol('mm_scanner.notify');
7
-
8
- module.exports = { SYNC, NOTIFY };
@@ -1,170 +0,0 @@
1
- 'use strict';
2
-
3
- const { Watcher } = require('mm_watcher');
4
- const cache_store = require('./cache_store');
5
- const cache_updater = require('./cache_update');
6
- const instance_registry = require('./instance_registry');
7
-
8
- /* 文件事件防抖窗口,合并一次写入产生的多条事件 */
9
- const DEBOUNCE = 100;
10
-
11
- /**
12
- * 目录监听管理器
13
- * @description 每个缓存键持有一个 mm_watcher 监听器,订阅 add/set/del/reload 事件,
14
- * 同一防抖批次内累积变更后增量维护缓存并同步全部监听实例
15
- */
16
- class WatchManager {
17
- /** 缓存键 -> Watcher */
18
- #watchers = new Map();
19
- /** 缓存键 -> { changes, need_refresh, scheduled } */
20
- #states = new Map();
21
-
22
- /**
23
- * 为缓存绑定目录监听器
24
- * @param {string} key 缓存键
25
- * @returns {boolean} 监听是否可用
26
- */
27
- bind(key) {
28
- const cache = cache_store.readCache(key);
29
- if (!cache) return false;
30
-
31
- if (this.#watchers.has(key)) {
32
- this._markWatched(cache);
33
- return true;
34
- }
35
-
36
- const state = { changes: [], need_refresh: false, scheduled: false };
37
- const watcher = new Watcher({
38
- target: cache.dir,
39
- ignore: cache.ignore,
40
- debounce: DEBOUNCE,
41
- onError: () => this.unbind(key),
42
- });
43
- this._subscribe(watcher, key, state);
44
-
45
- if (!watcher.listen()) {
46
- return false;
47
- }
48
-
49
- this._markWatched(cache);
50
- this.#watchers.set(key, watcher);
51
- this.#states.set(key, state);
52
- return true;
53
- }
54
-
55
- /**
56
- * 解除目录监听并恢复时间戳校验
57
- * @param {string} key 缓存键
58
- * @returns {void}
59
- */
60
- unbind(key) {
61
- const watcher = this.#watchers.get(key);
62
- if (watcher) {
63
- watcher.dispose();
64
- this.#watchers.delete(key);
65
- }
66
- this.#states.delete(key);
67
-
68
- instance_registry.remove(key);
69
-
70
- const cache = cache_store.readCache(key);
71
- if (cache) {
72
- cache.watched = false;
73
- cache_store.captureMtimes(cache);
74
- }
75
- }
76
-
77
- /**
78
- * 解除全部目录监听并清空实例登记
79
- * @returns {void}
80
- */
81
- closeAll() {
82
- const keys = [...this.#watchers.keys()];
83
- for (let i = 0; i < keys.length; i++) {
84
- this.unbind(keys[i]);
85
- }
86
- instance_registry.clear();
87
- }
88
-
89
- /**
90
- * 标记缓存进入监听状态并清空时间戳校验记录
91
- * @param {object} cache 缓存项
92
- * @returns {void}
93
- * @private
94
- */
95
- _markWatched(cache) {
96
- cache.watched = true;
97
- cache.dir_mtimes = [];
98
- cache.file_mtimes = [];
99
- }
100
-
101
- /**
102
- * 订阅监听器的全部事件类型
103
- * @param {object} watcher mm_watcher 监听器
104
- * @param {string} key 缓存键
105
- * @param {object} state 批次累积状态
106
- * @returns {void}
107
- * @private
108
- */
109
- _subscribe(watcher, key, state) {
110
- watcher.on('add', (rel_path) => this._onEvent(key, 'add', rel_path, state));
111
- watcher.on('set', (rel_path) => this._onEvent(key, 'set', rel_path, state));
112
- watcher.on('del', (rel_path) => this._onEvent(key, 'del', rel_path, state));
113
- watcher.on('reload', () => this._onEvent(key, 'reload', '', state));
114
- }
115
-
116
- /**
117
- * 处理单个监听事件,累积后于微任务统一提交
118
- * @param {string} key 缓存键
119
- * @param {string} type 事件类型,add/set/del/reload
120
- * @param {string} rel_path 相对路径
121
- * @param {object} state 批次累积状态
122
- * @returns {void}
123
- * @private
124
- */
125
- _onEvent(key, type, rel_path, state) {
126
- if (type === 'reload') {
127
- state.need_refresh = true;
128
- } else {
129
- const cache = cache_store.readCache(key);
130
- if (!cache_updater.applyChange(cache, { type, path: rel_path }, state.changes)) {
131
- state.need_refresh = true;
132
- }
133
- }
134
-
135
- if (!state.scheduled) {
136
- state.scheduled = true;
137
- queueMicrotask(() => this._process(key));
138
- }
139
- }
140
-
141
- /**
142
- * 提交批次内累积的变更:必要时全量刷新并同步全部监听实例
143
- * @param {string} key 缓存键
144
- * @returns {void}
145
- * @private
146
- */
147
- _process(key) {
148
- const state = this.#states.get(key);
149
- if (!state) return;
150
- state.scheduled = false;
151
-
152
- const need_refresh = state.need_refresh;
153
- const changes = state.changes;
154
- state.need_refresh = false;
155
- state.changes = [];
156
-
157
- if (!changes.length && !need_refresh) return;
158
-
159
- if (need_refresh) {
160
- const cache = cache_store.readCache(key);
161
- cache_updater.refreshCache(cache, changes);
162
- }
163
- instance_registry.sync(key, changes);
164
- }
165
- }
166
-
167
- const watch_manager = new WatchManager();
168
-
169
- /* 导出单例 */
170
- module.exports = watch_manager;
package/lib/watcher.js DELETED
@@ -1,119 +0,0 @@
1
- 'use strict';
2
-
3
- const instance_registry = require('./instance_registry');
4
- const watch_manager = require('./watch_manager');
5
- const { SYNC, NOTIFY } = require('./symbols');
6
-
7
- /**
8
- * 目录监听器
9
- * @description 代表 Scanner 实例的监听身份:登记到实例登记表、绑定目录监听、接收缓存同步并触发变更回调
10
- */
11
- class Watcher {
12
- /** 本次监听对应的缓存键 */
13
- #cache_key;
14
- /** 回填扫描结果的回调,由 Scanner 注入 */
15
- #fill;
16
- /** 外部变更回调 */
17
- #callback = null;
18
-
19
- /**
20
- * 创建监听器实例
21
- * @param {string} cache_key 缓存键
22
- * @param {(items: Array<object>, dirs: Array<string>) => void} fill 回填扫描结果的回调
23
- */
24
- constructor(cache_key, fill) {
25
- this.#cache_key = cache_key;
26
- this.#fill = fill;
27
- }
28
-
29
- /**
30
- * 开启监听,重复调用只更新回调
31
- * @description 绑定失败时自动注销登记并清空回调,静默降级为未监听
32
- * @param {(changes: Array<{ type: string, key: string, item: object }>) => void} [callback] 变更回调,type 为 add/change/unlink
33
- * @returns {boolean} 监听是否可用
34
- */
35
- start(callback) {
36
- if (typeof callback === 'function') this.#callback = callback;
37
- if (this.active) return true;
38
-
39
- instance_registry.add(this.#cache_key, this);
40
- if (!watch_manager.bind(this.#cache_key)) {
41
- this.#stop();
42
- this.#callback = null;
43
- return false;
44
- }
45
- return true;
46
- }
47
-
48
- /**
49
- * 关闭监听并清空变更回调
50
- * @returns {void}
51
- */
52
- dispose() {
53
- this.#callback = null;
54
- this.#stop();
55
- }
56
-
57
- /**
58
- * 判断当前监听器是否处于监听状态
59
- * @returns {boolean} 已登记返回 true
60
- */
61
- get active() {
62
- return instance_registry.has(this.#cache_key, this);
63
- }
64
-
65
- /**
66
- * 注销本监听器登记,最后一个注销时解绑目录监听
67
- * @returns {void}
68
- */
69
- #stop() {
70
- if (instance_registry.del(this.#cache_key, this)) {
71
- watch_manager.unbind(this.#cache_key);
72
- }
73
- }
74
-
75
- /**
76
- * 接收监听器同步的最新条目并回填
77
- * @param {Array<object>} items 缓存中的条目
78
- * @param {Array<string>} dirs 缓存中的目录列表
79
- * @returns {void}
80
- */
81
- [SYNC](items, dirs) {
82
- this.#fill(items, dirs);
83
- }
84
-
85
- /**
86
- * 把变更列表交给外部回调
87
- * @param {Array<{ type: string, key: string, item: object }>} changes 变更列表
88
- * @returns {void}
89
- */
90
- [NOTIFY](changes) {
91
- if (!this.#callback || !changes.length) return;
92
- try {
93
- this.#callback(changes.map((one) => ({ ...one, item: { ...one.item } })));
94
- } catch (error) {
95
- console.error('[scanner] watch 回调执行失败:', error);
96
- }
97
- }
98
-
99
- /**
100
- * 把缓存的最新条目与变更同步到指定缓存键下的全部监听器
101
- * @param {string} cache_key 缓存键
102
- * @param {Array<object>} changes 变更列表
103
- * @returns {void}
104
- */
105
- static sync(cache_key, changes) {
106
- instance_registry.sync(cache_key, changes);
107
- }
108
-
109
- /**
110
- * 关闭全部目录监听并清空监听器登记
111
- * @returns {void}
112
- */
113
- static closeAll() {
114
- watch_manager.closeAll();
115
- }
116
- }
117
-
118
- /* 导出类 */
119
- module.exports = Watcher;