-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathweb_worker_transfer.ts
302 lines (260 loc) · 9.8 KB
/
web_worker_transfer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import assert from 'assert';
import Grid from 'grid-index';
import Color from '../style-spec/util/color';
import {StylePropertyFunction, StyleExpression, ZoomDependentExpression, ZoomConstantExpression} from '../style-spec/expression/index';
import CompoundExpression from '../style-spec/expression/compound_expression';
import expressions from '../style-spec/expression/definitions/index';
import ResolvedImage from '../style-spec/expression/types/resolved_image';
import {AJAXError} from './ajax';
import Formatted, {FormattedSection} from '../style-spec/expression/types/formatted';
import type {Class} from '../types/class';
import type {GridIndex} from '../types/grid-index';
import type {Transferable} from '../types/transferable';
type SerializedObject = {
[_: string]: Serialized;
};
export type Serialized = null | undefined | boolean | number | string | Date | RegExp | ArrayBuffer | ArrayBufferView | ImageData | Array<Serialized> | SerializedObject;
type Klass = Class<any> & {
_classRegistryKey: string;
serialize?: (input: any, transferables?: Set<Transferable>) => SerializedObject;
};
type Registry = {
[_: string]: {
klass: Klass;
omit: ReadonlyArray<string>;
};
};
type RegisterOptions<T> = {
omit?: ReadonlyArray<keyof T>;
};
const registry: Registry = {};
/**
* Register the given class as serializable.
*
* @param options
* @param options.omit List of properties to omit from serialization (e.g., cached/computed properties)
*
* @private
*/
export function register<T extends any>(klass: Class<T>, name: string, options: RegisterOptions<T> = {}) {
assert(name, 'Can\'t register a class without a name.');
assert(!registry[name], `${name} is already registered.`);
Object.defineProperty(klass, '_classRegistryKey', {
value: name,
writable: false
});
registry[name] = {
klass,
omit: options.omit || []
} as unknown as Registry[string];
}
register(Object, 'Object');
type SerializedGrid = {
buffer: ArrayBuffer;
};
Grid.serialize = function serialize(grid: GridIndex, transferables?: Set<Transferable>): SerializedGrid {
const buffer = grid.toArrayBuffer();
if (transferables) {
transferables.add(buffer);
}
return {buffer};
};
Grid.deserialize = function deserialize(serialized: SerializedGrid): GridIndex {
return new Grid(serialized.buffer);
};
Object.defineProperty(Grid, 'name', {value: 'Grid'});
register(Grid as Class<Grid>, 'Grid');
register(Color, 'Color');
register(Error, 'Error');
register(Formatted, 'Formatted');
register(FormattedSection, 'FormattedSection');
register(AJAXError, 'AJAXError');
register(ResolvedImage, 'ResolvedImage');
register(StylePropertyFunction, 'StylePropertyFunction');
register(StyleExpression, 'StyleExpression', {omit: ['_evaluator']});
register(ZoomDependentExpression, 'ZoomDependentExpression');
register(ZoomConstantExpression, 'ZoomConstantExpression');
register(CompoundExpression, 'CompoundExpression', {omit: ['_evaluate']});
for (const name in expressions) {
if (!registry[(expressions[name] as any)._classRegistryKey]) register(expressions[name], `Expression${name}`);
}
function isArrayBuffer(val: any): boolean {
return val && typeof ArrayBuffer !== 'undefined' &&
(val instanceof ArrayBuffer || (val.constructor && val.constructor.name === 'ArrayBuffer'));
}
function isImageBitmap(val: any): boolean {
return self.ImageBitmap && val instanceof ImageBitmap;
}
/**
* Serialize the given object for transfer to or from a web worker.
*
* For non-builtin types, recursively serialize each property (possibly
* omitting certain properties - see register()), and package the result along
* with the constructor's `name` so that the appropriate constructor can be
* looked up in `deserialize()`.
*
* If a `transferables` set is provided, add any transferable objects (i.e.,
* any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed,
* this should happen in the client code, before using serialize().)
*
* @private
*/
export function serialize(input: unknown, transferables?: Set<Transferable> | null): Serialized {
if (input === null ||
input === undefined ||
typeof input === 'boolean' ||
typeof input === 'number' ||
typeof input === 'string' ||
input instanceof Boolean ||
input instanceof Number ||
input instanceof String ||
input instanceof Date ||
input instanceof RegExp) {
// @ts-expect-error - TS2322 - Type 'unknown' is not assignable to type 'Serialized'.
return input;
}
if (isArrayBuffer(input) || isImageBitmap(input)) {
if (transferables) {
transferables.add((input as ArrayBuffer));
}
return input as any;
}
if (ArrayBuffer.isView(input)) {
const view: ArrayBufferView = (input as any);
if (transferables) {
transferables.add(view.buffer);
}
return view;
}
if (input instanceof ImageData) {
if (transferables) {
transferables.add(input.data.buffer);
}
return input;
}
if (Array.isArray(input)) {
const serialized: Array<Serialized> = [];
for (const item of input) {
serialized.push(serialize(item, transferables));
}
return serialized;
}
if (input instanceof Map) {
const properties = {'$name': 'Map'};
for (const [key, value] of input.entries()) {
properties[key] = serialize(value);
}
return properties;
}
if (input instanceof Set) {
const properties = {'$name': 'Set'};
let idx = 0;
for (const value of input.values()) {
properties[++idx] = serialize(value);
}
return properties;
}
if (typeof input === 'object') {
const klass = input.constructor as Klass;
const name = klass._classRegistryKey;
if (!name) {
throw new Error(`can't serialize object of unregistered class ${name}`);
}
assert(registry[name]);
const properties: SerializedObject = klass.serialize ?
// (Temporary workaround) allow a class to provide static
// `serialize()` and `deserialize()` methods to bypass the generic
// approach.
// This temporary workaround lets us use the generic serialization
// approach for objects whose members include instances of dynamic
// StructArray types. Once we refactor StructArray to be static,
// we can remove this complexity.
klass.serialize(input, transferables) : {};
if (!klass.serialize) {
for (const key in input) {
if (!input.hasOwnProperty(key)) continue;
if (registry[name].omit.indexOf(key) >= 0) continue;
const property = (input as any)[key];
properties[key] = serialize(property, transferables);
}
if (input instanceof Error) {
properties['message'] = input.message;
}
} else {
// make sure statically serialized object survives transfer of $name property
assert(!transferables || !transferables.has((properties as any)));
}
if (properties['$name']) {
throw new Error('$name property is reserved for worker serialization logic.');
}
if (name !== 'Object') {
properties['$name'] = name;
}
return properties;
}
throw new Error(`can't serialize object of type ${typeof input}`);
}
export function deserialize(input: Serialized): unknown {
if (input === null ||
input === undefined ||
typeof input === 'boolean' ||
typeof input === 'number' ||
typeof input === 'string' ||
input instanceof Boolean ||
input instanceof Number ||
input instanceof String ||
input instanceof Date ||
input instanceof RegExp ||
isArrayBuffer(input) ||
isImageBitmap(input) ||
ArrayBuffer.isView(input) ||
input instanceof ImageData) {
return input;
}
if (Array.isArray(input)) {
return input.map(deserialize);
}
if (typeof input === 'object') {
const name = (input as any).$name || 'Object';
if (name === 'Map') {
const map = new Map();
for (const key of Object.keys(input)) {
if (key === '$name')
continue;
const value = (input as SerializedObject)[key];
map.set(key, deserialize(value));
}
return map;
}
if (name === 'Set') {
const set = new Set();
for (const key of Object.keys(input)) {
if (key === '$name')
continue;
const value = (input as SerializedObject)[key];
set.add(deserialize(value));
}
return set;
}
const {klass} = registry[name];
if (!klass) {
throw new Error(`can't deserialize unregistered class ${name}`);
}
// @ts-expect-error - TS2339 - Property 'deserialize' does not exist on type 'Class<any>'.
if (klass.deserialize) {
// @ts-expect-error - TS2339 - Property 'deserialize' does not exist on type 'Class<any>'.
return (klass.deserialize as typeof deserialize)(input);
}
const result: {
[_: string]: any;
} = Object.create(klass.prototype);
for (const key of Object.keys(input)) {
if (key === '$name')
continue;
const value = (input as SerializedObject)[key];
result[key] = deserialize(value);
}
return result;
}
throw new Error(`can't deserialize object of type ${typeof input}`);
}