-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
303 lines (303 loc) · 12.1 KB
/
index.js
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
303
"use strict";
// Copyright (c) 2022 System233
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
Object.defineProperty(exports, "__esModule", { value: true });
exports.deregister = exports.register = exports.parse = exports.stringify = exports.backward = exports.forward = exports.TSON = void 0;
;
/**
TSON - A Type-safe Serializer like JSON
*/
class TSON {
types = [];
map = {};
/** @hidden */
refname = '$ref';
constructor() {
this.register(Object, x => x, x => x, null, true);
this.register(String, x => new String(x), x => x.valueOf());
this.register(Number, x => new Number(x), x => x.valueOf());
this.register(Boolean, x => new Boolean(x), x => x.valueOf());
this.register(RegExp, (x) => new RegExp(x.source, x.flags), x => ({ source: x.source, flags: x.flags }));
this.register(Set, (x) => new Set(x), x => Array.from(x.values()), null, true);
this.register(Map, (x) => new Map(x), x => Array.from(x.entries()), null, true);
this.register(ArrayBuffer, (x) => new Uint8Array(x).buffer, x => Array.from(new Uint8Array(x)));
[
Int8Array, Uint8Array, Uint8ClampedArray,
Int16Array, Uint16Array,
Int32Array, Uint32Array,
Float32Array, Float64Array,
BigInt64Array, BigUint64Array
].forEach(constructor => this.register(constructor, (x) => new constructor(x.buffer, x.offset, x.length), (x) => ({ buffer: x.buffer, offset: x.byteOffset, length: x.length }), null, true));
this.register(DataView, data => new DataView(data.buffer, data.offset, data.length), value => ({ buffer: value.buffer, offset: value.byteOffset, length: value.byteLength }), null, true);
this.register('Array', x => x, x => x, x => Array.isArray(x), true);
this.register('Date', x => new Date(x), x => x.toJSON(), x => x instanceof Date);
this.register('NaN', () => NaN, () => void 0, x => Number.isNaN(x));
this.register('Infinity', (x) => x ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY, (x) => x > 0, x => typeof x == 'number' && !Number.isNaN(x) && !Number.isFinite(x));
const builtins = Object.values(Object.getOwnPropertyDescriptors(Symbol)).filter(value => typeof value.value == 'symbol').map(x => x.value);
const n2smap = Object.fromEntries(builtins.map(symbol => [symbol.description, symbol]));
const s2nmap = Object.fromEntries(builtins.map(symbol => [symbol, symbol.description]));
this.register('symbol', data => {
if (!data.description) {
return Symbol();
}
if (data.builtin) {
return n2smap[data.description];
}
if (data.shared) {
return Symbol.for(data.description);
}
return Symbol(data.description);
}, value => ({
description: value.description,
builtin: value in s2nmap,
shared: value.description != null && !!Symbol.for(value.description)
}), value => typeof value == 'symbol');
this.register('bigint', x => BigInt(x), x => x.toString(), x => typeof x == 'bigint');
this.register('undefined', () => void 0, () => void 0, x => typeof x == 'undefined');
this.register('boolean', x => x, x => x, x => typeof x == 'boolean');
this.register('string', x => x, x => x, x => typeof x == 'string');
this.register('number', x => x, x => x, x => typeof x == 'number' && !Number.isNaN(x) && Number.isFinite(x));
}
/** @hidden */
referenceable(value) {
return value != null && (typeof value == 'object' || typeof value == 'symbol');
}
/** @hidden */
reference(path) {
return {
type: this.refname,
data: path
};
}
/** @hidden */
dereference(data) {
if (data.type == this.refname) {
return data.data;
}
return null;
}
/**
* Transform the value to a TSONData object.
* The implementation of all `forward` overloads.
* @param value A value to be transformed.
* @returns The `TSONData` object of the `value`.
*/
forward(value) {
const map = new Map;
const reference = (value, path) => {
const ref = map.get(value);
if (ref == null) {
map.set(value, path);
return null;
}
return this.reference(ref);
};
const iforward = (value, path) => {
if (value === null) {
return null;
}
if (this.referenceable(value)) {
const ref = reference(value, path);
if (ref) {
return ref;
}
}
const typeDef = this.types.find(d => d.match(value));
if (!typeDef) {
return value;
}
const data = typeDef.dump(value);
const type = typeDef.type;
if (typeDef.recursive && data != null && typeof data == 'object') {
if (Array.isArray(data)) {
return {
type,
data: data.map((item, index) => iforward(item, [...path, index]))
};
}
return {
type,
data: Object.fromEntries(Object.entries(data).map(([key, value]) => {
return [key, iforward(value, [...path, key])];
}))
};
}
return {
type,
data
};
};
return iforward(value, []);
}
/**
* Transform the `TSONData` back to the original object.
* @param value A TSONData object or array of TSONData objects to be transformed.
* @returns The original object of the `TSONData` object.
*/
backward(value) {
let refs = [];
const map = {};
const get = (path) => {
const key = JSON.stringify(path);
if (key in map) {
return map[key];
}
return null;
};
const set = (path, value) => {
if (this.referenceable(value)) {
const key = JSON.stringify(path);
map[key] = value;
}
};
const ibackward = (value, path) => {
const record = (value) => {
set(path, value);
return value;
};
if (value === null) {
return null;
}
if (Array.isArray(value)) {
return record(value.map((item, index) => ibackward(item, [...path, index])));
}
const ref = this.dereference(value);
if (ref != null) {
const obj = get(ref);
if (!obj) {
refs.push([value, path]);
}
return obj;
}
const { type, data } = value;
const typeDef = this.map[type];
if (typeDef != null) {
if (typeDef.recursive && data != null && typeof data == 'object') {
if (Array.isArray(data)) {
return record(typeDef.load(data.map((item, index) => ibackward(item, [...path, index]))));
}
return record(typeDef.load(Object.fromEntries(Object.entries(data).map(([key, value]) => {
return [key, ibackward(value, [...path, key])];
}))));
}
return record(typeDef.load(data));
}
return record(data);
};
const data = ibackward(value, []);
while (refs.length) {
const cached = refs;
refs = [];
cached.forEach(([value, path]) => {
const distKey = path[path.length - 1];
const distObj = get(path.slice(0, -1));
distObj[distKey] = ibackward(value, path);
});
}
return data;
}
/**
* Wrapper for `JSON.stringify(TSON.forward(value),replacer,space)`\
* Converts a JavaScript value to a TSON string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value, replacer, space) {
return JSON.stringify(this.forward(value), replacer, space);
}
/**
* Wrapper for `TSON.backward(JSON.parse(text, reviver))`\
* Converts a TSON string into an object.
* @param text A valid TSON string.
* @param reviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is.
*/
parse(text, reviver) {
return this.backward(JSON.parse(text, reviver));
}
/**
* Register a TSON Serializer for Type.
* The implementation of all `register` overloads.
* @param serializer TSONSerializer object or string name or type constructor.
* @param load A function to deserialize the data.
* @param dump A function to serialize the value.
* @param match A function that checks the value matches this serializer. If null, `value instanceof constructor` is used by default.
* @param recursive Whether to process `load()` input and `dump()` output recursively.
* @returns `true` if register was successful, `false` otherwise.
*/
register(serializer, load, dump, match, recursive) {
if (typeof serializer == 'string') {
if (!load || !dump || !match) {
return false;
}
return this.register({
type: serializer,
load,
dump,
match,
recursive: !!recursive
});
}
if (typeof serializer == 'function') {
if (!load || !dump) {
return false;
}
return this.register({
type: serializer.name,
load,
dump,
match: match || (x => x instanceof serializer),
recursive: !!recursive
});
}
if (serializer.type in this.map) {
return false;
}
this.types.splice(0, 0, serializer);
this.map[serializer.type] = serializer;
return true;
}
/**
* Deregister a TSON Serializer.
* @param name The name of the serializer.
* @returns `true` if deregister was successful, `false` otherwise.
*/
deregister(name) {
if (name in this.map) {
const index = this.types.findIndex(x => x.type == name);
this.types.splice(index, 1);
delete this.map[name];
return true;
}
return false;
}
static instance = new TSON;
/**Link to {@link TSON.forward}. */
static forward = this.instance.forward.bind(this.instance);
/**Link to {@link TSON.backward}. */
static backward = this.instance.backward.bind(this.instance);
/**Link to {@link TSON.stringify}. */
static stringify = this.instance.stringify.bind(this.instance);
/**Link to {@link TSON.parse}. */
static parse = this.instance.parse.bind(this.instance);
/**Link to {@link TSON.register}. */
static register = this.instance.register.bind(this.instance);
/**Link to {@link TSON.deregister}. */
static deregister = this.instance.deregister.bind(this.instance);
}
exports.TSON = TSON;
/**Link to {@link TSON.forward}. */
exports.forward = TSON.forward;
/**Link to {@link TSON.backward}. */
exports.backward = TSON.backward;
/**Link to {@link TSON.stringify}. */
exports.stringify = TSON.stringify;
/**Link to {@link TSON.parse}. */
exports.parse = TSON.parse;
/**Link to {@link TSON.register}. */
exports.register = TSON.register;
/**Link to {@link TSON.deregister}. */
exports.deregister = TSON.deregister;
exports.default = TSON;