@latticexyz/utils 2.0.0-alpha.1.21 → 2.0.0-alpha.1.211
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/dist/index.js +2 -995
- package/dist/index.js.map +1 -1
- package/package.json +20 -33
- package/src/CoordMap.spec.ts +57 -0
- package/src/CoordMap.ts +106 -0
- package/src/VoxelCoordMap.ts +76 -0
- package/src/area.ts +15 -0
- package/{dist/arrays.d.ts → src/arrays.ts} +8 -2
- package/src/bytes.spec.ts +77 -0
- package/src/bytes.ts +85 -0
- package/src/console.ts +62 -0
- package/src/cubic.spec.ts +14 -0
- package/src/cubic.ts +109 -0
- package/src/deferred.ts +14 -0
- package/src/distance.ts +11 -0
- package/src/enums.ts +13 -0
- package/src/eth.ts +42 -0
- package/src/guards.ts +10 -0
- package/src/hash.ts +20 -0
- package/{dist/index.d.ts → src/index.ts} +13 -1
- package/src/iterable.spec.ts +56 -0
- package/src/iterable.ts +59 -0
- package/{dist/math.d.ts → src/math.ts} +4 -1
- package/src/mobx.ts +26 -0
- package/src/objects.ts +16 -0
- package/src/pack.spec.ts +37 -0
- package/src/pack.ts +61 -0
- package/src/promise.ts +46 -0
- package/src/proxy.spec.ts +186 -0
- package/src/proxy.ts +101 -0
- package/{dist/random.d.ts → src/random.ts} +7 -2
- package/src/rx.spec.ts +45 -0
- package/src/rx.ts +124 -0
- package/src/sleep.ts +3 -0
- package/src/types.ts +48 -0
- package/src/uuid.ts +70 -0
- package/src/v2/TableId.ts +49 -0
- package/src/v2/arrayToHex.ts +3 -0
- package/src/v2/bytesToString.ts +1 -0
- package/src/v2/getTableIds.ts +10 -0
- package/src/v2/hexToArray.ts +12 -0
- package/{dist/v2/index.d.ts → src/v2/index.ts} +3 -1
- package/src/v2/isDefined.ts +3 -0
- package/src/v2/isHex.ts +6 -0
- package/src/v2/isNotNull.ts +3 -0
- package/src/v2/stringToBytes.ts +9 -0
- package/src/worker.ts +16 -0
- package/dist/CoordMap.d.ts +0 -26
- package/dist/VoxelCoordMap.d.ts +0 -23
- package/dist/area.d.ts +0 -3
- package/dist/bytes.d.ts +0 -10
- package/dist/console.d.ts +0 -52
- package/dist/cubic.d.ts +0 -32
- package/dist/deferred.d.ts +0 -5
- package/dist/distance.d.ts +0 -8
- package/dist/enums.d.ts +0 -5
- package/dist/eth.d.ts +0 -22
- package/dist/guards.d.ts +0 -3
- package/dist/hash.d.ts +0 -8
- package/dist/iterable.d.ts +0 -10
- package/dist/mobx.d.ts +0 -6
- package/dist/objects.d.ts +0 -11
- package/dist/pack.d.ts +0 -16
- package/dist/promise.d.ts +0 -4
- package/dist/proxy.d.ts +0 -8
- package/dist/rx.d.ts +0 -30
- package/dist/sleep.d.ts +0 -1
- package/dist/types.d.ts +0 -40
- package/dist/uuid.d.ts +0 -19
- package/dist/v2/TableId.d.ts +0 -10
- package/dist/v2/arrayToHex.d.ts +0 -1
- package/dist/v2/bytesToString.d.ts +0 -1
- package/dist/v2/hexToArray.d.ts +0 -1
- package/dist/v2/isDefined.d.ts +0 -1
- package/dist/v2/isHex.d.ts +0 -1
- package/dist/v2/stringToBytes16.d.ts +0 -1
- package/dist/worker.d.ts +0 -6
package/src/pack.spec.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { pack, unpack } from "./pack";
|
|
2
|
+
|
|
3
|
+
describe("pack", () => {
|
|
4
|
+
it("should pack multiple numbers into one 32 bit integer", () => {
|
|
5
|
+
const packed = pack([1, 2], [8, 24]);
|
|
6
|
+
expect(packed).toBe(parseInt("1000000000000000000000010", 2));
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it("should be the inverse of unpack", () => {
|
|
10
|
+
const bits = [8, 24];
|
|
11
|
+
const numbers = [16777218, 2072396467, -1];
|
|
12
|
+
|
|
13
|
+
for (const nums of numbers) {
|
|
14
|
+
expect(pack(unpack(nums, bits), bits)).toEqual(nums);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe("unpack", () => {
|
|
20
|
+
it("should unpack a packed 32 bit integer into multiple numbers", () => {
|
|
21
|
+
const unpacked = unpack(parseInt("1000000000000000000000010", 2), [8, 24]);
|
|
22
|
+
expect(unpacked).toEqual([1, 2]);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("should be the inverse of pack", () => {
|
|
26
|
+
const bits = [8, 24];
|
|
27
|
+
const numbers = [
|
|
28
|
+
[1, 2],
|
|
29
|
+
[123, 8798899],
|
|
30
|
+
[2 ** 8 - 1, 2 ** 24 - 1],
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
for (const nums of numbers) {
|
|
34
|
+
expect(unpack(pack(nums, bits), bits)).toEqual(nums);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
package/src/pack.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
function rightMask(input: number, keep: number): number {
|
|
2
|
+
return input & (2 ** keep - 1);
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Packs two unsigned integers in one 32 bit unsigned integer
|
|
7
|
+
* @param numbers Unsigned integers to be packed in 32 bit integer
|
|
8
|
+
* @param bitsPerNumber Bits for each number
|
|
9
|
+
* @returns Packed 32 bit unsigned integer
|
|
10
|
+
*/
|
|
11
|
+
export function pack(numbers: number[], bitsPerNumber: number[]): number {
|
|
12
|
+
// Total number of bits must be 32
|
|
13
|
+
if (bitsPerNumber.reduce((acc, curr) => acc + curr, 0) > 32) {
|
|
14
|
+
throw new Error("JS pretends integers are 32 bit when bitshifts are involved");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Array lengths must match
|
|
18
|
+
if (numbers.length !== bitsPerNumber.length) throw new Error("Arrays' lengths must match");
|
|
19
|
+
|
|
20
|
+
// Numbers must fit in number of bits and must be unsigned
|
|
21
|
+
for (let i = 0; i < numbers.length; i++) {
|
|
22
|
+
if (numbers[i] < 0) {
|
|
23
|
+
throw new Error("Underflow: can only pack unsigned integer");
|
|
24
|
+
}
|
|
25
|
+
if (numbers[i] > 2 ** bitsPerNumber[i] - 1) {
|
|
26
|
+
const error = `Overflow: ${numbers[i]} does not fit in ${bitsPerNumber[i]} bits`;
|
|
27
|
+
throw new Error(error);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Pack number
|
|
32
|
+
let packed = 0;
|
|
33
|
+
for (let i = 0; i < numbers.length; i++) {
|
|
34
|
+
packed = (packed << bitsPerNumber[i]) | numbers[i];
|
|
35
|
+
}
|
|
36
|
+
return packed;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Unpacks a packed 32 bit unsigned integer into the original unsigned integers
|
|
41
|
+
* @param packed Packed 32 bit unsigned integer
|
|
42
|
+
* @param bitsPerNumber Bits for each unsigned integer
|
|
43
|
+
* @returns Array of unpacked unsignd integers
|
|
44
|
+
*/
|
|
45
|
+
export function unpack(packed: number, bitsPerNumber: number[]): number[] {
|
|
46
|
+
const numbers: number[] = [];
|
|
47
|
+
let shiftedPacked = packed;
|
|
48
|
+
for (let i = bitsPerNumber.length - 1; i >= 0; i--) {
|
|
49
|
+
numbers.unshift(rightMask(shiftedPacked, bitsPerNumber[i]));
|
|
50
|
+
shiftedPacked = shiftedPacked >>> bitsPerNumber[i];
|
|
51
|
+
}
|
|
52
|
+
return numbers;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function packTuple(numbers: [number, number]): number {
|
|
56
|
+
return pack(numbers, [8, 24]);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function unpackTuple(packed: number): [number, number] {
|
|
60
|
+
return unpack(packed, [8, 24]) as [number, number];
|
|
61
|
+
}
|
package/src/promise.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import { deferred } from "./deferred";
|
|
3
|
+
import { sleep } from "./sleep";
|
|
4
|
+
|
|
5
|
+
export const range = function* (total = 0, step = 1, from = 0) {
|
|
6
|
+
// eslint-disable-next-line no-empty
|
|
7
|
+
for (let i = 0; i < total; yield from + i++ * step) {}
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export async function rejectAfter<T>(ms: number, msg: string): Promise<T> {
|
|
11
|
+
await sleep(ms);
|
|
12
|
+
throw new Error(msg);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const timeoutAfter = async <T>(promise: Promise<T>, ms: number, timeoutMsg: string) => {
|
|
16
|
+
return Promise.race([promise, rejectAfter<T>(ms, timeoutMsg)]);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const callWithRetry = <T>(
|
|
20
|
+
fn: (...args: any[]) => Promise<T>,
|
|
21
|
+
args: any[] = [],
|
|
22
|
+
maxRetries = 10,
|
|
23
|
+
retryInterval = 1000
|
|
24
|
+
): Promise<T> => {
|
|
25
|
+
const [resolve, reject, promise] = deferred<T>();
|
|
26
|
+
const process = async () => {
|
|
27
|
+
let res: T;
|
|
28
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
29
|
+
try {
|
|
30
|
+
res = await fn(...args);
|
|
31
|
+
resolve(res);
|
|
32
|
+
break;
|
|
33
|
+
} catch (e) {
|
|
34
|
+
if (i < maxRetries - 1) {
|
|
35
|
+
console.info("[CallWithRetry Failed] attempt number=" + i, fn);
|
|
36
|
+
console.error(e);
|
|
37
|
+
await sleep(Math.min(retryInterval * 2 ** i + Math.random() * 100, 15000));
|
|
38
|
+
} else {
|
|
39
|
+
reject(e as unknown as Error);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
process();
|
|
45
|
+
return promise;
|
|
46
|
+
};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { runInAction } from "mobx";
|
|
2
|
+
import { computed, observable } from "mobx";
|
|
3
|
+
import { deferred } from "./deferred";
|
|
4
|
+
import { cacheUntilReady } from "./proxy";
|
|
5
|
+
|
|
6
|
+
describe("cacheUntilReady", () => {
|
|
7
|
+
describe("property access", () => {
|
|
8
|
+
it("should immediately relay simple property access to the computed target if it is ready", () => {
|
|
9
|
+
const target = computed(() => ({ a: 1 }));
|
|
10
|
+
const proxy = cacheUntilReady(target);
|
|
11
|
+
expect(proxy.a).toBe(1);
|
|
12
|
+
expect(proxy.proxied).toBe(false);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it("should immediately relay simple property access to the observable target if it is ready", () => {
|
|
16
|
+
const target = observable.box({ a: 1 });
|
|
17
|
+
const proxy = cacheUntilReady(target);
|
|
18
|
+
expect(proxy.a).toBe(1);
|
|
19
|
+
expect(proxy.proxied).toBe(false);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("should immediately relay deep property access to the computed target if it is ready", () => {
|
|
23
|
+
const target = computed(() => ({ a: { b: { c: 2 } } }));
|
|
24
|
+
const proxy = cacheUntilReady(target);
|
|
25
|
+
expect(proxy.a.b.c).toBe(2);
|
|
26
|
+
expect(proxy.proxied).toBe(false);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("should immediately relay deep property access to the observable target if it is ready", () => {
|
|
30
|
+
const target = observable.box({ a: { b: 2 } });
|
|
31
|
+
const proxy = cacheUntilReady(target);
|
|
32
|
+
expect(proxy.a.b).toBe(2);
|
|
33
|
+
expect(proxy.proxied).toBe(false);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it("should return undefined for property access if the target is not ready", () => {
|
|
37
|
+
const target = observable.box<{ a: { b: number } } | undefined>(undefined);
|
|
38
|
+
const proxy = cacheUntilReady(target);
|
|
39
|
+
const result1 = proxy.a;
|
|
40
|
+
const result2 = proxy.a.b;
|
|
41
|
+
|
|
42
|
+
expect(JSON.stringify(result1)).toBe(JSON.stringify({ proxied: true }));
|
|
43
|
+
expect(JSON.stringify(result2)).toBe(JSON.stringify({ proxied: true }));
|
|
44
|
+
expect(proxy.proxied).toBe(true);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe("function calls", () => {
|
|
49
|
+
it("should immediately relay top level function calls to the computed target it if it ready", () => {
|
|
50
|
+
const target = computed(() => ({
|
|
51
|
+
a: () => 1,
|
|
52
|
+
}));
|
|
53
|
+
|
|
54
|
+
const proxy = cacheUntilReady(target);
|
|
55
|
+
|
|
56
|
+
expect(proxy.a()).toBe(1);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("should immediately relay top level function calls to the observable target it if it ready", () => {
|
|
60
|
+
const target = observable.box({
|
|
61
|
+
a: () => 1,
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const proxy = cacheUntilReady(target);
|
|
65
|
+
|
|
66
|
+
expect(proxy.a()).toBe(1);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("should immediately relay deep nested function calls to the computed target it if it ready", () => {
|
|
70
|
+
const target = computed(() => ({
|
|
71
|
+
a: { b: () => 1 },
|
|
72
|
+
}));
|
|
73
|
+
|
|
74
|
+
const proxy = cacheUntilReady(target);
|
|
75
|
+
|
|
76
|
+
expect(proxy.a.b()).toBe(1);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("should immediately relay deep nested function calls to the observable target it if it ready", () => {
|
|
80
|
+
const target = observable.box({
|
|
81
|
+
a: { b: () => 1 },
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const proxy = cacheUntilReady(target);
|
|
85
|
+
|
|
86
|
+
expect(proxy.a.b()).toBe(1);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("should chache top level function calls to the target until it is ready", async () => {
|
|
90
|
+
const target = observable.box<{ a: (n: number) => number } | undefined>(undefined);
|
|
91
|
+
|
|
92
|
+
const proxy = cacheUntilReady(target);
|
|
93
|
+
|
|
94
|
+
// Target is not ready yet, but function is called already
|
|
95
|
+
const result1 = proxy.a(1);
|
|
96
|
+
const result2 = proxy.a(2);
|
|
97
|
+
|
|
98
|
+
// Now target is ready
|
|
99
|
+
runInAction(() => target.set({ a: (n) => n }));
|
|
100
|
+
|
|
101
|
+
// Cached function calls are applied,
|
|
102
|
+
expect(await result1).toEqual(1);
|
|
103
|
+
expect(await result2).toEqual(2);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("should chache nested function calls to the target until it is ready", async () => {
|
|
107
|
+
const target = observable.box<{ a: { b: (n: number) => number } } | undefined>(undefined);
|
|
108
|
+
|
|
109
|
+
const proxy = cacheUntilReady(target);
|
|
110
|
+
|
|
111
|
+
// Target is not ready yet, but function is called already
|
|
112
|
+
const result1 = proxy.a.b(1);
|
|
113
|
+
const result2 = proxy.a.b(2);
|
|
114
|
+
|
|
115
|
+
const getResult3 = async () => proxy.a.b((await result1) + (await result2));
|
|
116
|
+
const result3 = getResult3();
|
|
117
|
+
|
|
118
|
+
// Now target is ready
|
|
119
|
+
runInAction(() => target.set({ a: { b: (n) => n + 1 } }));
|
|
120
|
+
|
|
121
|
+
// Cached function calls are applied,
|
|
122
|
+
expect(await result1).toEqual(2);
|
|
123
|
+
expect(await result2).toEqual(3);
|
|
124
|
+
expect(await result3).toEqual(6);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("should chache nested function calls without parameters to the target until it is ready", async () => {
|
|
128
|
+
const target = observable.box<{ a: { b: () => number } } | undefined>(undefined);
|
|
129
|
+
|
|
130
|
+
const proxy = cacheUntilReady(target);
|
|
131
|
+
|
|
132
|
+
// Target is not ready yet, but function is called already
|
|
133
|
+
const result1 = proxy.a.b();
|
|
134
|
+
const result2 = proxy.proxied && proxy.a.b();
|
|
135
|
+
|
|
136
|
+
// Now target is ready
|
|
137
|
+
runInAction(() => target.set({ a: { b: () => 1 } }));
|
|
138
|
+
|
|
139
|
+
// Cached function calls are applied,
|
|
140
|
+
expect(await result1).toEqual(1);
|
|
141
|
+
expect(await result2).toEqual(1);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("should chache nested function calls with variable parameters to the target until it is ready", async () => {
|
|
145
|
+
const target = observable.box<{ a: { b: (...args: number[]) => number } } | undefined>(undefined);
|
|
146
|
+
|
|
147
|
+
const proxy = cacheUntilReady(target);
|
|
148
|
+
|
|
149
|
+
// Target is not ready yet, but function is called already
|
|
150
|
+
const result1 = proxy.a.b();
|
|
151
|
+
const result2 = proxy.a.b(1);
|
|
152
|
+
const result3 = proxy.a.b(1, 2);
|
|
153
|
+
const result4 = proxy.a.b(1, 2, 3);
|
|
154
|
+
|
|
155
|
+
// Now target is ready
|
|
156
|
+
runInAction(() => target.set({ a: { b: (...args) => args.reduce((acc, curr) => acc + curr, 0) } }));
|
|
157
|
+
|
|
158
|
+
// Cached function calls are applied,
|
|
159
|
+
expect(await result1).toEqual(0);
|
|
160
|
+
expect(await result2).toEqual(1);
|
|
161
|
+
expect(await result3).toEqual(3);
|
|
162
|
+
expect(await result4).toEqual(6);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("should return a non-nested proxy if the called target function returns a proxy", async () => {
|
|
166
|
+
const target = observable.box<{ a: { b: () => Promise<number> } } | undefined>(undefined);
|
|
167
|
+
|
|
168
|
+
const proxy = cacheUntilReady(target);
|
|
169
|
+
|
|
170
|
+
// Target is not ready yet, but function is called already
|
|
171
|
+
const result1 = proxy.a.b();
|
|
172
|
+
const result2 = proxy.a.b();
|
|
173
|
+
|
|
174
|
+
const [resolve, , promise] = deferred<number>();
|
|
175
|
+
// Now target is ready
|
|
176
|
+
runInAction(() => target.set({ a: { b: () => promise } }));
|
|
177
|
+
|
|
178
|
+
// Now resolve the promise returned by the target function
|
|
179
|
+
resolve(1);
|
|
180
|
+
|
|
181
|
+
// Cached function calls are applied,
|
|
182
|
+
expect(await result1).toEqual(1);
|
|
183
|
+
expect(await result2).toEqual(1);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
});
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import { IComputedValue, IObservableValue, reaction } from "mobx";
|
|
3
|
+
import DeepProxy from "proxy-deep";
|
|
4
|
+
import { deferred } from "./deferred";
|
|
5
|
+
import { isFunction, isObject } from "./guards";
|
|
6
|
+
import { Cached } from "./types";
|
|
7
|
+
|
|
8
|
+
function deepAccess(target: Record<string, unknown>, path: string[]): any {
|
|
9
|
+
if (path.length === 0) return target;
|
|
10
|
+
if (path.length === 1) return target[path[0]];
|
|
11
|
+
const [next, ...rest] = path;
|
|
12
|
+
const nextTarget = target[next];
|
|
13
|
+
if (!isObject(nextTarget)) throw new Error("Path does not exist on the target");
|
|
14
|
+
return deepAccess(nextTarget, rest);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Caches any function calls to the target until the target is ready.
|
|
19
|
+
* @param target T extends Cachable
|
|
20
|
+
* @returns Cached<T>
|
|
21
|
+
*/
|
|
22
|
+
export function cacheUntilReady<T extends Record<string, any>>(
|
|
23
|
+
target: IObservableValue<T | undefined> | IComputedValue<T | undefined>
|
|
24
|
+
): Cached<T> {
|
|
25
|
+
// The call queue contains the path and arguments of calls to the
|
|
26
|
+
// proxiedTarget while the target was not available yet.
|
|
27
|
+
// It also contains resolve and reject methods to fulfil the promise
|
|
28
|
+
// returned when calling the proxiedTarget once the target becomes available.
|
|
29
|
+
const callQueue: {
|
|
30
|
+
path: string[];
|
|
31
|
+
args?: any[];
|
|
32
|
+
resolve: (result: any) => void;
|
|
33
|
+
reject: (e: Error) => void;
|
|
34
|
+
}[] = [];
|
|
35
|
+
|
|
36
|
+
// The proxiedTarget proxies all calls to the target.
|
|
37
|
+
// If a function is called on the proxiedTarget while the target is not
|
|
38
|
+
// available, a promise is returned and the call will be stored in the callQueue
|
|
39
|
+
// until the target becomes available and the promise is fulfilled.
|
|
40
|
+
const proxiedTarget = new DeepProxy(
|
|
41
|
+
{},
|
|
42
|
+
{
|
|
43
|
+
get(_t, prop) {
|
|
44
|
+
const targetReady = target.get();
|
|
45
|
+
if (targetReady) {
|
|
46
|
+
// If the target is ready, relay all calls directly to the target
|
|
47
|
+
// (Except for the "proxied" key, which indicates whether the object is currently proxied)
|
|
48
|
+
if (prop === "proxied") return false;
|
|
49
|
+
return Reflect.get(targetReady, prop);
|
|
50
|
+
} else {
|
|
51
|
+
// Note: if the target is not available, accessing a property returns another proxy,
|
|
52
|
+
// not a Promise. It is possible to check whether a value is currently proxied using the proxied key.
|
|
53
|
+
if (prop === "proxied") return true;
|
|
54
|
+
if (prop === "name") return "ProxiedTarget";
|
|
55
|
+
if (prop === "toJSON") return () => ({ proxied: true });
|
|
56
|
+
return this.nest(() => void 0);
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
apply(_, thisArg, args) {
|
|
60
|
+
const targetReady = target.get();
|
|
61
|
+
if (targetReady) {
|
|
62
|
+
// If the target is ready, relay all calls directly to the target
|
|
63
|
+
const targetFunc = deepAccess(targetReady, this.path);
|
|
64
|
+
if (!isFunction(targetFunc)) throw new Error("Target is not callable");
|
|
65
|
+
return Reflect.apply(targetFunc, thisArg, args);
|
|
66
|
+
} else {
|
|
67
|
+
// Otherwise store the call and relay it to the target later once it's ready.
|
|
68
|
+
// The return value of this call is a promise, that gets resolved once the target is ready.
|
|
69
|
+
const [resolve, reject, promise] = deferred();
|
|
70
|
+
callQueue.push({ path: this.path, args, resolve, reject });
|
|
71
|
+
return promise;
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
reaction(
|
|
78
|
+
() => target.get(),
|
|
79
|
+
(targetReady) => {
|
|
80
|
+
if (!targetReady) return;
|
|
81
|
+
// Move all entries from callQueue to queuedCalls
|
|
82
|
+
const queuedCalls = callQueue.splice(0);
|
|
83
|
+
for (const { path, args, resolve, reject } of queuedCalls) {
|
|
84
|
+
const target = deepAccess(targetReady, path);
|
|
85
|
+
if (args && isFunction(target)) {
|
|
86
|
+
(async () => {
|
|
87
|
+
try {
|
|
88
|
+
resolve(await target(...args));
|
|
89
|
+
} catch (e: any) {
|
|
90
|
+
reject(e);
|
|
91
|
+
}
|
|
92
|
+
})();
|
|
93
|
+
} else {
|
|
94
|
+
resolve(target);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
return proxiedTarget as Cached<T>;
|
|
101
|
+
}
|
|
@@ -4,9 +4,14 @@
|
|
|
4
4
|
* @param from Lower bound (included). Default 0.
|
|
5
5
|
* @returns A random integer between from and to.
|
|
6
6
|
*/
|
|
7
|
-
export
|
|
7
|
+
export function random(to: number, from = 0): number {
|
|
8
|
+
return Math.floor(Math.random() * (to - from + 1)) + from;
|
|
9
|
+
}
|
|
10
|
+
|
|
8
11
|
/**
|
|
9
12
|
* @param array Array to pick a random element from.
|
|
10
13
|
* @returns Random element from the given array.
|
|
11
14
|
*/
|
|
12
|
-
export
|
|
15
|
+
export function pickRandom<T>(array: [T, ...T[]]): T {
|
|
16
|
+
return array[random(array.length - 1)];
|
|
17
|
+
}
|
package/src/rx.spec.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Subject } from "rxjs";
|
|
2
|
+
import { awaitStreamValue, streamToComputed } from "./rx";
|
|
3
|
+
import { sleep } from "./sleep";
|
|
4
|
+
|
|
5
|
+
describe("streamToComputed", () => {
|
|
6
|
+
it("should return a computed value that corresponds to the last stream value", () => {
|
|
7
|
+
const stream = new Subject<number>();
|
|
8
|
+
const comp = streamToComputed(stream);
|
|
9
|
+
expect(comp.get()).toBeUndefined();
|
|
10
|
+
|
|
11
|
+
stream.next(1);
|
|
12
|
+
expect(comp.get()).toBe(1);
|
|
13
|
+
|
|
14
|
+
stream.next(2);
|
|
15
|
+
expect(comp.get()).toBe(2);
|
|
16
|
+
|
|
17
|
+
stream.next(3);
|
|
18
|
+
stream.next(4);
|
|
19
|
+
expect(comp.get()).toBe(4);
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe("awaitStreamValue", () => {
|
|
24
|
+
it("should return a promise that resolves once the requested stream value is emitted", async () => {
|
|
25
|
+
const stream = new Subject<number>();
|
|
26
|
+
const promise = awaitStreamValue(stream, (v) => v === 1);
|
|
27
|
+
|
|
28
|
+
let isFulfilled = false;
|
|
29
|
+
(async () => {
|
|
30
|
+
await promise;
|
|
31
|
+
isFulfilled = true;
|
|
32
|
+
})();
|
|
33
|
+
|
|
34
|
+
await sleep(100);
|
|
35
|
+
expect(isFulfilled).toBe(false);
|
|
36
|
+
|
|
37
|
+
stream.next(2);
|
|
38
|
+
await sleep(100);
|
|
39
|
+
expect(isFulfilled).toBe(false);
|
|
40
|
+
|
|
41
|
+
stream.next(1);
|
|
42
|
+
await sleep(100);
|
|
43
|
+
expect(isFulfilled).toBe(true);
|
|
44
|
+
});
|
|
45
|
+
});
|
package/src/rx.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import {
|
|
2
|
+
concatMap,
|
|
3
|
+
delay,
|
|
4
|
+
filter,
|
|
5
|
+
first,
|
|
6
|
+
mergeMap,
|
|
7
|
+
Observable,
|
|
8
|
+
of,
|
|
9
|
+
OperatorFunction,
|
|
10
|
+
pipe,
|
|
11
|
+
ReplaySubject,
|
|
12
|
+
scan,
|
|
13
|
+
Timestamp,
|
|
14
|
+
timestamp,
|
|
15
|
+
} from "rxjs";
|
|
16
|
+
import { computed, IComputedValue, IObservableValue, observable, reaction, runInAction, toJS } from "mobx";
|
|
17
|
+
import { deferred } from "./deferred";
|
|
18
|
+
import { awaitValue } from "./mobx";
|
|
19
|
+
|
|
20
|
+
export function filterNullish<T>(): OperatorFunction<T, NonNullable<T>> {
|
|
21
|
+
return pipe<Observable<T>, Observable<NonNullable<T>>>(
|
|
22
|
+
filter<T>((x: T) => x != null) as OperatorFunction<T, NonNullable<T>>
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function awaitPromise<T extends Promise<unknown>>(): OperatorFunction<T, Awaited<T>> {
|
|
27
|
+
return pipe(concatMap((x: T) => x)) as OperatorFunction<T, Awaited<T>>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* RxJS operator to stretch out an event stream by a given delay per event
|
|
32
|
+
* @param spacingDelayMs Delay between each event in ms
|
|
33
|
+
* @returns stream of events with at least spacingDelayMs spaceing between event
|
|
34
|
+
*/
|
|
35
|
+
export function stretch<T>(spacingDelayMs: number) {
|
|
36
|
+
return pipe(
|
|
37
|
+
timestamp<T>(),
|
|
38
|
+
scan((acc: (Timestamp<T> & { delay: number }) | null, curr: Timestamp<T>) => {
|
|
39
|
+
// calculate delay needed to offset next emission
|
|
40
|
+
let delay = 0;
|
|
41
|
+
if (acc !== null) {
|
|
42
|
+
const timeDelta = curr.timestamp - acc.timestamp;
|
|
43
|
+
delay = timeDelta > spacingDelayMs ? 0 : spacingDelayMs - timeDelta;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
timestamp: curr.timestamp,
|
|
48
|
+
delay: delay,
|
|
49
|
+
value: curr.value,
|
|
50
|
+
};
|
|
51
|
+
}, null),
|
|
52
|
+
filterNullish(),
|
|
53
|
+
mergeMap((i) => of(i.value).pipe(delay(i.delay)), 1)
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function observableToComputed<T>(obs: IObservableValue<T>): IComputedValue<T> {
|
|
58
|
+
return computed(() => obs.get());
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function computedToStream<T>(comp: IComputedValue<T> | IObservableValue<T>): Observable<T> {
|
|
62
|
+
const stream = new ReplaySubject<T>(1);
|
|
63
|
+
reaction(
|
|
64
|
+
() => comp.get(),
|
|
65
|
+
(value) => {
|
|
66
|
+
if (value != null) stream.next(value);
|
|
67
|
+
},
|
|
68
|
+
{ fireImmediately: true }
|
|
69
|
+
);
|
|
70
|
+
return stream;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function observableToStream<T>(obs: T): Observable<T> {
|
|
74
|
+
const stream = new ReplaySubject<T>(1);
|
|
75
|
+
reaction(
|
|
76
|
+
() => toJS(obs),
|
|
77
|
+
(value) => {
|
|
78
|
+
if (value != null) stream.next(value);
|
|
79
|
+
},
|
|
80
|
+
{ fireImmediately: true }
|
|
81
|
+
);
|
|
82
|
+
return stream;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function streamToComputed<T>(stream$: Observable<T>): IComputedValue<T | undefined> {
|
|
86
|
+
const value = observable.box<T | undefined>();
|
|
87
|
+
stream$.subscribe((val) => runInAction(() => value.set(val)));
|
|
88
|
+
return computed(() => value.get());
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function streamToDefinedComputed<T>(stream$: Observable<T>): Promise<IComputedValue<T>> {
|
|
92
|
+
const value = observable.box<T>();
|
|
93
|
+
stream$.subscribe((val) => runInAction(() => value.set(val)));
|
|
94
|
+
const computedValue = computed(() => value.get());
|
|
95
|
+
await awaitValue(computedValue);
|
|
96
|
+
return computedValue as IComputedValue<T>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
*
|
|
101
|
+
* @param stream$ RxJS observable to check for the given value
|
|
102
|
+
* @param predicate Predicate to check
|
|
103
|
+
* @returns A promise that resolves with the requested value once the predicate is true
|
|
104
|
+
*/
|
|
105
|
+
export async function awaitStreamValue<T>(
|
|
106
|
+
stream$: Observable<T>,
|
|
107
|
+
predicate: (value: T) => boolean = (value) => value != null
|
|
108
|
+
): Promise<T> {
|
|
109
|
+
const [resolve, , promise] = deferred<T>();
|
|
110
|
+
stream$.pipe(first(predicate)).subscribe(resolve);
|
|
111
|
+
return promise;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Turns a stream into an updating object for easy access outside of rxjs
|
|
116
|
+
* @param stream$ Stream to turn into a wrapped value
|
|
117
|
+
* @returns Object with `current` key corresponding to last stream value
|
|
118
|
+
*/
|
|
119
|
+
export async function streamToWrappedValue<T>(stream$: Observable<T>): Promise<{ current: T }> {
|
|
120
|
+
const value: { current?: T } = {};
|
|
121
|
+
stream$.subscribe((v) => (value.current = v));
|
|
122
|
+
value.current = await awaitStreamValue(stream$);
|
|
123
|
+
return value as { current: T };
|
|
124
|
+
}
|
package/src/sleep.ts
ADDED
package/src/types.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { enableLogger } from "./console";
|
|
2
|
+
|
|
3
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
4
|
+
export type Func<A extends any[], R> = (...args: A) => R;
|
|
5
|
+
export type AsyncFunc<A extends any[], R> = R extends Promise<unknown> ? (...args: A) => R : (...args: A) => Promise<R>;
|
|
6
|
+
|
|
7
|
+
export type CachedValue<V, Proxied extends boolean> = Proxied extends true
|
|
8
|
+
? V extends Func<infer A, infer B>
|
|
9
|
+
? AsyncFunc<A, B>
|
|
10
|
+
: V extends Record<string, any>
|
|
11
|
+
? Cached<V> & { proxied: true }
|
|
12
|
+
: { proxied: true }
|
|
13
|
+
: V extends Func<infer A, infer B>
|
|
14
|
+
? Func<A, B>
|
|
15
|
+
: V extends Record<string, any>
|
|
16
|
+
? V
|
|
17
|
+
: V & { proxied: false };
|
|
18
|
+
|
|
19
|
+
export type Cached<C> =
|
|
20
|
+
| ({ proxied: false } & { [key in keyof C]: CachedValue<C[key], false> })
|
|
21
|
+
| ({ proxied: true } & { [key in keyof C]: CachedValue<C[key], true> });
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @deprecated Use Awaited<T> instead
|
|
25
|
+
*/
|
|
26
|
+
export type PromiseValue<T> = Awaited<T>;
|
|
27
|
+
|
|
28
|
+
export type ValueOf<T extends object> = T[keyof T];
|
|
29
|
+
|
|
30
|
+
export type Area = {
|
|
31
|
+
x: number;
|
|
32
|
+
y: number;
|
|
33
|
+
width: number;
|
|
34
|
+
height: number;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type Coord = {
|
|
38
|
+
x: number;
|
|
39
|
+
y: number;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type VoxelCoord = {
|
|
43
|
+
x: number;
|
|
44
|
+
y: number;
|
|
45
|
+
z: number;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type Logger = ReturnType<typeof enableLogger>;
|