event-storage 1.4.1 → 1.5.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.
@@ -1,144 +1,90 @@
1
1
  import { assert, compileAccessor } from './util.js';
2
2
  import { buildMatcherFn } from './metadataUtil.js';
3
3
 
4
- /**
5
- * Merge two sorted index-entry ranges into one sorted union without duplicates.
6
- * Assumes each range is sorted and contains no duplicates (by entry number).
4
+ /*
5
+ * `union` and `intersect` combine two lazy ranges of index entries, as returned by `index.range()`, into a new
6
+ * lazy range in the same direction. A range may reuse its entry object, so an entry is only read before the range
7
+ * that yielded it is advanced.
7
8
  *
8
- * @param {Array<Array<number>>} left Sorted index-entry range.
9
- * @param {Array<Array<number>>} right Sorted index-entry range.
10
- * @returns {Array<Array<number>>} A new union range.
9
+ * Calling `next(number)` on a range skips ahead to the first entry that does not come before `number`.
10
+ * `intersect` uses that to jump over long stretches without a match instead of stepping through them.
11
11
  */
12
- function unionTwoIndexEntryRanges(left, right) {
13
- if (left.length === 0) {
14
- return right.slice();
15
- }
16
- if (right.length === 0) {
17
- return left.slice();
18
- }
19
-
20
- const merged = new Array(left.length + right.length);
21
- let leftIndex = 0;
22
- let rightIndex = 0;
23
- let count = 0;
24
-
25
- while (leftIndex < left.length && rightIndex < right.length) {
26
- const leftEntry = left[leftIndex];
27
- const rightEntry = right[rightIndex];
28
- const leftNumber = leftEntry[0];
29
- const rightNumber = rightEntry[0];
30
-
31
- if (leftNumber < rightNumber) {
32
- merged[count++] = leftEntry;
33
- leftIndex++;
34
- } else if (rightNumber < leftNumber) {
35
- merged[count++] = rightEntry;
36
- rightIndex++;
37
- } else {
38
- merged[count++] = leftEntry;
39
- leftIndex++;
40
- rightIndex++;
41
- }
42
- }
43
-
44
- while (leftIndex < left.length) {
45
- merged[count++] = left[leftIndex++];
46
- }
47
- while (rightIndex < right.length) {
48
- merged[count++] = right[rightIndex++];
49
- }
50
12
 
51
- merged.length = count;
52
- return merged;
13
+ /**
14
+ * @param {boolean} forwards
15
+ * @returns {function(number, number): boolean} Whether the first number comes before the second in that direction.
16
+ */
17
+ function comesBefore(forwards) {
18
+ return forwards ? (left, right) => left < right : (left, right) => left > right;
53
19
  }
54
20
 
55
21
  /**
56
- * Merge multiple sorted index-entry ranges into one sorted union without duplicates.
57
- * Pairwise reduction via two-way merges, optimized for realistic data with moderate overlap.
58
- * Assumes each range is sorted and contains no duplicates (by entry number).
22
+ * Continue yielding the entries of a range, passing skip targets through.
59
23
  *
60
- * @param {...Array<Array<number>>} ranges Sorted index-entry ranges.
61
- * @returns {Array<Array<number>>} A new union range.
24
+ * @param {IteratorResult} current The current, not yet yielded result of the range.
25
+ * @param {Generator} range
62
26
  */
63
- function union(...ranges) {
64
- if (ranges.length === 0) {
65
- return [];
66
- }
67
- if (ranges.length === 1) {
68
- return ranges[0].slice();
27
+ function* drain(current, range) {
28
+ while (!current.done) {
29
+ current = range.next(yield current.value);
69
30
  }
70
-
71
- let merged = unionTwoIndexEntryRanges(ranges[0], ranges[1]);
72
- for (let i = 2; i < ranges.length; i++) {
73
- merged = unionTwoIndexEntryRanges(merged, ranges[i]);
74
- }
75
- return merged;
76
31
  }
77
32
 
78
33
  /**
79
- * Intersect two sorted index-entry ranges by global number.
80
- * Assumes each range is sorted and contains no duplicates (by entry number).
34
+ * Merge two ranges into one ordered range without duplicates.
81
35
  *
82
- * @param {Array<Array<number>>} left Sorted index-entry range.
83
- * @param {Array<Array<number>>} right Sorted index-entry range.
84
- * @returns {Array<Array<number>>} A new intersection range.
36
+ * @param {Generator} left
37
+ * @param {Generator} right
38
+ * @param {boolean} [forwards=true]
39
+ * @returns {Generator}
85
40
  */
86
- function intersectTwoIndexEntryRanges(left, right) {
87
- if (left.length === 0 || right.length === 0) {
88
- return [];
89
- }
90
-
91
- const selected = new Array(Math.min(left.length, right.length));
92
- let leftIndex = 0;
93
- let rightIndex = 0;
94
- let count = 0;
95
-
96
- while (leftIndex < left.length && rightIndex < right.length) {
97
- const leftEntry = left[leftIndex];
98
- const rightEntry = right[rightIndex];
99
- const leftNumber = leftEntry[0];
100
- const rightNumber = rightEntry[0];
101
-
102
- if (leftNumber < rightNumber) {
103
- leftIndex++;
104
- } else if (rightNumber < leftNumber) {
105
- rightIndex++;
106
- } else {
107
- selected[count++] = leftEntry;
108
- leftIndex++;
109
- rightIndex++;
41
+ function* union(left, right, forwards = true) {
42
+ const before = comesBefore(forwards);
43
+ let a = left.next();
44
+ let b = right.next();
45
+ while (!a.done && !b.done) {
46
+ const leftNumber = a.value.number;
47
+ const rightNumber = b.value.number;
48
+ const leftFirst = !before(rightNumber, leftNumber);
49
+ const rightFirst = !before(leftNumber, rightNumber);
50
+ const target = yield leftFirst ? a.value : b.value;
51
+ // Advance the side that was yielded, and also the other side when a skip target leaves it behind.
52
+ if (leftFirst || (target !== undefined && before(leftNumber, target))) {
53
+ a = left.next(target);
54
+ }
55
+ if (rightFirst || (target !== undefined && before(rightNumber, target))) {
56
+ b = right.next(target);
110
57
  }
111
58
  }
112
-
113
- selected.length = count;
114
- return selected;
59
+ yield* drain(a, left);
60
+ yield* drain(b, right);
115
61
  }
116
62
 
117
63
  /**
118
- * Intersect multiple sorted index-entry ranges by global number.
119
- * Pairwise reduction with size-order optimization, best for moderate to high overlap.
120
- * Assumes each range is sorted and contains no duplicates (by entry number).
64
+ * Yield the entries that are contained in both ranges.
121
65
  *
122
- * @param {...Array<Array<number>>} ranges Sorted index-entry ranges.
123
- * @returns {Array<Array<number>>} A new intersection range.
66
+ * @param {Generator} left
67
+ * @param {Generator} right
68
+ * @param {boolean} [forwards=true]
69
+ * @returns {Generator}
124
70
  */
125
- function intersect(...ranges) {
126
- if (ranges.length === 0) {
127
- return [];
128
- }
129
- if (ranges.length === 1) {
130
- return ranges[0].slice();
131
- }
132
-
133
- ranges.sort((a, b) => a.length - b.length);
134
- if (ranges[0].length === 0) {
135
- return [];
136
- }
137
- let selected = intersectTwoIndexEntryRanges(ranges[0], ranges[1]);
138
- for (let i = 2; i < ranges.length && selected.length > 0; i++) {
139
- selected = intersectTwoIndexEntryRanges(selected, ranges[i]);
71
+ function* intersect(left, right, forwards = true) {
72
+ const before = comesBefore(forwards);
73
+ let a = left.next();
74
+ let b = right.next();
75
+ while (!a.done && !b.done) {
76
+ const leftNumber = a.value.number;
77
+ const rightNumber = b.value.number;
78
+ if (leftNumber === rightNumber) {
79
+ const target = yield a.value;
80
+ a = left.next(target);
81
+ b = right.next(target);
82
+ } else if (before(leftNumber, rightNumber)) {
83
+ a = left.next(rightNumber);
84
+ } else {
85
+ b = right.next(leftNumber);
86
+ }
140
87
  }
141
- return selected;
142
88
  }
143
89
 
144
90
  /**
@@ -196,6 +142,28 @@ function optimizeSelectorNode(selectorNode, depth) {
196
142
  return selectorNode;
197
143
  }
198
144
 
145
+ /**
146
+ * Remove streams from a selector by treating them as empty: an OR level drops them, an AND level that contains one
147
+ * matches nothing anymore and is dropped as a whole. The result therefore never matches more than the input.
148
+ * `'_all'` is never removed.
149
+ *
150
+ * @param {string|Array} selector A selector in the algebra of `fromStreams()` (depth 0 = OR).
151
+ * @param {Set<string>} names The stream names to treat as empty.
152
+ * @param {number} [depth=0]
153
+ * @returns {string|Array|null} The reduced selector, or `null` if nothing is left.
154
+ */
155
+ function excludeStreams(selector, names, depth = 0) {
156
+ if (typeof selector === 'string') {
157
+ return names.has(selector) && selector !== '_all' ? null : selector;
158
+ }
159
+ const children = selector.map(node => excludeStreams(node, names, depth + 1));
160
+ if (depth % 2 === 0) {
161
+ const remaining = children.filter(node => node !== null);
162
+ return remaining.length > 0 ? remaining : null;
163
+ }
164
+ return children.includes(null) ? null : children;
165
+ }
166
+
199
167
  /**
200
168
  * Pre-compile a stream source descriptor with a single curried matcher factory:
201
169
  * `matcherFn(operator)(value) => objectMatcher`. The scalar and `$has` shapes are compiled
@@ -218,6 +186,7 @@ function buildStreamSource(sourcePath, nameBuilder) {
218
186
  }
219
187
 
220
188
  export {
189
+ excludeStreams,
221
190
  union,
222
191
  intersect,
223
192
  normalizeSelector,
@@ -11,6 +11,7 @@ import {
11
11
 
12
12
  const compiledMatcherCache = new WeakMap();
13
13
  const rawBufferMatcherCache = new WeakMap();
14
+ const ORDERING_OPERATORS = new Set(['$gt', '$gte', '$lt', '$lte', '$eq', '$ne']);
14
15
 
15
16
  /**
16
17
  * @param {any} value Value to classify.
@@ -140,6 +141,10 @@ function buildOperatorChecks(operatorObj) {
140
141
  case '$hasAny':
141
142
  checks.push(value => Array.isArray(value) && expectedValue.some(v => value.includes(v)));
142
143
  break;
144
+ case '$startsWith':
145
+ assert(typeof expectedValue === 'string', '$startsWith expects a string prefix.', TypeError);
146
+ checks.push(value => typeof value === 'string' && value.startsWith(expectedValue));
147
+ break;
143
148
  default:
144
149
  throw new TypeError(`Unknown operator: ${operator}`);
145
150
  }
@@ -369,6 +374,11 @@ function buildMatcherTreeChild(key, value) {
369
374
  const hasAnyPatterns = value['$hasAny'].map(v => Buffer.from(JSON.stringify(v), 'utf8'));
370
375
  child.matches = (buffer, valueStart) =>
371
376
  hasAnyPatterns.some(vp => indexOfSameLevel(buffer, vp, valueStart) !== -1);
377
+ } else if (isLoneStartsWith(value)) {
378
+ // The serialized prefix without its closing quote is a byte prefix of every JSON string
379
+ // that starts with it, so the key/value pattern alone decides the match.
380
+ child.isKeyPattern = true;
381
+ child.pattern = Buffer.concat([keyPrefix, Buffer.from(JSON.stringify(value['$startsWith']).slice(0, -1), 'utf8')]);
372
382
  } else if (isOperatorObject(value)) {
373
383
  child.isKeyPattern = true;
374
384
  child.pattern = keyPrefix;
@@ -384,6 +394,18 @@ function buildMatcherTreeChild(key, value) {
384
394
  return child;
385
395
  }
386
396
 
397
+ /**
398
+ * A prefix ending in a lone surrogate serializes as an escape sequence, while a document string
399
+ * continuing the surrogate pair serializes as raw UTF-8, so only well-formed prefixes are byte prefixes.
400
+ *
401
+ * @param {object} value Operator object.
402
+ * @returns {boolean} True when `value` is `{ $startsWith: string }` that can be matched as a byte prefix.
403
+ */
404
+ function isLoneStartsWith(value) {
405
+ const prefix = value['$startsWith'];
406
+ return typeof prefix === 'string' && prefix.isWellFormed() && Object.keys(value).length === 1;
407
+ }
408
+
387
409
  /**
388
410
  * @param {Buffer} keyPrefix Serialized key prefix (`"key":`).
389
411
  * @param {any} value Scalar value to append.
@@ -497,7 +519,7 @@ function matchesOrdering(operator, ordering) {
497
519
  function buildNumericOperatorComparisons(entries) {
498
520
  const comparisons = [];
499
521
  for (const [operator, expectedValue] of entries) {
500
- if (typeof expectedValue !== 'number') {
522
+ if (typeof expectedValue !== 'number' || !ORDERING_OPERATORS.has(operator)) {
501
523
  return null;
502
524
  }
503
525
  const expectedStr = JSON.stringify(expectedValue);