1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | Object.defineProperty(exports, "__esModule", { value: true });
|
6 | const path_1 = __importDefault(require("path"));
|
7 | const chokidar_1 = __importDefault(require("chokidar"));
|
8 | class Watcher {
|
9 | constructor(options) {
|
10 | const { onReady, onTrigger, onCollectFiles, onError } = options;
|
11 | this.onReady = onReady;
|
12 | this.onTrigger = onTrigger;
|
13 | this.onCollectFiles = onCollectFiles;
|
14 | this.onError = onError;
|
15 | }
|
16 | async watch() {
|
17 |
|
18 | const files = await this.onCollectFiles();
|
19 |
|
20 | this.watcher = chokidar_1.default.watch(files, {
|
21 | persistent: true,
|
22 | ignoreInitial: true,
|
23 | atomic: 500,
|
24 | });
|
25 |
|
26 | const watcher = this.watcher;
|
27 | const onTrigger = this.onTrigger;
|
28 | const onCollectFiles = this.onCollectFiles;
|
29 | const onError = this.onError;
|
30 | const onReady = this.onReady;
|
31 | watcher.on('ready', async () => {
|
32 |
|
33 | onReady();
|
34 |
|
35 | await onTrigger(undefined);
|
36 | });
|
37 | watcher.on('error', (error) => {
|
38 | onError(error);
|
39 | });
|
40 | watcher.on('all', async (_, file) => {
|
41 | try {
|
42 |
|
43 | const newFiles = await onCollectFiles();
|
44 |
|
45 | let watchedFiles = [];
|
46 | const watched = watcher.getWatched();
|
47 | watchedFiles = Object.keys(watched).reduce((files, dirname) => watched[dirname].reduce((files, filename) => {
|
48 | files.push(path_1.default.resolve(path_1.default.join(dirname, filename)));
|
49 | return files;
|
50 | }, files), []);
|
51 | const diff = (xs, ys) => ({
|
52 | added: ys.filter((y) => !xs.includes(y)),
|
53 | removed: xs.filter((x) => !ys.includes(x)),
|
54 | });
|
55 |
|
56 |
|
57 | const filesDiff = diff(watchedFiles, newFiles);
|
58 | watcher.unwatch(filesDiff.removed);
|
59 | watcher.add(filesDiff.added);
|
60 |
|
61 | await onTrigger(file);
|
62 | }
|
63 | catch (e) {
|
64 | onError(e);
|
65 | }
|
66 | });
|
67 | }
|
68 | close() {
|
69 | if (this.watcher !== undefined) {
|
70 | this.watcher.close();
|
71 | }
|
72 | }
|
73 | }
|
74 | exports.default = Watcher;
|