@mark1russell7/collections 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +78 -2
- package/build/dag/index.d.ts +144 -0
- package/build/dag/index.d.ts.map +1 -0
- package/build/dag/index.js +294 -0
- package/build/dag/index.js.map +1 -0
- package/build/graph/index.d.ts +20 -0
- package/build/graph/index.d.ts.map +1 -0
- package/build/graph/index.js +48 -0
- package/build/graph/index.js.map +1 -0
- package/build/index.d.ts +4952 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +7811 -0
- package/build/index.js.map +1 -0
- package/build/testing/index.d.ts +25 -0
- package/build/testing/index.d.ts.map +1 -0
- package/build/testing/index.js +72 -0
- package/build/testing/index.js.map +1 -0
- package/package.json +77 -3
- package/src/async/async-queue.ts +481 -0
- package/src/async/channels.ts +450 -0
- package/src/async/settled.ts +41 -0
- package/src/behaviors/bounded.ts +485 -0
- package/src/behaviors/composite.ts +99 -0
- package/src/behaviors/evented.ts +464 -0
- package/src/behaviors/lru.ts +449 -0
- package/src/behaviors/readonly.ts +236 -0
- package/src/behaviors/safe.ts +358 -0
- package/src/behaviors/synchronized.ts +316 -0
- package/src/behaviors/ttl.ts +464 -0
- package/src/core/effects.ts +327 -0
- package/src/core/events.ts +363 -0
- package/src/core/middleware.ts +413 -0
- package/src/core/policies.ts +316 -0
- package/src/core/traits.ts +164 -0
- package/src/dag/builder.ts +124 -0
- package/src/dag/executor.ts +190 -0
- package/src/dag/index.ts +14 -0
- package/src/dag/traversal.ts +129 -0
- package/src/dag/types.ts +87 -0
- package/src/fx/collectors.ts +500 -0
- package/src/fx/iter.ts +536 -0
- package/src/graph/hub-order.ts +53 -0
- package/src/graph/index.ts +5 -0
- package/src/impl/array-deque.ts +463 -0
- package/src/impl/array-list.ts +490 -0
- package/src/impl/hash-map.ts +623 -0
- package/src/impl/hash-set.ts +342 -0
- package/src/impl/linked-hash-map.ts +572 -0
- package/src/impl/linked-list.ts +610 -0
- package/src/impl/priority-queue.ts +448 -0
- package/src/impl/summary-tree.ts +594 -0
- package/src/impl/tree-map.ts +913 -0
- package/src/impl/tree-set.ts +469 -0
- package/src/index.ts +237 -0
- package/src/interfaces/collection.ts +141 -0
- package/src/interfaces/list.ts +281 -0
- package/src/interfaces/map.ts +405 -0
- package/src/interfaces/queue.ts +353 -0
- package/src/interfaces/set.ts +158 -0
- package/src/order/index.ts +6 -0
- package/src/order/rank.ts +271 -0
- package/src/storage/listeners.ts +72 -0
- package/src/testing/check.ts +81 -0
- package/src/testing/index.ts +7 -0
- package/src/utils/defaults.ts +345 -0
- package/src/utils/factories.ts +357 -0
- package/src/utils/helpers.ts +248 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The keys of an ordered list: fractional indexing with base-62 keys. A
|
|
3
|
+
* key is a string. Each item of the list keeps one, and the list sorts by it. An item that moves
|
|
4
|
+
* between two others gets a key between theirs, so a move writes one item and no other.
|
|
5
|
+
*
|
|
6
|
+
* - A key has an integer part and a fraction part. The first character of the integer part gives its
|
|
7
|
+
* length. An insertion at an end changes the integer part, so the keys stay short.
|
|
8
|
+
* - An insertion between two keys uses the fraction part, which can grow without a limit. Thus the keys
|
|
9
|
+
* do not run out, and the list needs no rebalance.
|
|
10
|
+
* - Compare two keys by the code units of the strings (`a < b`), not with `localeCompare`.
|
|
11
|
+
* - Two writers that move items into the same gap at the same time can get the same key. Sort by the
|
|
12
|
+
* key, then by the id of the item, so each reader sees one order.
|
|
13
|
+
*
|
|
14
|
+
* The algorithm is the one of the `fractional-indexing` package of Rocicorp (CC0), after the article
|
|
15
|
+
* "Implementing Fractional Indexing" of David Greenspan.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** The digits of a key, in ascending order of their code units. */
|
|
19
|
+
export const KEY_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
20
|
+
|
|
21
|
+
const ZERO = KEY_DIGITS[0]!;
|
|
22
|
+
const LAST = KEY_DIGITS[KEY_DIGITS.length - 1]!;
|
|
23
|
+
/** The smallest integer part. No key comes before it. */
|
|
24
|
+
const SMALLEST_INTEGER = `A${ZERO.repeat(26)}`;
|
|
25
|
+
|
|
26
|
+
function invalid(message: string): RangeError {
|
|
27
|
+
return new RangeError(message);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** This function gives the length of an integer part from its head character: a to z and Z to A give 2 to 27. */
|
|
31
|
+
function integerLength(head: string): number {
|
|
32
|
+
if (head >= "a" && head <= "z") return head.charCodeAt(0) - "a".charCodeAt(0) + 2;
|
|
33
|
+
if (head >= "A" && head <= "Z") return "Z".charCodeAt(0) - head.charCodeAt(0) + 2;
|
|
34
|
+
throw invalid(`A key cannot start with "${head}"`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function integerPart(key: string): string {
|
|
38
|
+
const length = integerLength(key[0] ?? "");
|
|
39
|
+
if (length > key.length) throw invalid(`The key "${key}" is too short for its integer part`);
|
|
40
|
+
return key.slice(0, length);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function validateKey(key: string): void {
|
|
44
|
+
if (typeof key !== "string" || key === "") throw invalid("A key is a string that is not empty");
|
|
45
|
+
for (const c of key) if (!KEY_DIGITS.includes(c)) throw invalid(`The key "${key}" has a character that is no digit of a key`);
|
|
46
|
+
if (key === SMALLEST_INTEGER) throw invalid(`The key "${key}" is reserved`);
|
|
47
|
+
const fraction = key.slice(integerPart(key).length);
|
|
48
|
+
if (fraction.endsWith(ZERO)) throw invalid(`The fraction part of the key "${key}" ends with ${ZERO}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A fraction strictly between two fractions. `b` null is the end. Neither one ends with the zero digit. */
|
|
52
|
+
function midpoint(a: string, b: string | null): string {
|
|
53
|
+
if (b !== null) {
|
|
54
|
+
let n = 0;
|
|
55
|
+
while ((a[n] ?? ZERO) === b[n]) n++;
|
|
56
|
+
if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
|
|
57
|
+
}
|
|
58
|
+
const digitA = a ? KEY_DIGITS.indexOf(a[0]!) : 0;
|
|
59
|
+
const digitB = b !== null ? KEY_DIGITS.indexOf(b[0]!) : KEY_DIGITS.length;
|
|
60
|
+
if (digitB - digitA > 1) return KEY_DIGITS[Math.round((digitA + digitB) / 2)]!;
|
|
61
|
+
// The first digits are next to each other
|
|
62
|
+
if (b !== null && b.length > 1) return b.slice(0, 1);
|
|
63
|
+
return KEY_DIGITS[digitA]! + midpoint(a.slice(1), null);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function incrementInteger(x: string): string | null {
|
|
67
|
+
const [head, ...digits] = x.split("") as [string, ...string[]];
|
|
68
|
+
let carry = true;
|
|
69
|
+
for (let i = digits.length - 1; carry && i >= 0; i--) {
|
|
70
|
+
const d = KEY_DIGITS.indexOf(digits[i]!) + 1;
|
|
71
|
+
if (d === KEY_DIGITS.length) digits[i] = ZERO;
|
|
72
|
+
else {
|
|
73
|
+
digits[i] = KEY_DIGITS[d]!;
|
|
74
|
+
carry = false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (!carry) return head + digits.join("");
|
|
78
|
+
if (head === "Z") return `a${ZERO}`;
|
|
79
|
+
if (head === "z") return null;
|
|
80
|
+
const next = String.fromCharCode(head.charCodeAt(0) + 1);
|
|
81
|
+
if (next > "a") digits.push(ZERO);
|
|
82
|
+
else digits.pop();
|
|
83
|
+
return next + digits.join("");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function decrementInteger(x: string): string | null {
|
|
87
|
+
const [head, ...digits] = x.split("") as [string, ...string[]];
|
|
88
|
+
let borrow = true;
|
|
89
|
+
for (let i = digits.length - 1; borrow && i >= 0; i--) {
|
|
90
|
+
const d = KEY_DIGITS.indexOf(digits[i]!) - 1;
|
|
91
|
+
if (d === -1) digits[i] = LAST;
|
|
92
|
+
else {
|
|
93
|
+
digits[i] = KEY_DIGITS[d]!;
|
|
94
|
+
borrow = false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (!borrow) return head + digits.join("");
|
|
98
|
+
if (head === "a") return `Z${LAST}`;
|
|
99
|
+
if (head === "A") return null;
|
|
100
|
+
const next = String.fromCharCode(head.charCodeAt(0) - 1);
|
|
101
|
+
if (next < "Z") digits.push(LAST);
|
|
102
|
+
else digits.pop();
|
|
103
|
+
return next + digits.join("");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* This function gives a key strictly between two keys. Without `prev`, the key comes before `next`.
|
|
108
|
+
* Without `next`, it comes after `prev`. Without both, it gives the first key of a list ("a0").
|
|
109
|
+
*
|
|
110
|
+
* @throws RangeError when a key is not valid, or when `prev` is not before `next`
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```ts
|
|
114
|
+
* keyBetween(undefined, undefined); // "a0"
|
|
115
|
+
* keyBetween("a0", undefined); // "a1", after a0
|
|
116
|
+
* keyBetween("a0", "a1"); // "a0V"
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
export function keyBetween(prev: string | null | undefined, next: string | null | undefined): string {
|
|
120
|
+
const a = prev ?? null;
|
|
121
|
+
const b = next ?? null;
|
|
122
|
+
if (a !== null) validateKey(a);
|
|
123
|
+
if (b !== null) validateKey(b);
|
|
124
|
+
if (a !== null && b !== null && a >= b) throw invalid(`The key "${a}" is not before the key "${b}"`);
|
|
125
|
+
if (a === null) {
|
|
126
|
+
if (b === null) return `a${ZERO}`;
|
|
127
|
+
const ib = integerPart(b);
|
|
128
|
+
const fb = b.slice(ib.length);
|
|
129
|
+
if (ib === SMALLEST_INTEGER) return ib + midpoint("", fb);
|
|
130
|
+
if (ib < b) return ib;
|
|
131
|
+
const decremented = decrementInteger(ib);
|
|
132
|
+
if (decremented === null) throw invalid("No key comes before this one");
|
|
133
|
+
return decremented;
|
|
134
|
+
}
|
|
135
|
+
const ia = integerPart(a);
|
|
136
|
+
const fa = a.slice(ia.length);
|
|
137
|
+
if (b === null) {
|
|
138
|
+
const incremented = incrementInteger(ia);
|
|
139
|
+
return incremented === null ? ia + midpoint(fa, null) : incremented;
|
|
140
|
+
}
|
|
141
|
+
const ib = integerPart(b);
|
|
142
|
+
const fb = b.slice(ib.length);
|
|
143
|
+
if (ia === ib) return ia + midpoint(fa, fb);
|
|
144
|
+
const incremented = incrementInteger(ia);
|
|
145
|
+
if (incremented === null) throw invalid("No key comes after this one");
|
|
146
|
+
if (incremented < b) return incremented;
|
|
147
|
+
return ia + midpoint(fa, null);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* This function gives `count` keys in ascending order, strictly between two keys.
|
|
152
|
+
* Use it to put several items at one place, or to give keys to a new list.
|
|
153
|
+
*
|
|
154
|
+
* @throws RangeError as `keyBetween`, or when `count` is not an integer of 0 or more
|
|
155
|
+
*/
|
|
156
|
+
export function keysBetween(prev: string | null | undefined, next: string | null | undefined, count: number): string[] {
|
|
157
|
+
if (!Number.isInteger(count) || count < 0) throw invalid(`A count of keys is an integer of 0 or more, not ${count}`);
|
|
158
|
+
const a = prev ?? null;
|
|
159
|
+
const b = next ?? null;
|
|
160
|
+
if (count === 0) return [];
|
|
161
|
+
if (count === 1) return [keyBetween(a, b)];
|
|
162
|
+
if (b === null) {
|
|
163
|
+
const keys = [keyBetween(a, null)];
|
|
164
|
+
for (let i = 1; i < count; i++) keys.push(keyBetween(keys[i - 1]!, null));
|
|
165
|
+
return keys;
|
|
166
|
+
}
|
|
167
|
+
if (a === null) {
|
|
168
|
+
const keys = [keyBetween(null, b)];
|
|
169
|
+
for (let i = 1; i < count; i++) keys.push(keyBetween(null, keys[i - 1]!));
|
|
170
|
+
return keys.reverse();
|
|
171
|
+
}
|
|
172
|
+
const half = Math.floor(count / 2);
|
|
173
|
+
const middle = keyBetween(a, b);
|
|
174
|
+
return [...keysBetween(a, middle, half), middle, ...keysBetween(middle, b, count - half - 1)];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The options of `isValidKey`. */
|
|
178
|
+
export interface KeyCheckOptions {
|
|
179
|
+
/** The longest key that the check accepts. The default is 1024 characters. */
|
|
180
|
+
readonly maxLength?: number;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* This function tells if a value is a valid key, for example a key that a client writes. A key that
|
|
185
|
+
* is longer than `maxLength` is not valid.
|
|
186
|
+
*/
|
|
187
|
+
export function isValidKey(key: unknown, options: KeyCheckOptions = {}): key is string {
|
|
188
|
+
if (typeof key !== "string" || key.length > (options.maxLength ?? 1024)) return false;
|
|
189
|
+
try {
|
|
190
|
+
validateKey(key);
|
|
191
|
+
return true;
|
|
192
|
+
} catch {
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** An item of an ordered list: its id and its key. */
|
|
198
|
+
export interface KeyedItem {
|
|
199
|
+
readonly id: string;
|
|
200
|
+
readonly key: string;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* This function gives the writes of a move: the new key of the item that moves, and new keys for the
|
|
205
|
+
* neighbors that need them. Give the other items of the list in order (by key, then by id), without
|
|
206
|
+
* the item that moves. Also give the index of the drop, from 0 to their number (`dropIndex`).
|
|
207
|
+
*
|
|
208
|
+
* Two writers can give two items one key. A drop between two such items has no key between them.
|
|
209
|
+
* So the helper first gives new keys to the items after the drop that have the key of the item before
|
|
210
|
+
* it. Each write is `{ id, key }`. The writes of the neighbors come first, and the write of the item
|
|
211
|
+
* that moves comes last.
|
|
212
|
+
*
|
|
213
|
+
* @throws RangeError when the index is outside the list, when the list holds the item that moves, or
|
|
214
|
+
* when a key is not valid
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* ```ts
|
|
218
|
+
* const index = dropIndex(pointer, others.map(centerOf));
|
|
219
|
+
* for (const { id, key } of keysForDrop(others, index, dragged.id)) await save(id, { rank: key });
|
|
220
|
+
* ```
|
|
221
|
+
*/
|
|
222
|
+
export function keysForDrop(items: readonly KeyedItem[], index: number, movingId: string): Array<{ id: string; key: string }> {
|
|
223
|
+
if (!Number.isInteger(index) || index < 0 || index > items.length) throw invalid(`The index ${index} is outside the list of ${items.length} items`);
|
|
224
|
+
if (items.some((item) => item.id === movingId)) throw invalid(`The list holds the item that moves (${movingId})`);
|
|
225
|
+
const prev = items[index - 1]?.key ?? null;
|
|
226
|
+
// The items from the index on that do not come after the item before the drop need new keys
|
|
227
|
+
let end = index;
|
|
228
|
+
while (end < items.length && prev !== null && items[end]!.key <= prev) end++;
|
|
229
|
+
const writes: Array<{ id: string; key: string }> = [];
|
|
230
|
+
if (end > index) {
|
|
231
|
+
const keys = keysBetween(prev, items[end]?.key ?? null, end - index);
|
|
232
|
+
for (let i = index; i < end; i++) writes.push({ id: items[i]!.id, key: keys[i - index]! });
|
|
233
|
+
}
|
|
234
|
+
const next = writes.length > 0 ? writes[0]!.key : (items[index]?.key ?? null);
|
|
235
|
+
writes.push({ id: movingId, key: keyBetween(prev, next) });
|
|
236
|
+
return writes;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** The order of two keys: the code units of the strings, as the keys need (not `localeCompare`). */
|
|
240
|
+
export function compareKeys(a: string, b: string): number {
|
|
241
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** A point, for example the center of an item on the screen. */
|
|
245
|
+
export interface Point {
|
|
246
|
+
readonly x: number;
|
|
247
|
+
readonly y: number;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* This function gives the index at which a point goes among the items of a list on the screen.
|
|
252
|
+
* The reading order is the rows from top to bottom, and each row from left to right.
|
|
253
|
+
* The index is that of the first item whose center comes after the point, from 0 to the number of items. A center within
|
|
254
|
+
* `rowTolerance` of the point on the vertical axis is in the row of the point.
|
|
255
|
+
*
|
|
256
|
+
* Give the centers in reading order, the same order as the keys, and without the item that moves.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
* ```ts
|
|
260
|
+
* const index = dropIndex(pointer, others.map(centerOf));
|
|
261
|
+
* const key = keyBetween(keys[index - 1], keys[index]);
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
export function dropIndex(point: Point, centers: readonly Point[], rowTolerance = 24): number {
|
|
265
|
+
for (let i = 0; i < centers.length; i++) {
|
|
266
|
+
const c = centers[i]!;
|
|
267
|
+
if (point.y < c.y - rowTolerance) return i;
|
|
268
|
+
if (Math.abs(point.y - c.y) <= rowTolerance && point.x < c.x) return i;
|
|
269
|
+
}
|
|
270
|
+
return centers.length;
|
|
271
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A set of listeners for the events of a storage: the change batches of `observe()`, or the status
|
|
3
|
+
* of a sync. A storage package uses it, so each storage treats its listeners in the same way.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** The function that gets the error of a listener. */
|
|
7
|
+
export type ListenerErrorHandler = (error: unknown) => void;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The default handler of the error of a listener. It throws the error again in a microtask, as an
|
|
11
|
+
* `EventTarget` reports the error of a listener. Thus the error is not lost, and the write that
|
|
12
|
+
* sent the event does not fail.
|
|
13
|
+
*/
|
|
14
|
+
export const reportListenerError: ListenerErrorHandler = (error) => {
|
|
15
|
+
queueMicrotask(() => {
|
|
16
|
+
throw error;
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The listeners of one kind of event.
|
|
22
|
+
*
|
|
23
|
+
* - `emit()` gives the event to each listener, in the order of `add()`.
|
|
24
|
+
* - A listener that `add()` gets during an `emit()` gets the next event, not this one.
|
|
25
|
+
* - The error of a listener goes to the error handler. The other listeners get the event.
|
|
26
|
+
* - The same function can be added two times. Each `add()` gives its own function that removes it.
|
|
27
|
+
*/
|
|
28
|
+
export class StorageListeners<E> {
|
|
29
|
+
private readonly listeners = new Set<{ readonly listener: (event: E) => void }>();
|
|
30
|
+
private readonly onError: ListenerErrorHandler;
|
|
31
|
+
|
|
32
|
+
/** @param onError - The function that gets the error of a listener. The default is `reportListenerError`. */
|
|
33
|
+
constructor(onError: ListenerErrorHandler = reportListenerError) {
|
|
34
|
+
this.onError = onError;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The number of listeners. */
|
|
38
|
+
get size(): number {
|
|
39
|
+
return this.listeners.size;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* This method adds a listener.
|
|
44
|
+
*
|
|
45
|
+
* @returns The function that removes the listener. A second use of it does nothing.
|
|
46
|
+
*/
|
|
47
|
+
add(listener: (event: E) => void): () => void {
|
|
48
|
+
const entry = { listener };
|
|
49
|
+
this.listeners.add(entry);
|
|
50
|
+
return () => {
|
|
51
|
+
this.listeners.delete(entry);
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** This method gives the event to each listener. */
|
|
56
|
+
emit(event: E): void {
|
|
57
|
+
for (const entry of [...this.listeners]) {
|
|
58
|
+
// A listener that a listener before it removed gets no event
|
|
59
|
+
if (!this.listeners.has(entry)) continue;
|
|
60
|
+
try {
|
|
61
|
+
entry.listener(event);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
this.onError(error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** This method removes each listener. */
|
|
69
|
+
clear(): void {
|
|
70
|
+
this.listeners.clear();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The checks of the contract suite. The suite does not import a test framework, so a runtime
|
|
3
|
+
* entry of this package does not load one. A failed check throws `ContractViolation`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** The error of a failed check of the contract suite. */
|
|
7
|
+
export class ContractViolation extends Error {
|
|
8
|
+
override readonly name = "ContractViolation";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** This function gives the text of a value for a message: JSON, with a `Map` as its entries. */
|
|
12
|
+
export function show(value: unknown): string {
|
|
13
|
+
if (value === undefined) return "undefined";
|
|
14
|
+
try {
|
|
15
|
+
return JSON.stringify(value, (_key, item: unknown) => (item instanceof Map ? { Map: [...item.entries()] } : item === undefined ? "<undefined>" : item));
|
|
16
|
+
} catch {
|
|
17
|
+
return String(value);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
22
|
+
if (typeof value !== "object" || value === null) return false;
|
|
23
|
+
const prototype = Object.getPrototypeOf(value) as unknown;
|
|
24
|
+
return prototype === Object.prototype || prototype === null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps
|
|
29
|
+
* are equal when they have the same keys with equal values, in any order.
|
|
30
|
+
*/
|
|
31
|
+
export function deepEqual(actual: unknown, expected: unknown): boolean {
|
|
32
|
+
if (Object.is(actual, expected)) return true;
|
|
33
|
+
if (actual instanceof Map && expected instanceof Map) {
|
|
34
|
+
if (actual.size !== expected.size) return false;
|
|
35
|
+
for (const [key, value] of actual) {
|
|
36
|
+
if (!expected.has(key) || !deepEqual(value, expected.get(key))) return false;
|
|
37
|
+
}
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
if (Array.isArray(actual) && Array.isArray(expected)) {
|
|
41
|
+
return actual.length === expected.length && actual.every((item, index) => deepEqual(item, expected[index]));
|
|
42
|
+
}
|
|
43
|
+
if (isPlainObject(actual) && isPlainObject(expected)) {
|
|
44
|
+
const keys = Object.keys(actual);
|
|
45
|
+
if (keys.length !== Object.keys(expected).length) return false;
|
|
46
|
+
return keys.every((key) => Object.prototype.hasOwnProperty.call(expected, key) && deepEqual(actual[key], expected[key]));
|
|
47
|
+
}
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** This function throws `ContractViolation` when the two values are not deeply equal. */
|
|
52
|
+
export function same(actual: unknown, expected: unknown, what: string): void {
|
|
53
|
+
if (!deepEqual(actual, expected)) {
|
|
54
|
+
throw new ContractViolation(`${what}: expected ${show(expected)}, got ${show(actual)}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** This function throws `ContractViolation` when the condition is false. */
|
|
59
|
+
export function holds(condition: boolean, what: string): void {
|
|
60
|
+
if (!condition) throw new ContractViolation(what);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* This function starts an operation that must fail with a rejected promise, and gives the error.
|
|
65
|
+
* A synchronous throw breaks the contract too: each method of a storage gives a promise.
|
|
66
|
+
*/
|
|
67
|
+
export async function rejects(start: () => Promise<unknown>, what: string): Promise<unknown> {
|
|
68
|
+
let promise: Promise<unknown>;
|
|
69
|
+
try {
|
|
70
|
+
promise = start();
|
|
71
|
+
} catch (error) {
|
|
72
|
+
throw new ContractViolation(`${what}: the method threw at once (${show(error instanceof Error ? error.message : error)}), and did not give a rejected promise`);
|
|
73
|
+
}
|
|
74
|
+
holds(typeof promise?.then === "function", `${what}: the method did not give a promise`);
|
|
75
|
+
try {
|
|
76
|
+
await promise;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
return error;
|
|
79
|
+
}
|
|
80
|
+
throw new ContractViolation(`${what}: the promise did not reject`);
|
|
81
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@mark1russell7/collections/testing`: the checks of a contract suite.
|
|
3
|
+
*
|
|
4
|
+
* This entry imports no test framework. The runtime entries of the package do not import this entry.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export { ContractViolation, deepEqual, holds, rejects, same, show } from "./check.js";
|