event-storage 1.3.2 → 1.3.4

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/index.d.ts CHANGED
@@ -4,9 +4,16 @@ import { Readable } from 'node:stream';
4
4
  export type EventMatcher = Record<string, unknown> | ((payload: any, metadata?: any) => boolean);
5
5
  export type EventPredicate = EventMatcher | ((buffer: Buffer) => boolean) | null;
6
6
 
7
+ export interface IndexEntry {
8
+ number: number;
9
+ position: number;
10
+ size: number;
11
+ partition: number;
12
+ }
7
13
  export interface StreamIndexInfo {
8
14
  length: number;
9
15
  metadata?: Record<string, unknown> | null;
16
+ lastEntry: IndexEntry;
10
17
  }
11
18
 
12
19
  export interface StreamInfo {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "event-storage",
3
- "version": "1.3.2",
3
+ "version": "1.3.4",
4
4
  "type": "module",
5
5
  "description": "An optimized embedded event store for node.js",
6
6
  "keywords": [
@@ -27,7 +27,7 @@
27
27
  "types": "./index.d.ts",
28
28
  "scripts": {
29
29
  "test": "c8 --reporter=lcov --reporter=text mocha test/*.spec.js",
30
- "test:grep": "c8 --reporter=lcov --reporter=text mocha test/*.spec.js --grep",
30
+ "test:grep": "mocha test/*.spec.js --grep",
31
31
  "coverage": "c8 report --reporter=text-lcov | coveralls"
32
32
  },
33
33
  "files": [
@@ -57,7 +57,7 @@
57
57
  }
58
58
  ],
59
59
  "engines": {
60
- "node": ">=18.0"
60
+ "node": ">=20.0"
61
61
  },
62
62
  "dependencies": {
63
63
  "mkdirp": "^3.0.1"
package/src/EventStore.js CHANGED
@@ -7,7 +7,7 @@ import Storage, { ReadOnly as ReadOnlyStorage, LOCK_THROW, LOCK_RECLAIM } from '
7
7
  import Index from './Index.js';
8
8
  import Consumer from './Consumer.js';
9
9
  import { assert, getPropertyAtPath } from './utils/util.js';
10
- import { ensureDirectory, scanForFiles } from './utils/fsUtil.js';
10
+ import { ensureDirectory, resolvePath, scanForFiles } from './utils/fsUtil.js';
11
11
  import { buildTypeMatcherFn } from './utils/metadataUtil.js';
12
12
  import { fixCommitArgumentTypes, parseStreamFromIndexName, normalizePredicateRaw } from './utils/apiHelpers.js';
13
13
 
@@ -90,7 +90,7 @@ class EventStore extends events.EventEmitter {
90
90
  this.typeMatcherFn = null;
91
91
  }
92
92
 
93
- this.storageDirectory = path.resolve(config.storageDirectory || /* istanbul ignore next */ './data');
93
+ this.storageDirectory = resolvePath(config.storageDirectory || /* istanbul ignore next */ './data');
94
94
  let defaults = {
95
95
  dataDirectory: this.storageDirectory,
96
96
  indexDirectory: config.streamsDirectory || path.join(this.storageDirectory, 'streams'),
@@ -130,7 +130,7 @@ class EventStore extends events.EventEmitter {
130
130
  */
131
131
  initialize(storeName, storageConfig) {
132
132
  this.storageConfig = storageConfig;
133
- this.streamsDirectory = path.resolve(storageConfig.indexDirectory);
133
+ this.streamsDirectory = resolvePath(storageConfig.indexDirectory);
134
134
  this.storeName = storeName;
135
135
  this.consumers = new Map();
136
136
 
@@ -139,7 +139,9 @@ class EventStore extends events.EventEmitter {
139
139
  : new Storage(storeName, storageConfig);
140
140
 
141
141
  this.mountStorage(storage, () => {
142
- this.checkUnfinishedCommits();
142
+ if (storageConfig.readOnly !== true) {
143
+ this.checkUnfinishedCommits();
144
+ }
143
145
  this.emit('ready');
144
146
  });
145
147
  }
@@ -653,12 +655,6 @@ class EventStore extends events.EventEmitter {
653
655
  assert(stream in this.streams, `Stream "${stream}" does not exist.`);
654
656
  }
655
657
 
656
- if (streamNames.length === 1) {
657
- const stream = new EventStream(streamNames[0], this, minRevision, maxRevision, predicate, raw);
658
- stream.name = streamName;
659
- return stream;
660
- }
661
-
662
658
  return new JoinEventStream(streamName, streamNames, this, minRevision, maxRevision, predicate, raw);
663
659
  }
664
660
 
@@ -193,15 +193,15 @@ class EventStream extends stream.Readable {
193
193
  * @returns {Array<object>}
194
194
  */
195
195
  get events() {
196
- if (this._events instanceof Array) {
197
- return this._events;
196
+ if (this.cachedEvents instanceof Array) {
197
+ return this.cachedEvents;
198
198
  }
199
- this._events = [];
199
+ this.cachedEvents = [];
200
200
  let next;
201
201
  while ((next = this.next()) !== false) {
202
- this._events.push(next.payload);
202
+ this.cachedEvents.push(next.payload);
203
203
  }
204
- return this._events;
204
+ return this.cachedEvents;
205
205
  }
206
206
 
207
207
  /**
@@ -242,7 +242,7 @@ class EventStream extends stream.Readable {
242
242
  */
243
243
  reset() {
244
244
  this._iterator = null;
245
- this._events = null;
245
+ this.cachedEvents = null;
246
246
  return this;
247
247
  }
248
248
 
@@ -259,7 +259,7 @@ class EventStream extends stream.Readable {
259
259
  this.predicate = predicate || null;
260
260
  this.rawMatcher = null;
261
261
  this._iterator = null;
262
- this._events = null;
262
+ this.cachedEvents = null;
263
263
  return this;
264
264
  }
265
265
 
@@ -13,6 +13,19 @@ class ReadOnlyIndex extends watchesFile(ReadableIndex) {
13
13
  */
14
14
  constructor(name, options) {
15
15
  super(name, options);
16
+ this.syncOnMissingWatchFilename = !!options?.syncOnMissingWatchFilename;
17
+ }
18
+
19
+ /**
20
+ * @private
21
+ * @param {string} filename
22
+ * @returns {boolean}
23
+ */
24
+ watchFileFilter(filename) {
25
+ if (!filename) {
26
+ return this.syncOnMissingWatchFilename && this.readFileLength() !== this.data.length;
27
+ }
28
+ return filename === this.name;
16
29
  }
17
30
 
18
31
  /**
@@ -1,9 +1,9 @@
1
1
  import fs from 'fs';
2
- import path from 'path';
3
2
  import events from 'events';
4
3
  import Entry, { assertValidEntryClass } from '../IndexEntry.js';
5
4
  import { assert, wrapAndCheck, binarySearch } from '../utils/util.js';
6
5
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
6
+ import { resolvePath } from "../utils/fsUtil.js";
7
7
 
8
8
  // node-event-store-index V01
9
9
  const HEADER_MAGIC = "nesidx01";
@@ -69,7 +69,7 @@ class ReadableIndex extends events.EventEmitter {
69
69
  this.fileMode = 'r';
70
70
  this.EntryClass = options.EntryClass;
71
71
  this.dataDirectory = options.dataDirectory;
72
- this.fileName = path.resolve(options.dataDirectory, this.name);
72
+ this.fileName = resolvePath(options.dataDirectory, this.name);
73
73
  this.readBuffer = Buffer.allocUnsafe(Math.max(options.EntryClass.size, options.writeBufferSize > 0 ? options.writeBufferSize : 4096));
74
74
 
75
75
  if (options.metadata) {
@@ -128,6 +128,7 @@ class ReadableIndex extends events.EventEmitter {
128
128
  stat.size -= this.readMetadata();
129
129
  assert(stat.size >= 0, 'Invalid index file!');
130
130
 
131
+ this.crtime = stat.birthtimeMs;
131
132
  const length = Math.floor(stat.size / this.EntryClass.size);
132
133
  assert(stat.size === length * this.EntryClass.size, 'Index file is corrupt!', CorruptedIndexErrorFactory(length));
133
134
 
@@ -34,9 +34,14 @@ class JoinEventStream extends EventStream {
34
34
  if (!streamIndex || streamIndex.length === 0) {
35
35
  return emptyIterator;
36
36
  }
37
- const from = streamIndex.find(this.minRevision, this.minRevision <= this.maxRevision);
38
- const until = streamIndex.find(this.maxRevision, this.minRevision > this.maxRevision);
39
- if (from === 0 || until === 0) {
37
+ const ascending = this.minRevision <= this.maxRevision;
38
+ const from = streamIndex.find(this.minRevision, ascending);
39
+ const until = streamIndex.find(this.maxRevision, !ascending);
40
+ if (
41
+ from === 0 ||
42
+ until === 0 ||
43
+ (ascending ? from > until : from < until)
44
+ ) {
40
45
  // find() returns 0 when the requested revision is outside the stream's range
41
46
  // (e.g. minRevision > all entries, or maxRevision < all entries).
42
47
  return emptyIterator;
@@ -2,6 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import events from 'events';
4
4
  import { assert, alignTo, hash, binarySearch } from '../utils/util.js';
5
+ import { resolvePath } from "../utils/fsUtil.js";
5
6
 
6
7
 
7
8
 
@@ -50,7 +51,7 @@ class ReadablePartition extends events.EventEmitter {
50
51
  readBufferSize: DEFAULT_READ_BUFFER_SIZE
51
52
  };
52
53
  config = Object.assign(defaults, config);
53
- this.dataDirectory = path.resolve(config.dataDirectory);
54
+ this.dataDirectory = resolvePath(config.dataDirectory);
54
55
 
55
56
  this.name = name;
56
57
  this.id = ReadablePartition.idFor(name);
@@ -155,6 +156,7 @@ class ReadablePartition extends events.EventEmitter {
155
156
  */
156
157
  readFileSize() {
157
158
  const stat = fs.statSync(this.fileName);
159
+ this.crtime = stat.birthtimeMs;
158
160
  return stat.size - this.headerSize;
159
161
  }
160
162
 
@@ -1,7 +1,8 @@
1
1
  import ReadableStorage from './ReadableStorage.js';
2
- import ReadablePartition from '../Partition/ReadablePartition.js';
3
2
  import Watcher from '../Watcher.js';
4
3
 
4
+ const DEFAULT_SCAN_DELAY_MS = 10;
5
+
5
6
  /**
6
7
  * An append-only storage with highly performant positional range scans.
7
8
  * It's highly optimized for an event-store and hence does not support compaction or data-rewrite, nor any querying
@@ -23,7 +24,10 @@ class ReadOnlyStorage extends ReadableStorage {
23
24
  * @returns {boolean}
24
25
  */
25
26
  storageFilesFilter(filename) {
26
- return !filename.endsWith('.branch') && filename.substring(0, this.storageFile.length) === this.storageFile;
27
+ if (!filename) {
28
+ return true;
29
+ }
30
+ return !filename.endsWith('.branch') && (filename === this.storageFile || filename.substring(0, this.storageFile.length + 1) === this.storageFile + '.');
27
31
  }
28
32
 
29
33
  /**
@@ -39,15 +43,43 @@ class ReadOnlyStorage extends ReadableStorage {
39
43
  if (!this.watcher) {
40
44
  this.watcher = new Watcher([this.dataDirectory, this.indexDirectory], this.storageFilesFilter);
41
45
  this.watcher.on('rename', this.onStorageFileChanged);
46
+ // Emit change events without filename as a signal to resync
47
+ this.watcher.on('change', (filename) => !filename && this.scheduleScan());
42
48
  }
43
49
  return super.open(callback);
44
50
  }
45
51
 
52
+ /**
53
+ * Schedule a fresh scan of the filesystem to get the ReadOnly instance in sync.
54
+ * Scheduling will be throttled so multiple calls will not cause multiple scan operations.
55
+ * Note though that the callback will not be deduplicated, so calling this repeatedly with the same callback will
56
+ * lead to this callback being executed multiple times once the scan is finished.
57
+ *
58
+ * @param {function} [callback] If provided, will be added to the callbacks invoked after the next full scan.
59
+ * @param {number} [time=SCAN_DELAY_MS] The delay in ms to schedule the scan for
60
+ */
61
+ scheduleScan(callback, time = DEFAULT_SCAN_DELAY_MS) {
62
+ if (typeof callback === 'function') {
63
+ this.onScanFinished = this.onScanFinished || [];
64
+ this.onScanFinished.push(callback);
65
+ }
66
+ this.scanSchedule = this.scanSchedule || setTimeout(() =>
67
+ this.scanFiles(() => {
68
+ this.scanSchedule = null;
69
+ const callbacks = this.onScanFinished || [];
70
+ this.onScanFinished = [];
71
+ callbacks.forEach(callback => callback());
72
+ }), typeof callback === 'number' ? callback : time);
73
+ }
74
+
46
75
  /**
47
76
  * @private
48
77
  * @param {string} filename
49
78
  */
50
79
  onStorageFileChanged(filename) {
80
+ if (!filename) {
81
+ return;
82
+ }
51
83
  if (filename.endsWith('.index')) {
52
84
  const indexName = filename.substring(this.storageFile.length + 1, filename.length - 6);
53
85
  // New indexes are not automatically opened in the reader
@@ -55,12 +87,7 @@ class ReadOnlyStorage extends ReadableStorage {
55
87
  return;
56
88
  }
57
89
 
58
- const partitionId = ReadablePartition.idFor(filename);
59
- if (!this.partitions.has(partitionId)) {
60
- const partition = this.createPartition(filename, this.partitionConfig);
61
- this.partitions.add(partition.id, partition);
62
- this.emit('partition-created', partition.id);
63
- }
90
+ this.registerPartitionFile(filename);
64
91
  }
65
92
 
66
93
  /**
@@ -71,6 +98,11 @@ class ReadOnlyStorage extends ReadableStorage {
71
98
  * @returns void
72
99
  */
73
100
  close() {
101
+ if (this.scanSchedule) {
102
+ clearTimeout(this.scanSchedule);
103
+ this.scanSchedule = null;
104
+ }
105
+ this.onScanFinished = [];
74
106
  if (this.watcher) {
75
107
  this.watcher.close();
76
108
  this.watcher = null;
@@ -97,14 +129,7 @@ class ReadOnlyStorage extends ReadableStorage {
97
129
  if (entries === false) {
98
130
  return;
99
131
  }
100
- for (let entry of entries) {
101
- const document = this.readFrom(entry.partition, entry.position, entry.size);
102
- if (index === this.index) {
103
- this.emit('wrote', document, entry, entry.position);
104
- } else {
105
- this.emit('index-add', indexShortName, entry.number, document);
106
- }
107
- }
132
+ this.processAppendedEntries(index, indexShortName, entries);
108
133
  });
109
134
  index.on('truncate', (prevLength, newLength) => {
110
135
  if (index === this.index) {
@@ -113,6 +138,53 @@ class ReadOnlyStorage extends ReadableStorage {
113
138
  });
114
139
  return { index };
115
140
  }
141
+
142
+ /**
143
+ * Emit `'wrote'` / `'index-add'` for each appended index entry.
144
+ *
145
+ * If an entry references a partition that has not been registered yet (the partition-creation
146
+ * watch event is still pending), the remaining entries are re-processed on the next tick instead
147
+ * of throwing a hard `Partition #… does not exist.` error out of the synchronous emit path.
148
+ *
149
+ * @private
150
+ * @param {ReadableIndex} index
151
+ * @param {string} indexShortName
152
+ * @param {IndexEntry[]} entries
153
+ * @param {number} [startIndex] The entry offset to resume from on a retry.
154
+ */
155
+ processAppendedEntries(index, indexShortName, entries, startIndex = 0) {
156
+ for (let i = startIndex; i < entries.length; i++) {
157
+ const entry = entries[i];
158
+ if (!this.partitions.has(entry.partition)) {
159
+ this.scheduleScan(() => {
160
+ this.processAppendedEntries(index, indexShortName, entries, i);
161
+ });
162
+ return;
163
+ }
164
+ this.emitAppendedEntry(index, indexShortName, entry);
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Read a single appended entry and emit the corresponding event.
170
+ * A read failure is surfaced as an `'error'` event (when observed) rather than crashing the reader.
171
+ * @private
172
+ */
173
+ emitAppendedEntry(index, indexShortName, entry) {
174
+ let document;
175
+ try {
176
+ document = this.readFrom(entry.partition, entry.position, entry.size);
177
+ } catch (error) {
178
+ /* c8 ignore next */
179
+ this.emit('error', error);
180
+ return;
181
+ }
182
+ if (index === this.index) {
183
+ this.emit('wrote', document, entry, entry.position);
184
+ } else {
185
+ this.emit('index-add', indexShortName, entry.number, document);
186
+ }
187
+ }
116
188
  }
117
189
 
118
190
  export default ReadOnlyStorage;
@@ -4,11 +4,12 @@ import events from 'events';
4
4
  import { ReadOnly as ReadOnlyPartition } from '../Partition.js';
5
5
  import { ReadOnly as ReadOnlyIndex } from '../Index.js';
6
6
  import { assert, wrapAndCheck, iterate, kWayMerge } from '../utils/util.js';
7
- import { scanForFiles } from '../utils/fsUtil.js';
7
+ import { resolvePath, scanForFiles } from '../utils/fsUtil.js';
8
8
  import { createHmac, matches, buildMetadataForMatcher } from '../utils/metadataUtil.js';
9
9
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
10
10
  import IndexMatcher from '../IndexMatcher.js';
11
11
  import PartitionPool from '../PartitionPool.js';
12
+ import ReadablePartition from "../Partition/ReadablePartition.js";
12
13
 
13
14
  const DEFAULT_READ_BUFFER_SIZE = 4 * 1024;
14
15
 
@@ -78,7 +79,7 @@ class ReadableStorage extends events.EventEmitter {
78
79
 
79
80
  this.hmac = createHmac(config.hmacSecret);
80
81
 
81
- this.dataDirectory = path.resolve(config.dataDirectory);
82
+ this.dataDirectory = resolvePath(config.dataDirectory);
82
83
 
83
84
  const partitionDefaults = { readBufferSize: DEFAULT_READ_BUFFER_SIZE };
84
85
  this.partitionConfig = Object.assign(partitionDefaults, config);
@@ -120,13 +121,13 @@ class ReadableStorage extends events.EventEmitter {
120
121
  * @returns void
121
122
  */
122
123
  initializeIndexes(config) {
123
- this.indexDirectory = path.resolve(config.indexDirectory || this.dataDirectory);
124
+ this.indexDirectory = resolvePath(config.indexDirectory || this.dataDirectory);
124
125
 
125
126
  this.indexOptions = config.indexOptions;
126
127
  this.indexOptions.dataDirectory = this.indexDirectory;
127
128
  // Safety precaution to prevent accidentally restricting main index
128
129
  delete this.indexOptions.matcher;
129
- const { index } = this.createIndex(config.indexFile, this.indexOptions);
130
+ const { index } = this.createIndex(config.indexFile, Object.assign({}, this.indexOptions, { syncOnMissingWatchFilename: true }));
130
131
  this.index = index;
131
132
  this.secondaryIndexes = {};
132
133
  this.readonlyIndexes = {};
@@ -143,6 +144,24 @@ class ReadableStorage extends events.EventEmitter {
143
144
  return this.index.length;
144
145
  }
145
146
 
147
+ /**
148
+ * Register a partition by its relative file name if it is not already known.
149
+ * Shared by the file-watch path and the initial scan so both stay consistent.
150
+ *
151
+ * @protected
152
+ * @param {string} filename
153
+ * @returns {number} The id of the (now registered) partition.
154
+ */
155
+ registerPartitionFile(filename) {
156
+ const partitionId = ReadablePartition.idFor(filename);
157
+ if (!this.partitions.has(partitionId)) {
158
+ const partition = this.createPartition(filename, this.partitionConfig);
159
+ this.partitions.add(partition.id, partition);
160
+ this.emit('partition-created', partition.id);
161
+ }
162
+ return partitionId;
163
+ }
164
+
146
165
  /**
147
166
  * Scan partitions and secondary index files; emit 'index-created' for each found index.
148
167
  * @param {function} done Called when both scans finish.
@@ -152,8 +171,7 @@ class ReadableStorage extends events.EventEmitter {
152
171
  const partitionPattern = new RegExp(`^(${escaped}.*)$`);
153
172
  scanForFiles(this.dataDirectory, partitionPattern, (file) => {
154
173
  if (file.endsWith('.index') || file.endsWith('.branch') || file.endsWith('.lock')) return;
155
- const partition = this.createPartition(file, this.partitionConfig);
156
- this.partitions.add(partition.id, partition);
174
+ this.registerPartitionFile(file);
157
175
  }, (partErr) => {
158
176
  /* c8 ignore next */
159
177
  if (partErr) throw partErr;
@@ -167,7 +185,9 @@ class ReadableStorage extends events.EventEmitter {
167
185
  }
168
186
  const indexPattern = new RegExp(`^${escaped}\\.(.+)\\.index$`);
169
187
  scanForFiles(this.indexDirectory, indexPattern, (name) => {
170
- this.emit('index-created', name);
188
+ if (!(name in this.secondaryIndexes)) {
189
+ this.emit('index-created', name);
190
+ }
171
191
  }, (indexErr) => {
172
192
  // The directory could disappear between existsSync and readdir (e.g. test cleanup).
173
193
  /* c8 ignore next */
@@ -66,11 +66,12 @@ class WritableStorage extends ReadableStorage {
66
66
  }
67
67
 
68
68
  /**
69
- * @inheritDoc
70
69
  * Acquires the write lock synchronously.
71
70
  * For LOCK_RECLAIM, removes any orphaned lock before trying to acquire our own; torn-write
72
71
  * repair runs after the primary index is open, before `'opened'` is emitted.
73
72
  *
73
+ * @param {function(): void} [callback] Called after indexes open, before `'opened'` is emitted.
74
+ * Can be used as a synchronous alternative to listening to the `'opened'` event.
74
75
  * @returns {boolean}
75
76
  * @throws {StorageLockedError} If this storage is locked by another process.
76
77
  */
package/src/Watcher.js CHANGED
@@ -2,6 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import events from 'events';
4
4
  import { assert } from './utils/util.js';
5
+ import { isSameOrParentDirectory } from "./utils/fsUtil.js";
5
6
 
6
7
  /** @type {Map<string, DirectoryWatcher>} */
7
8
  const directoryWatchers = new Map();
@@ -10,7 +11,91 @@ const directoryWatchers = new Map();
10
11
  * A reference counting singleton nodejs watcher for directories.
11
12
  * Emits events 'change' and 'rename' with the file name as argument.
12
13
  */
13
- class DirectoryWatcher extends events.EventEmitter {
14
+ class DirectoryWatcher {
15
+
16
+ /**
17
+ * Register a handler with optional filename resolver.
18
+ *
19
+ * @param {function(string, string): void} handler
20
+ * @param {function(string, string): string|null} [filenameResolver]
21
+ */
22
+ registerHandler(handler, filenameResolver = null) {
23
+ this.subscriptions.set(handler, typeof filenameResolver === 'function' ? filenameResolver : null);
24
+ }
25
+
26
+ /**
27
+ * Unregister a previously added handler.
28
+ *
29
+ * @param {function(string, string): void} handler
30
+ */
31
+ unregisterHandler(handler) {
32
+ this.subscriptions.delete(handler);
33
+ }
34
+
35
+ /**
36
+ * Dispatch an fs event to matching subscribers.
37
+ *
38
+ * @private
39
+ * @param {'change'|'rename'} eventType
40
+ * @param {string} filename
41
+ */
42
+ dispatch(eventType, filename) {
43
+ for (const [handler, filenameResolver] of this.subscriptions) {
44
+ const resolvedFilename = filenameResolver ? filenameResolver(filename, eventType) : filename;
45
+ if (resolvedFilename === null || resolvedFilename === undefined) {
46
+ continue;
47
+ }
48
+ handler(eventType, resolvedFilename);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Normalize fs.watch filenames to be relative to the watched directory.
54
+ * On Windows recursive watches may yield absolute `\\?\` names or directory names.
55
+ *
56
+ * @private
57
+ * @param {string|Buffer|null} filename
58
+ * @returns {string}
59
+ */
60
+ normalizeFilename(filename) {
61
+ if (!filename) return '';
62
+ if (Buffer.isBuffer(filename)) {
63
+ filename = filename.toString();
64
+ }
65
+ if (typeof filename !== 'string' || filename.length === 0) {
66
+ return '';
67
+ }
68
+
69
+ const stripped = filename
70
+ .replace(/^\\\\\?\\UNC\\/i, '\\\\')
71
+ .replace(/^\\\\\?\\/, '');
72
+ filename = path.normalize(stripped);
73
+
74
+ if (path.isAbsolute(filename)) {
75
+ filename = path.relative(this.directory, filename);
76
+ }
77
+ if (!filename || filename === '.') {
78
+ return '';
79
+ }
80
+ return filename.replace(/\\/g, '/');
81
+ }
82
+
83
+ /**
84
+ * Forward fs.watch events with normalized filenames.
85
+ *
86
+ * @private
87
+ * @param {string} eventType
88
+ * @param {string|Buffer|null} filename
89
+ */
90
+ onFsEvent(eventType, filename) {
91
+ const normalized = this.normalizeFilename(filename);
92
+ if (eventType === 'rename' && !filename) {
93
+ // Close if the watched directory was removed
94
+ this.close();
95
+ return;
96
+ }
97
+ this.dispatch(eventType, normalized);
98
+ }
14
99
 
15
100
  /**
16
101
  * @param {string} directory
@@ -18,20 +103,22 @@ class DirectoryWatcher extends events.EventEmitter {
18
103
  * @returns {DirectoryWatcher}
19
104
  */
20
105
  constructor(directory, options = {}) {
21
- directory = path.normalize(directory);
106
+ const watchOptions = Object.assign({ recursive: true }, options);
107
+ const watcherKey = `${directory}|r:${watchOptions.recursive}`;
22
108
 
23
- if (directoryWatchers.has(directory)) {
24
- const watcher = directoryWatchers.get(directory);
109
+ if (directoryWatchers.has(watcherKey)) {
110
+ const watcher = directoryWatchers.get(watcherKey);
25
111
  watcher.references++;
26
112
  return watcher;
27
113
  }
28
114
  assert(fs.existsSync(directory), `Can not watch a non-existing directory "${directory}".`);
29
115
  assert(fs.statSync(directory).isDirectory(), `Can only watch directories, but "${directory}" is none.`);
30
- super();
31
- this.setMaxListeners(1000);
32
- directoryWatchers.set(directory, this);
116
+ directoryWatchers.set(watcherKey, this);
117
+ this.watcherKey = watcherKey;
33
118
  this.directory = directory;
34
- this.watcher = fs.watch(directory, Object.assign({ persistent: false }, options), this.emit.bind(this));
119
+ this.subscriptions = new Map();
120
+ this.onFsEvent = this.onFsEvent.bind(this);
121
+ this.watcher = fs.watch(directory, watchOptions, this.onFsEvent);
35
122
  this.references = 1;
36
123
  }
37
124
 
@@ -44,91 +131,150 @@ class DirectoryWatcher extends events.EventEmitter {
44
131
  if (this.references === 0 && this.watcher) {
45
132
  this.watcher.close();
46
133
  this.watcher = null;
47
- directoryWatchers.delete(this.directory);
134
+ directoryWatchers.delete(this.watcherKey);
48
135
  }
49
136
  }
50
137
 
51
138
  }
52
139
 
140
+ const VALID_WATCH_EVENT_TYPES = ['change', 'rename'];
141
+
53
142
  /**
54
143
  * A watcher for a single file or a directory, with the possibility to provide a filter method for file names to watch.
55
144
  */
56
- class Watcher {
145
+ class Watcher extends events.EventEmitter {
146
+
147
+ /**
148
+ * Remove redundant nested directories so each tree is watched only once.
149
+ *
150
+ * @private
151
+ * @param {string[]} directories
152
+ * @param {boolean} recursive
153
+ * @returns {[string[], string[]]} Tuple of [watchedDirectories, removedRelativePrefixes]
154
+ */
155
+ static deduplicateDirectories(directories, recursive = true) {
156
+ const normalized = [...new Set(directories)];
157
+ if (!recursive) {
158
+ return [normalized, []];
159
+ }
160
+ normalized.sort((a, b) => a.length - b.length);
161
+ const deduplicated = [];
162
+ const removedRelativePrefixes = new Set();
163
+ for (const directory of normalized) {
164
+ const parent = deduplicated.find(current => isSameOrParentDirectory(current, directory));
165
+ if (parent) {
166
+ const relative = path.relative(parent, directory).replace(/\\/g, '/');
167
+ if (relative && relative !== '.') {
168
+ removedRelativePrefixes.add(relative);
169
+ }
170
+ continue;
171
+ }
172
+ deduplicated.push(directory);
173
+ }
174
+ return [deduplicated, [...removedRelativePrefixes]];
175
+ }
176
+
177
+ /**
178
+ * Resolve a filename to a path relative to the longest matching watched prefix.
179
+ *
180
+ * @private
181
+ * @param {string} filename
182
+ * @returns {string}
183
+ */
184
+ resolveRelativeFilename(filename) {
185
+ filename = path.normalize(filename).replace(/\\/g, '/');
186
+ for (const prefix of this.relativePrefixes) {
187
+ if (filename === prefix) {
188
+ return '';
189
+ }
190
+ const withSeparator = prefix + '/';
191
+ if (filename.startsWith(withSeparator)) {
192
+ return filename.slice(withSeparator.length);
193
+ }
194
+ }
195
+ return filename;
196
+ }
197
+
198
+ /**
199
+ * Resolve the final filename used for matching and emitting.
200
+ * Returns `null` when the filename is filtered out.
201
+ *
202
+ * @private
203
+ * @param {string} filename
204
+ * @returns {string|null}
205
+ */
206
+ resolveFilename(filename) {
207
+ if (!filename) {
208
+ if (!this.fileFilter(filename)) {
209
+ return null;
210
+ }
211
+ return this.fixedFilename || '';
212
+ }
213
+
214
+ filename = this.resolveRelativeFilename(filename);
215
+
216
+ if (!this.fileFilter(filename)) {
217
+ return null;
218
+ }
219
+ return filename;
220
+ }
57
221
 
58
222
  /**
59
223
  * @param {string|string[]} fileOrDirectory The filename or directory or list of directories to watch
60
- * @param {function(string): boolean} [fileFilter] A filter that will receive a filename and needs to return true if this watcher should be invoked. Will be ignored if the first argument is a file.
224
+ * @param {function(string): boolean} [fileFilter] A filter that will receive a filename and needs to return true if this watcher should be invoked.
225
+ * @param {object|null} [options] Internal watcher options.
226
+ * @param {boolean} [options.recursive=true] Whether directories are watched recursively.
227
+ * @param {string} [options.rootDirectory] Root directory used to relativize single-file watcher events.
61
228
  * @returns {Watcher}
62
229
  */
63
- constructor(fileOrDirectory, fileFilter = null) {
230
+ constructor(fileOrDirectory, fileFilter = null, options = null) {
231
+ super();
232
+ const watchOptions = Object.assign({ recursive: true }, options);
233
+ delete watchOptions.rootDirectory;
234
+ this.relativePrefixes = [];
64
235
  let directories;
65
236
  if (typeof fileOrDirectory === 'string') {
66
237
  directories = [fileOrDirectory];
67
238
  if (!fs.statSync(fileOrDirectory).isDirectory()) {
68
- directories = [path.dirname(fileOrDirectory)];
69
- const filename = path.basename(fileOrDirectory);
70
- fileFilter = changedFilename => changedFilename === filename;
239
+ const rootDirectory = options?.rootDirectory || path.dirname(fileOrDirectory);
240
+
241
+ directories = [rootDirectory];
242
+ this.fixedFilename = path.relative(rootDirectory, fileOrDirectory).replace(/\\/g, '/');
243
+ if (fileFilter === null) {
244
+ fileFilter = changedFilename => changedFilename === this.fixedFilename;
245
+ }
71
246
  }
72
247
  } else {
73
- directories = [...new Set(fileOrDirectory.map(path.normalize))];
248
+ this.fixedFilename = null;
249
+ const [deduplicatedDirectories, removedRelativePrefixes] = Watcher.deduplicateDirectories(fileOrDirectory, watchOptions.recursive);
250
+ directories = deduplicatedDirectories;
251
+ this.relativePrefixes = removedRelativePrefixes.sort((a, b) => b.length - a.length);
74
252
  }
75
253
 
76
- this.watchers = directories.map(dir => new DirectoryWatcher(dir));
254
+ this.watchers = directories.map(dir => new DirectoryWatcher(dir, watchOptions));
77
255
 
78
256
  if (fileFilter === null) {
79
257
  fileFilter = () => true;
80
258
  }
81
259
 
82
260
  this.fileFilter = fileFilter;
83
- this.onChange = this.onChange.bind(this);
84
- this.onRename = this.onRename.bind(this);
261
+ this.resolveFilename = this.resolveFilename.bind(this);
262
+ this.emitHandler = this.emit.bind(this);
85
263
  this.watchers.forEach(watcher => {
86
- watcher.on('change', this.onChange);
87
- watcher.on('rename', this.onRename);
264
+ watcher.registerHandler(this.emitHandler, this.resolveFilename);
88
265
  });
89
- this.handlers = { change: [], rename: [] };
90
266
  }
91
267
 
92
268
  /**
93
- * Register a new handler that is triggered if the fileFilter matches.
269
+ * Override to validate against allowed event types.
270
+ * @override
94
271
  * @param {string} eventType
95
- * @param {function(string): void} handler A handler method that should be invoked with the filename as argument
96
- * @api
97
- */
98
- on(eventType, handler) {
99
- assert(eventType in this.handlers, `Event type ${eventType} is unknown. Only 'change' and 'rename' are supported.`);
100
-
101
- this.handlers[eventType].push(handler);
102
- }
103
-
104
- /**
105
- * @private
106
- * @param {string} filename
107
- */
108
- onChange(filename) {
109
- if (this.handlers.change.length === 0) {
110
- return;
111
- }
112
- if (!filename || !this.fileFilter(filename)) {
113
- return;
114
- }
115
- this.handlers.change
116
- .forEach((handler) => handler(filename));
117
- }
118
-
119
- /**
120
- * @private
121
- * @param {string} filename
272
+ * @param {function} listener
273
+ * @returns {Watcher}
122
274
  */
123
- onRename(filename) {
124
- if (this.handlers.rename.length === 0) {
125
- return;
126
- }
127
- if (!filename || !this.fileFilter(filename)) {
128
- return;
129
- }
130
- this.handlers.rename
131
- .forEach((handler) => handler(filename));
275
+ on(eventType, listener) {
276
+ assert(VALID_WATCH_EVENT_TYPES.includes(eventType), `Event type ${eventType} is unknown. Only 'change' and 'rename' are supported.`);
277
+ return super.on(eventType, listener);
132
278
  }
133
279
 
134
280
  /**
@@ -137,12 +283,11 @@ class Watcher {
137
283
  */
138
284
  close() {
139
285
  this.watchers.forEach(watcher => {
140
- watcher.removeListener('change', this.onChange);
141
- watcher.removeListener('rename', this.onRename);
286
+ watcher.unregisterHandler(this.emitHandler);
142
287
  watcher.close();
143
288
  });
144
289
  this.watchers = [];
145
- this.handlers = { change: [], rename: [] };
290
+ this.removeAllListeners();
146
291
  }
147
292
 
148
293
  }
@@ -14,7 +14,10 @@ const WatchesFile = Base => class extends Base {
14
14
  */
15
15
  watchFile() {
16
16
  this.stopWatching();
17
- this.watcher = new Watcher(this.fileName);
17
+ const fileFilter = typeof this.watchFileFilter === 'function'
18
+ ? this.watchFileFilter.bind(this)
19
+ : null;
20
+ this.watcher = new Watcher(this.fileName, fileFilter, { rootDirectory: this.dataDirectory });
18
21
  this.watcher.on('change', this.onChange.bind(this));
19
22
  this.watcher.on('rename', this.onRename.bind(this));
20
23
  }
@@ -1,7 +1,19 @@
1
1
  import fs from 'fs';
2
+ import os from "os";
2
3
  import path from 'path';
3
4
  import { mkdirpSync } from 'mkdirp';
4
5
 
6
+ /**
7
+ * Resolve a file or directory path, supporting `~/` for the user's home directory and joining with additional path segments.
8
+ * @param {string} fileOrDirectory
9
+ * @param {string} [directories]
10
+ * @returns {string} The normalized path, with resolved relative and home directory references.
11
+ */
12
+ function resolvePath(fileOrDirectory, ...directories) {
13
+ fileOrDirectory = fileOrDirectory.replace(/^~\//, os.homedir() + '/');
14
+ return path.resolve(fileOrDirectory, ...directories);
15
+ }
16
+
5
17
  /**
6
18
  * Ensure that the given directory exists.
7
19
  * @param {string} dirName Target directory.
@@ -121,7 +133,22 @@ function scanForFiles(directory, regexPattern, onEach, onDone) {
121
133
  scanDir(directory, '', true, regexPattern, onEach, onDone);
122
134
  }
123
135
 
136
+ /**
137
+ * Return true when both paths are equal or `child` is nested inside `parent`.
138
+ *
139
+ * @private
140
+ * @param {string} parent
141
+ * @param {string} child
142
+ * @returns {boolean}
143
+ */
144
+ function isSameOrParentDirectory(parent, child) {
145
+ const relative = path.relative(parent, child);
146
+ return !relative || (!relative.startsWith('..') && !path.isAbsolute(relative));
147
+ }
148
+
124
149
  export {
150
+ resolvePath,
125
151
  ensureDirectory,
126
152
  scanForFiles,
153
+ isSameOrParentDirectory
127
154
  };