event-storage 1.2.0 → 1.3.1

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- ![event-storage](logo/color.png)
1
+ ![event-storage](logo/color.svg)
2
2
 
3
3
  [![build](https://github.com/albe/node-event-storage/actions/workflows/build.yml/badge.svg?branch=main)](https://github.com/albe/node-event-storage/actions/workflows/build.yml)
4
4
  [![npm version](https://badge.fury.io/js/event-storage.svg)](https://badge.fury.io/js/event-storage)
@@ -62,8 +62,8 @@ eventstore.on('ready', () => {
62
62
  | **Optimistic concurrency** | Pass `expectedVersion` to `commit()` to guarantee conflict-free writes. |
63
63
  | **Flexible stream reading** | Range queries, reverse iteration, and a fluent builder API. |
64
64
  | **Derived streams** | Filter or combine events into new read-only streams. |
65
- | **Multi-value matchers** | Object matchers support array values (OR semantics) and still benefit from O(1) discriminant routing on writes. |
66
- | **DCB / `typeAccessor`** | Configure `typeAccessor` to have per-type stream indexes maintained automatically, and use `query()` / `Condition` for fine-grained, query-scoped optimistic concurrency (Dynamic Consistency Boundaries). |
65
+ | **Object matchers** | Support nested equality, array values (OR semantics), and scalar operators like `$gt` / `$gte` / `$lt` / `$lte` / `$eq` / `$ne`, while still benefiting from O(1) discriminant routing on writes. |
66
+ | **DCB** | Configure `typeAccessor` to have per-type stream indexes maintained automatically, and use `query()` / `Condition` for fine-grained, query-scoped optimistic concurrency (Dynamic Consistency Boundaries). |
67
67
  | **Stream categories** | Name streams `<category>-<id>` and query the whole category at once. |
68
68
  | **Durable consumers** | At-least-once (and exactly-once with `setState`) event delivery with automatic position tracking. |
69
69
  | **Consistency guards** | Build aggregates that enforce business invariants with built-in snapshotting. |
@@ -75,6 +75,30 @@ eventstore.on('ready', () => {
75
75
 
76
76
  ---
77
77
 
78
+ ## DCB Example
79
+
80
+ ```javascript
81
+ const { stream, condition } = store.query(['OrderPlaced'], { payload: { customerId: 'cust-1' } });
82
+ const hasOpenOrder = stream.some((event) => event.status === 'open');
83
+
84
+ if (!hasOpenOrder) {
85
+ store.commit('orders-cust-1', [{ type: 'OrderPlaced', customerId: 'cust-1' }], condition);
86
+ }
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Object Matcher Syntax
92
+
93
+ Object matchers support nested equality, array values, and scalar operators like `$gt`, `$gte`, `$lt`, `$lte`, `$eq`, and `$ne`.
94
+
95
+ ```javascript
96
+ { payload: { type: ['OrderPlaced', 'OrderCancelled'] } }
97
+ { payload: { amount: { $gte: 100, $lt: 1000 } } }
98
+ ```
99
+
100
+ ---
101
+
78
102
  ## HTTP API
79
103
 
80
104
  To expose an event store over HTTP, see the companion package **[event-storage-http](https://github.com/albe/node-event-storage-http)**:
@@ -102,7 +126,7 @@ The full documentation is hosted at **<https://node-event-storage.readthedocs.io
102
126
 
103
127
  - [Getting Started](https://node-event-storage.readthedocs.io/en/latest/getting-started/) — installation, constructor options, basic usage.
104
128
  - [Event Streams](https://node-event-storage.readthedocs.io/en/latest/streams/) — writing, reading, optimistic concurrency, fluent API, joining streams, categories, and event metadata.
105
- - [Dynamic Consistency Boundaries (DCB)](https://node-event-storage.readthedocs.io/en/latest/dcb/) — `typeAccessor`, multi-value matchers, consistency tokens, and the full DCB workflow.
129
+ - [Dynamic Consistency Boundaries (DCB)](https://node-event-storage.readthedocs.io/en/latest/dcb/) — `typeAccessor`, query matchers, consistency tokens, and the full DCB workflow.
106
130
  - [Consumers](https://node-event-storage.readthedocs.io/en/latest/consumers/) — at-least-once and exactly-once delivery, consumer state, consistency guards, and read-only mode.
107
131
  - [Advanced Topics](https://node-event-storage.readthedocs.io/en/latest/advanced/) — ACID properties, reliability and crash-safety guarantees, storage configuration, partitioning, custom serialization, compression, security, and access control hooks.
108
132
 
package/index.d.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { Readable } from 'node:stream';
3
+
4
+ export type EventMatcher = Record<string, unknown> | ((payload: any, metadata?: any) => boolean);
5
+ export type EventPredicate = EventMatcher | ((buffer: Buffer) => boolean) | null;
6
+
7
+ export interface StreamIndexInfo {
8
+ length: number;
9
+ metadata?: Record<string, unknown> | null;
10
+ }
11
+
12
+ export interface StreamInfo {
13
+ index: StreamIndexInfo;
14
+ matcher?: EventMatcher;
15
+ closed?: boolean;
16
+ }
17
+
18
+ export class CommitCondition {
19
+ constructor(types: string[], matcher: EventMatcher | null | undefined, noneMatchAfter: number, raw?: boolean);
20
+ types: string[];
21
+ matcher: EventMatcher | null;
22
+ raw: boolean;
23
+ noneMatchAfter: number;
24
+ }
25
+
26
+ export class OptimisticConcurrencyError extends Error {}
27
+
28
+ export const ExpectedVersion: {
29
+ Any: -1;
30
+ EmptyStream: 0;
31
+ };
32
+
33
+ export class EventStream extends Readable {
34
+ constructor(name: string, eventStore: EventStore, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean);
35
+ name: string;
36
+ raw: boolean;
37
+ version: number;
38
+ minRevision: number;
39
+ maxRevision: number;
40
+ streamIndex: StreamIndexInfo;
41
+ predicate: EventPredicate;
42
+
43
+ from(revision: number): this;
44
+ until(revision: number): this;
45
+ fromStart(): this;
46
+ fromEnd(): this;
47
+ previous(amount: number): this;
48
+ following(amount: number): this;
49
+ backwards(): this;
50
+ forwards(): this;
51
+ where(predicate?: EventPredicate): this;
52
+ filter(predicate?: EventPredicate): this;
53
+ filter(
54
+ predicate: (chunk: any, options?: { signal?: AbortSignal }) => boolean | Promise<boolean>,
55
+ options: { concurrency?: number; signal?: AbortSignal }
56
+ ): Readable;
57
+ next(): any | false;
58
+ }
59
+
60
+ export class Consumer extends Readable {
61
+ constructor(storage: Storage, indexName: string, identifier: string, initialState?: Record<string, unknown>, startFrom?: number);
62
+ streamName: string;
63
+ position: number;
64
+ state: Record<string, unknown>;
65
+ start(): this;
66
+ stop(): void;
67
+ reset(initialState?: Record<string, unknown>, startFrom?: number): this;
68
+ setState(state: Record<string, unknown>): this;
69
+ }
70
+
71
+ export class Storage extends EventEmitter {
72
+ static ReadOnly: typeof Storage;
73
+ static StorageLockedError: typeof StorageLockedError;
74
+ static LOCK_THROW: number;
75
+ static LOCK_RECLAIM: number;
76
+
77
+ initialized: boolean | null;
78
+ length: number;
79
+ indexDirectory: string;
80
+ storageFile: string;
81
+ }
82
+
83
+ export class StorageLockedError extends Error {}
84
+
85
+ export class Index {
86
+ static ReadOnly: typeof Index;
87
+ static Entry: unknown;
88
+
89
+ length: number;
90
+ metadata?: Record<string, unknown> | null;
91
+ }
92
+
93
+ export class EventStore extends EventEmitter {
94
+ static Storage: typeof Storage;
95
+ static Index: typeof Index;
96
+
97
+ storage: Storage;
98
+ streams: Record<string, StreamInfo>;
99
+ consumers: Map<string, Consumer>;
100
+ length: number;
101
+
102
+ constructor(storeName?: string, config?: Record<string, unknown>);
103
+
104
+ open(callback?: (err?: Error | null) => void): void;
105
+ close(callback?: (err?: Error | null) => void): void;
106
+
107
+ getStreamVersion(streamName: string): number;
108
+ getEventStream(streamName: string, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream | false;
109
+ getAllEvents(minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
110
+ fromStreams(streamName: string, streamNames: string[], minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
111
+ getEventStreamForCategory(categoryName: string, minRevision?: number, maxRevision?: number, predicate?: EventPredicate, raw?: boolean): EventStream;
112
+
113
+ query(types: string[], matcher?: EventMatcher | null, minRevision?: number, raw?: boolean): { stream: EventStream; condition: CommitCondition };
114
+ createEventStream(streamName: string, matcher: EventMatcher, reindex?: boolean): EventStream;
115
+
116
+ commit(
117
+ streamName: string,
118
+ events: any[],
119
+ expectedVersion: number | CommitCondition,
120
+ metadata: Record<string, unknown>,
121
+ callback: (error: Error | null, commit?: Record<string, unknown>) => void
122
+ ): void;
123
+
124
+ getConsumer(streamName: string, identifier: string, initialState?: Record<string, unknown>, since?: number): Consumer;
125
+ getConsumer(identifier: string): Consumer | null;
126
+ scanConsumers(
127
+ callback: (error: Error | null, consumers: Array<{ name: string; stream: string; identifier: string }>) => void,
128
+ autoStart?: boolean
129
+ ): void;
130
+ }
131
+
132
+ export const LOCK_THROW: number;
133
+ export const LOCK_RECLAIM: number;
134
+
135
+ export function matches(document: Record<string, unknown>, matcher: Record<string, unknown>): boolean;
136
+ export function buildRawBufferMatcher(matcher: Record<string, unknown>): (buffer: Buffer, startOffset?: number) => boolean;
137
+
138
+ export default EventStore;
139
+
140
+
141
+
142
+
package/index.js CHANGED
@@ -3,3 +3,4 @@ export { default as EventStream } from './src/EventStream.js';
3
3
  export { default as Storage, StorageLockedError } from './src/Storage.js';
4
4
  export { default as Index } from './src/Index.js';
5
5
  export { default as Consumer } from './src/Consumer.js';
6
+ export { matches, buildRawBufferMatcher } from './src/utils/metadataUtil.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "event-storage",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "type": "module",
5
5
  "description": "An optimized embedded event store for node.js",
6
6
  "keywords": [
@@ -24,8 +24,10 @@
24
24
  "exports": {
25
25
  ".": "./index.js"
26
26
  },
27
+ "types": "./index.d.ts",
27
28
  "scripts": {
28
29
  "test": "c8 --reporter=lcov --reporter=text mocha test/*.spec.js",
30
+ "test:grep": "c8 --reporter=lcov --reporter=text mocha test/*.spec.js --grep",
29
31
  "coverage": "c8 report --reporter=text-lcov | coveralls"
30
32
  },
31
33
  "files": [
@@ -44,6 +46,7 @@
44
46
  "src/Storage/*.js",
45
47
  "src/WatchesFile.js",
46
48
  "index.js",
49
+ "index.d.ts",
47
50
  "src/utils/*.js"
48
51
  ],
49
52
  "license": "MIT",
package/src/Consumer.js CHANGED
@@ -3,6 +3,7 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { assert } from './utils/util.js';
5
5
  import { ensureDirectory } from './utils/fsUtil.js';
6
+ import { normalizeConsumerStateArgs } from './utils/apiHelpers.js';
6
7
  import Storage from './Storage/ReadableStorage.js';
7
8
  const MAX_CATCHUP_BATCH = 10;
8
9
 
@@ -11,7 +12,7 @@ const MAX_CATCHUP_BATCH = 10;
11
12
  * @param {string} filename
12
13
  */
13
14
  const safeUnlink = (filename) => {
14
- /* istanbul ignore next */
15
+ /* c8 ignore next */
15
16
  try {
16
17
  fs.unlinkSync(filename);
17
18
  } catch (e) {
@@ -84,14 +85,11 @@ class Consumer extends stream.Readable {
84
85
  * @param {number} startFrom The revision to start from within the index to consume.
85
86
  */
86
87
  restoreState(initialState, startFrom) {
87
- /* istanbul ignore if */
88
+ /* c8 ignore next 3 */
88
89
  if (!this.fileName) {
89
90
  return;
90
91
  }
91
- if (typeof initialState === 'number') {
92
- startFrom = initialState;
93
- initialState = {};
94
- }
92
+ ({ initialState, startFrom } = normalizeConsumerStateArgs(initialState, startFrom));
95
93
  try {
96
94
  const consumerData = fs.readFileSync(this.fileName);
97
95
  this.position = consumerData.readInt32LE(0);
@@ -137,7 +135,6 @@ class Consumer extends stream.Readable {
137
135
  return;
138
136
  }
139
137
 
140
- /* istanbul ignore if */
141
138
  if (this.position !== position - 1) {
142
139
  return;
143
140
  }
@@ -171,7 +168,7 @@ class Consumer extends stream.Readable {
171
168
  consumerData.write(consumerState, 4, consumerState.length, 'utf-8');
172
169
  const tmpFile = this.fileName + '.' + this.position;
173
170
  this.persisting = null;
174
- /* istanbul ignore if */
171
+ /* c8 ignore next 3 */
175
172
  if (fs.existsSync(tmpFile)) {
176
173
  throw new Error(`Trying to update consumer ${this.name} concurrently. Keep each single consumer within a single process.`);
177
174
  }
@@ -181,7 +178,7 @@ class Consumer extends stream.Readable {
181
178
  fs.renameSync(tmpFile, this.fileName);
182
179
  this.emit('persisted', consumerState);
183
180
  } catch (e) {
184
- /* istanbul ignore next */
181
+ /* c8 ignore next */
185
182
  safeUnlink(tmpFile);
186
183
  }
187
184
  });
@@ -274,10 +271,7 @@ class Consumer extends stream.Readable {
274
271
  * @api
275
272
  */
276
273
  reset(initialState = {}, startFrom = 0) {
277
- if (typeof initialState === 'number') {
278
- startFrom = initialState;
279
- initialState = {};
280
- }
274
+ ({ initialState, startFrom } = normalizeConsumerStateArgs(initialState, startFrom));
281
275
  const restart = this.consuming;
282
276
  this.stop();
283
277
  this.state = Object.freeze(initialState);
package/src/EventStore.js CHANGED
@@ -9,6 +9,7 @@ import Consumer from './Consumer.js';
9
9
  import { assert, getPropertyAtPath } from './utils/util.js';
10
10
  import { ensureDirectory, scanForFiles } from './utils/fsUtil.js';
11
11
  import { buildTypeMatcherFn } from './utils/metadataUtil.js';
12
+ import { fixCommitArgumentTypes, parseStreamFromIndexName, normalizePredicateRaw } from './utils/apiHelpers.js';
12
13
 
13
14
  const ExpectedVersion = {
14
15
  Any: -1,
@@ -39,7 +40,7 @@ class OptimisticConcurrencyError extends Error {}
39
40
  class CommitCondition {
40
41
  /**
41
42
  * @param {string[]} types
42
- * @param {function(object, object): boolean|object|null} [matcher]
43
+ * @param {(function(object, object): boolean)|object|null} [matcher]
43
44
  * @param {number} noneMatchAfter
44
45
  * @param {boolean} [raw=false]
45
46
  */
@@ -185,7 +186,6 @@ class EventStore extends events.EventEmitter {
185
186
  * @param {string} name The full stream name, including the `stream-` prefix (and optional `.closed` suffix).
186
187
  */
187
188
  registerStream(name) {
188
- /* istanbul ignore if */
189
189
  if (!name.startsWith('stream-')) {
190
190
  return;
191
191
  }
@@ -343,39 +343,6 @@ class EventStore extends events.EventEmitter {
343
343
  return this.storage.length;
344
344
  }
345
345
 
346
- /**
347
- * This method makes it so the last three arguments can be given either as:
348
- * - expectedVersion, metadata, callback
349
- * - expectedVersion, callback
350
- * - metadata, callback
351
- * - callback
352
- *
353
- * @private
354
- * @param {Array<object>|object} events
355
- * @param {number|CommitCondition} [expectedVersion]
356
- * @param {object|function} [metadata]
357
- * @param {function} [callback]
358
- * @returns {{events: Array<object>, metadata: object, callback: function, expectedVersion: number|CommitCondition}}
359
- */
360
- static fixArgumentTypes(events, expectedVersion, metadata, callback) {
361
- if (!(events instanceof Array)) {
362
- events = [events];
363
- }
364
- if (typeof expectedVersion !== 'number' && !(expectedVersion instanceof CommitCondition)) {
365
- callback = metadata;
366
- metadata = expectedVersion;
367
- expectedVersion = ExpectedVersion.Any;
368
- }
369
- if (typeof metadata !== 'object') {
370
- callback = metadata;
371
- metadata = {};
372
- }
373
- if (typeof callback !== 'function') {
374
- callback = () => {};
375
- }
376
- return { events, expectedVersion, metadata, callback };
377
- }
378
-
379
346
  /**
380
347
  * Check a {@link CommitCondition} against the current state of the store.
381
348
  * Iterates a join stream over all condition type streams starting from
@@ -383,6 +350,7 @@ class EventStore extends events.EventEmitter {
383
350
  * {@link OptimisticConcurrencyError} when a new event of a listed type satisfies
384
351
  * `condition.matcher(payload, metadata)` (or any such event when no matcher is provided).
385
352
  *
353
+ * @private
386
354
  * @param {CommitCondition} condition
387
355
  * @throws {OptimisticConcurrencyError}
388
356
  */
@@ -410,6 +378,7 @@ class EventStore extends events.EventEmitter {
410
378
  * Ensure a dedicated type stream exists for each event's type, creating it if needed.
411
379
  * Must be called before the entity stream is created to guarantee correct index routing.
412
380
  *
381
+ * @private
413
382
  * @param {Array<object>} events The events to process.
414
383
  */
415
384
  ensureTypeStreams(events) {
@@ -425,6 +394,11 @@ class EventStore extends events.EventEmitter {
425
394
  }
426
395
  }
427
396
 
397
+ /**
398
+ * @private
399
+ * @param {object} event
400
+ * @returns {string|null}
401
+ */
428
402
  resolveValidatedTypeStreamName(event) {
429
403
  const type = this.typeAccessor(event);
430
404
  if (type === undefined || type === null || type === '') {
@@ -435,6 +409,11 @@ class EventStore extends events.EventEmitter {
435
409
  return type;
436
410
  }
437
411
 
412
+ /**
413
+ * @private
414
+ * @param {string[]} types
415
+ * @returns {string[]}
416
+ */
438
417
  getExistingQueryTypes(types) {
439
418
  const queryTypes = [];
440
419
  for (const type of types) {
@@ -469,7 +448,14 @@ class EventStore extends events.EventEmitter {
469
448
  assert(typeof streamName === 'string' && streamName !== '', 'Must specify a stream name for commit.');
470
449
  assert(typeof events !== 'undefined' && events !== null, 'No events specified for commit.');
471
450
 
472
- ({ events, expectedVersion, metadata, callback } = EventStore.fixArgumentTypes(events, expectedVersion, metadata, callback));
451
+ ({ events, expectedVersion, metadata, callback } = fixCommitArgumentTypes(
452
+ events,
453
+ expectedVersion,
454
+ metadata,
455
+ callback,
456
+ ExpectedVersion.Any,
457
+ CommitCondition
458
+ ));
473
459
 
474
460
  // Perform DCB-style concurrency check when a CommitCondition is provided.
475
461
  if (expectedVersion instanceof CommitCondition) {
@@ -782,7 +768,13 @@ class EventStore extends events.EventEmitter {
782
768
  }
783
769
  const streamName = streamNameOrIdentifier;
784
770
  if (this.consumers.has(identifier)) {
785
- return this.consumers.get(identifier);
771
+ const existingConsumer = this.consumers.get(identifier);
772
+ if (existingConsumer.streamName === streamName) {
773
+ return existingConsumer;
774
+ }
775
+ // Rebind identifier to the requested stream when a consumer with the same
776
+ // identifier already exists for another stream.
777
+ existingConsumer.stop();
786
778
  }
787
779
  const consumer = new Consumer(this.storage, streamName === '_all' ? '_all' : 'stream-' + streamName, identifier, initialState, since);
788
780
  consumer.streamName = streamName;
@@ -829,22 +821,6 @@ class EventStore extends events.EventEmitter {
829
821
  }
830
822
  }
831
823
 
832
- function parseStreamFromIndexName(indexName) {
833
- if (indexName === '_all') {
834
- return '_all';
835
- }
836
- if (indexName.startsWith('stream-')) {
837
- return indexName.slice(7);
838
- }
839
- return indexName;
840
- }
841
-
842
- function normalizePredicateRaw(predicate, raw) {
843
- if (typeof predicate === 'boolean' && raw === false) {
844
- return { predicate: null, raw: predicate };
845
- }
846
- return { predicate, raw };
847
- }
848
824
 
849
825
  EventStore.Storage = Storage;
850
826
  EventStore.Index = Index;
@@ -1,29 +1,11 @@
1
1
  import stream from 'stream';
2
2
  import { assert } from './utils/util.js';
3
3
  import { buildRawBufferMatcher, matches } from './utils/metadataUtil.js';
4
+ import { normalizeRevision, normalizeMaxRevision } from './utils/apiHelpers.js';
5
+ import { emitDeprecationWarningOnce } from './utils/deprecations.js';
4
6
 
5
7
  const NDJSON_NEWLINE = Buffer.from('\n');
6
-
7
- /**
8
- * Calculate the actual version number from a possibly relative (negative) version number.
9
- *
10
- * @param {number} version The version to normalize.
11
- * @param {number} length The maximum version number
12
- * @returns {number} The absolute version number.
13
- */
14
- function normalizeVersion(version, length) {
15
- return version < 0 ? version + length + 1 : version;
16
- }
17
-
18
- /**
19
- * Return the lower absolute version given a version and a maxVersion constraint.
20
- * @param {number} version
21
- * @param {number} maxVersion
22
- * @returns {number}
23
- */
24
- function minVersion(version, maxVersion) {
25
- return Math.min(version, maxVersion < 0 ? version + maxVersion + 1 : maxVersion);
26
- }
8
+ const FILTER_MATCHER_DEPRECATION_CODE = 'EVENTSTREAM_FILTER_MATCHER_DEPRECATED';
27
9
 
28
10
  /**
29
11
  * An event stream is a simple wrapper around an iterator over storage documents.
@@ -56,9 +38,9 @@ class EventStream extends stream.Readable {
56
38
  this.rawMatcher = null;
57
39
  if (eventStore.streams[name]) {
58
40
  this.streamIndex = eventStore.streams[name].index;
59
- this.minRevision = normalizeVersion(minRevision, this.streamIndex.length);
60
- this.maxRevision = normalizeVersion(maxRevision, this.streamIndex.length);
61
- this.version = minVersion(this.streamIndex.length, maxRevision);
41
+ this.minRevision = normalizeRevision(minRevision, this.streamIndex.length);
42
+ this.maxRevision = normalizeRevision(maxRevision, this.streamIndex.length);
43
+ this.version = normalizeMaxRevision(this.streamIndex.length, maxRevision);
62
44
  this._iterator = null;
63
45
  this.fetch = () => eventStore.storage.readRange(this.minRevision, this.maxRevision, this.streamIndex, raw);
64
46
  } else {
@@ -74,7 +56,7 @@ class EventStream extends stream.Readable {
74
56
  * @returns {EventStream}
75
57
  */
76
58
  from(revision) {
77
- this.minRevision = normalizeVersion(revision, this.streamIndex.length);
59
+ this.minRevision = normalizeRevision(revision, this.streamIndex.length);
78
60
  return this;
79
61
  }
80
62
 
@@ -84,8 +66,8 @@ class EventStream extends stream.Readable {
84
66
  * @returns {EventStream}
85
67
  */
86
68
  until(revision) {
87
- this.maxRevision = normalizeVersion(revision, this.streamIndex.length);
88
- this.version = minVersion(this.streamIndex.length, this.maxRevision);
69
+ this.maxRevision = normalizeRevision(revision, this.streamIndex.length);
70
+ this.version = normalizeMaxRevision(this.streamIndex.length, this.maxRevision);
89
71
  return this;
90
72
  }
91
73
 
@@ -169,7 +151,7 @@ class EventStream extends stream.Readable {
169
151
  let tmp = this.maxRevision;
170
152
  this.maxRevision = this.minRevision;
171
153
  this.minRevision = tmp;
172
- this.version = minVersion(this.streamIndex.length, this.maxRevision);
154
+ this.version = normalizeMaxRevision(this.streamIndex.length, this.maxRevision);
173
155
  return this;
174
156
  }
175
157
 
@@ -265,16 +247,15 @@ class EventStream extends stream.Readable {
265
247
  }
266
248
 
267
249
  /**
268
- * Apply a filter predicate to this stream. Only events for which `predicate(payload, metadata)`
269
- * returns a truthy value will be yielded. The predicate is stored as a first-class property
270
- * of the stream and applied in {@link EventStream#next}.
250
+ * Apply matcher semantics to this EventStream instance (legacy `filter()` behavior).
271
251
  *
272
252
  * @api
273
- * @param {function(object, object): boolean} predicate A function receiving `(payload, metadata)`.
274
- * Events for which the predicate returns falsy are skipped.
253
+ * @param {(function(object, object): boolean)|(function(Buffer): boolean)|object|null} [predicate]
254
+ * Matcher function/object for object mode, or buffer matcher function/object for raw mode.
255
+ * Omit to clear the current predicate.
275
256
  * @returns {EventStream} `this`
276
257
  */
277
- filter(predicate) {
258
+ where(predicate) {
278
259
  this.predicate = predicate || null;
279
260
  this.rawMatcher = null;
280
261
  this._iterator = null;
@@ -282,6 +263,28 @@ class EventStream extends stream.Readable {
282
263
  return this;
283
264
  }
284
265
 
266
+ /**
267
+ * Readable-compatible filter entry point.
268
+ *
269
+ * - `filter(callback, options)` delegates to Node's `Readable.filter(...)`.
270
+ * - `filter(matcher)` keeps legacy EventStream matcher behavior and is deprecated.
271
+ *
272
+ * @api
273
+ * @param {function|object|null} [predicate]
274
+ * @param {{concurrency?: number, signal?: AbortSignal}|undefined} [options]
275
+ * @returns {stream.Readable|EventStream}
276
+ */
277
+ filter(predicate, options) {
278
+ if (options !== undefined) {
279
+ return super.filter(predicate, options);
280
+ }
281
+ emitDeprecationWarningOnce(
282
+ FILTER_MATCHER_DEPRECATION_CODE,
283
+ 'EventStream.filter() with matcher semantics is deprecated. Use EventStream.where() for matcher/object predicates or pass options to filter() to use Readable.filter().'
284
+ );
285
+ return this.where(predicate);
286
+ }
287
+
285
288
  matchesPredicate(entry) {
286
289
  if (!this.predicate) {
287
290
  return true;
@@ -20,7 +20,7 @@ class ReadOnlyIndex extends watchesFile(ReadableIndex) {
20
20
  * @param {string} filename
21
21
  */
22
22
  onChange(filename) {
23
- /* istanbul ignore if */
23
+ /* c8 ignore next 3 */
24
24
  if (!this.fd) {
25
25
  return;
26
26
  }
@@ -3,6 +3,7 @@ import path from 'path';
3
3
  import events from 'events';
4
4
  import Entry, { assertValidEntryClass } from '../IndexEntry.js';
5
5
  import { assert, wrapAndCheck, binarySearch } from '../utils/util.js';
6
+ import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
6
7
 
7
8
  // node-event-store-index V01
8
9
  const HEADER_MAGIC = "nesidx01";
@@ -44,10 +45,7 @@ class ReadableIndex extends events.EventEmitter {
44
45
  */
45
46
  constructor(name = '.index', options = {}) {
46
47
  super();
47
- if (typeof name !== 'string') {
48
- options = name;
49
- name = '.index';
50
- }
48
+ ({ name, options } = normalizeNamedCtorArgs(name, options, '.index'));
51
49
  let defaults = {
52
50
  dataDirectory: '.',
53
51
  EntryClass: Entry
@@ -3,6 +3,7 @@ import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC } from './Reada
3
3
  import { assert, assertEqual } from '../utils/util.js';
4
4
  import { buildMetadataHeader } from '../utils/metadataUtil.js';
5
5
  import { ensureDirectory } from '../utils/fsUtil.js';
6
+ import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
6
7
 
7
8
  /**
8
9
  * An index is a simple append-only file that stores an ordered list of entry elements pointing to the actual file position
@@ -27,10 +28,7 @@ class WritableIndex extends ReadableIndex {
27
28
  * @param {object} [options.metadata] An object containing the metadata information for this index. Will be written on initial creation and checked on subsequent openings.
28
29
  */
29
30
  constructor(name = '.index', options = {}) {
30
- if (typeof name !== 'string') {
31
- options = name;
32
- name = '.index';
33
- }
31
+ ({ name, options } = normalizeNamedCtorArgs(name, options, '.index'));
34
32
  let defaults = {
35
33
  writeBufferSize: 4096,
36
34
  flushDelay: 100,
@@ -1,20 +1,10 @@
1
1
  import EventStream from './EventStream.js';
2
2
  import { assert, kWayMerge } from './utils/util.js';
3
+ import { normalizeRevision } from './utils/apiHelpers.js';
3
4
 
4
5
  /** Reusable sentinel used for missing or empty per-stream iterators. */
5
6
  const emptyIterator = Object.freeze({ next() { return { done: true }; } });
6
7
 
7
- /**
8
- * Calculate the actual version number from a possibly relative (negative) version number.
9
- *
10
- * @param {number} version The version to normalize.
11
- * @param {number} length The maximum version number
12
- * @returns {number} The absolute version number.
13
- */
14
- function normalizeVersion(version, length) {
15
- return version < 0 ? version + length + 1 : version;
16
- }
17
-
18
8
  /**
19
9
  * An event stream is a simple wrapper around an iterator over storage documents.
20
10
  * It implements a node readable stream interface.
@@ -36,8 +26,8 @@ class JoinEventStream extends EventStream {
36
26
 
37
27
  this.streamIndex = eventStore.storage.index;
38
28
  // Translate revisions to index numbers (1-based) and wrap around negatives
39
- this.minRevision = normalizeVersion(minRevision, eventStore.length);
40
- this.maxRevision = normalizeVersion(maxRevision, eventStore.length);
29
+ this.minRevision = normalizeRevision(minRevision, eventStore.length);
30
+ this.maxRevision = normalizeRevision(maxRevision, eventStore.length);
41
31
  this.fetch = function() {
42
32
  return streams.map(streamName => {
43
33
  const streamIndex = eventStore.streams[streamName]?.index;
@@ -18,7 +18,7 @@ class ReadOnlyPartition extends WatchesFile(ReadablePartition) {
18
18
  * @param {string} filename
19
19
  */
20
20
  onChange(filename) {
21
- /* istanbul ignore if */
21
+ /* c8 ignore next 3 */
22
22
  if (!this.fd) {
23
23
  return;
24
24
  }