json-as 0.9.17 → 0.9.18

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,460 +1,514 @@
1
- import { FieldDeclaration } from "assemblyscript/dist/assemblyscript.js";
1
+ import {
2
+ FieldDeclaration,
3
+ StringLiteralExpression,
4
+ } from "assemblyscript/dist/assemblyscript.js";
2
5
  import { toString, isStdlib } from "visitor-as/dist/utils.js";
3
6
  import { BaseVisitor, SimpleParser } from "visitor-as/dist/index.js";
4
7
  import { Transform } from "assemblyscript/dist/transform.js";
5
8
  class JSONTransform extends BaseVisitor {
6
- constructor() {
7
- super(...arguments);
8
- this.schemasList = [];
9
- this.sources = new Set();
9
+ constructor() {
10
+ super(...arguments);
11
+ this.schemasList = [];
12
+ this.sources = new Set();
13
+ }
14
+ visitMethodDeclaration() {}
15
+ visitClassDeclaration(node) {
16
+ if (!node.decorators?.length) return;
17
+ let found = false;
18
+ for (const decorator of node.decorators) {
19
+ const name = decorator.name.text;
20
+ if (name === "json" || name === "serializable") {
21
+ found = true;
22
+ break;
23
+ }
10
24
  }
11
- visitMethodDeclaration() { }
12
- visitClassDeclaration(node) {
13
- if (!node.decorators?.length)
14
- return;
15
- let found = false;
16
- for (const decorator of node.decorators) {
17
- const name = decorator.name.text;
18
- if (name === "json" || name === "serializable") {
19
- found = true;
20
- break;
21
- }
22
- }
23
- if (!found)
24
- return;
25
- const schema = new SchemaData();
26
- schema.node = node;
27
- schema.name = node.name.text;
28
- const members = [
29
- ...node.members.filter(v => v.kind === 54 /* NodeKind.FieldDeclaration */)
30
- ];
31
- if (node.extendsType) {
32
- schema.parent = this.schemasList.find((v) => v.name == node.extendsType?.name.identifier.text);
33
- if (schema.parent?.members) {
34
- for (let i = schema.parent.members.length - 1; i >= 0; i--) {
35
- const replace = schema.members.find((v) => v.name == schema.parent?.members[i]?.name);
36
- if (!replace) {
37
- //schema.members.unshift(schema.parent?.members[i]!);
38
- members.unshift(schema.parent?.members[i].node);
39
- }
40
- }
41
- }
42
- }
43
- if (!members.length) {
44
- let SERIALIZE_RAW_EMPTY = "__SERIALIZE(): string {\n return \"{}\";\n}";
45
- //let SERIALIZE_PRETTY_EMPTY = "__SERIALIZE_PRETTY(): string {\n return \"{}\";\n}";
46
- let INITIALIZE_EMPTY = "__INITIALIZE(): this {\n return this;\n}";
47
- let DESERIALIZE_EMPTY = "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n return false;\n}";
48
- if (process.env["JSON_DEBUG"]) {
49
- console.log(SERIALIZE_RAW_EMPTY);
50
- //console.log(SERIALIZE_PRETTY_EMPTY);
51
- console.log(INITIALIZE_EMPTY);
52
- console.log(DESERIALIZE_EMPTY);
53
- }
54
- const SERIALIZE_RAW_METHOD_EMPTY = SimpleParser.parseClassMember(SERIALIZE_RAW_EMPTY, node);
55
- //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
56
- const INITIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(INITIALIZE_EMPTY, node);
57
- const DESERIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(DESERIALIZE_EMPTY, node);
58
- if (!node.members.find(v => v.name.text == "__SERIALIZE"))
59
- node.members.push(SERIALIZE_RAW_METHOD_EMPTY);
60
- if (!node.members.find(v => v.name.text == "__INITIALIZE"))
61
- node.members.push(INITIALIZE_METHOD_EMPTY);
62
- if (!node.members.find(v => v.name.text == "__DESERIALIZE"))
63
- node.members.push(DESERIALIZE_METHOD_EMPTY);
64
- this.schemasList.push(schema);
25
+ if (!found) return;
26
+ const schema = new SchemaData();
27
+ schema.node = node;
28
+ schema.name = node.name.text;
29
+ const members = [
30
+ ...node.members.filter(
31
+ (v) => v.kind === 54 /* NodeKind.FieldDeclaration */,
32
+ ),
33
+ ];
34
+ if (node.extendsType) {
35
+ schema.parent = this.schemasList.find(
36
+ (v) => v.name == node.extendsType?.name.identifier.text,
37
+ );
38
+ if (schema.parent?.members) {
39
+ for (let i = schema.parent.members.length - 1; i >= 0; i--) {
40
+ const replace = schema.members.find(
41
+ (v) => v.name == schema.parent?.members[i]?.name,
42
+ );
43
+ if (!replace) {
44
+ members.unshift(schema.parent?.members[i].node);
45
+ }
65
46
  }
66
- for (const member of members) {
67
- const name = member.name;
68
- if (!(member instanceof FieldDeclaration))
69
- continue;
70
- if (!member.type) {
71
- throw new Error("Fields must be strongly typed! Found " + toString(member) + " at " + node.range.source.normalizedPath);
72
- }
73
- const type = toString(member.type);
74
- if (type.startsWith("(") && type.includes("=>"))
75
- continue;
76
- const value = member.initializer ? toString(member.initializer) : null;
77
- if (member.flags == 32 /* CommonFlags.Static */)
78
- continue;
79
- if (member.flags === 512 /* CommonFlags.Private */)
80
- continue;
81
- if (member.flags === 1024 /* CommonFlags.Protected */)
82
- continue;
83
- if (member.decorators && member.decorators.find((v) => v.name.text == "omit"))
84
- continue;
85
- const mem = new Property();
86
- mem.name = name.text;
87
- mem.type = type;
88
- mem.value = value;
89
- mem.node = member;
90
- if (member.decorators) {
91
- let decorator = null;
92
- if (decorator = member.decorators.find(v => v.name.text == "alias")) {
93
- if (decorator.name.text == "alias") {
94
- if (!decorator.args?.length)
95
- throw new Error("Expected 1 argument but got zero at @alias in " + node.range.source.normalizedPath);
96
- mem.flags.push(PropertyFlags.Alias);
97
- mem.alias = decorator.args[0].value;
98
- }
99
- }
100
- for (let i = 0; i < (member.decorators).length; i++) {
101
- const decorator = member.decorators[i];
102
- if (decorator.name.text == "omitnull") {
103
- mem.flags.push(PropertyFlags.OmitNull);
104
- }
105
- else if (decorator.name.text == "omitif") {
106
- if (!decorator.args?.length)
107
- throw new Error("Expected 1 argument but got zero at @omitif in " + node.range.source.normalizedPath);
108
- mem.args?.push(decorator.args[0].value);
109
- mem.flags.push(PropertyFlags.OmitIf);
110
- }
111
- else if (decorator.name.text == "flatten") {
112
- if (!decorator.args?.length)
113
- throw new Error("Expected 1 argument but got zero at @flatten in " + node.range.source.normalizedPath);
114
- mem.flags.push(PropertyFlags.Flatten);
115
- mem.args = [decorator.args[0].value];
116
- }
117
- }
118
- }
119
- if (!mem.flags.length) {
120
- mem.flags = [PropertyFlags.None];
121
- if (type == "JSON.Raw") {
122
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${this." + name.text + "}";
123
- mem.deserialize = "this." + name.text + " = " + "data.substring(value_start, value_end);";
124
- }
125
- else {
126
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${__SERIALIZE<" + type + ">(this." + name.text + ")}";
127
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
128
- }
129
- }
130
- if (mem.flags.includes(PropertyFlags.OmitNull)) {
131
- mem.serialize = "${changetype<usize>(this." + mem.name + ") == <usize>0" + " ? \"\" : '" + escapeString(JSON.stringify(mem.alias || mem.name)) + ":' + __SERIALIZE<" + type + ">(this." + name.text + ") + \",\"}";
132
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
133
- }
134
- else if (mem.flags.includes(PropertyFlags.OmitIf)) {
135
- mem.serialize = "${" + mem.args[0] + " ? \"\" : '" + escapeString(JSON.stringify(mem.alias || mem.name)) + ":' + __SERIALIZE<" + type + ">(this." + name.text + ") + \",\"}";
136
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
137
- }
138
- else if (mem.flags.includes(PropertyFlags.Alias)) {
139
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${__SERIALIZE<" + type + ">(this." + name.text + ")}";
140
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
141
- mem.name = name.text;
142
- }
143
- else if (mem.flags.includes(PropertyFlags.Flatten)) {
144
- const nullable = mem.node.type.isNullable;
145
- if (nullable) {
146
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${this." + name.text + " ? __SERIALIZE(changetype<nonnull<" + type + ">>(this." + name.text + ")" + (mem.args?.length ? '.' + mem.args.join(".") : '') + ") : \"null\"}";
147
- mem.deserialize = "if (value_end - value_start == 4 && load<u64>(changetype<usize>(data) + <usize>(value_start << 1)) == " + charCodeAt64("null", 0) + ") {\n this." + name.text + " = null;\n } else {\n this." + name.text + " = " + "__DESERIALIZE<" + type + ">('{\"" + mem.args[0] + "\":' + data.substring(value_start, value_end) + \"}\");\n }";
148
- }
149
- else {
150
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${this." + name.text + " ? __SERIALIZE(this." + name.text + (mem.args?.length ? '.' + mem.args.join(".") : '') + ") : \"null\"}";
151
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">('{\"" + mem.args[0] + "\":' + data.substring(value_start, value_end) + \"}\");";
152
- }
153
- mem.name = name.text;
154
- }
155
- const t = mem.node.type.name?.identifier.text;
156
- if (this.schemasList.find(v => v.name == t)) {
157
- mem.initialize = "this." + name.text + " = changetype<nonnull<" + mem.type + ">>(__new(offsetof<nonnull<" + mem.type + ">>(), idof<nonnull<" + mem.type + ">>()));\n changetype<nonnull<" + mem.type + ">>(this." + name.text + ").__INITIALIZE()";
158
- }
159
- else if (mem.value) {
160
- mem.initialize = "this." + name.text + " = " + mem.value;
161
- }
162
- else if (t === "Map") {
163
- mem.initialize = "this." + name.text + " = new " + mem.type + "()";
164
- }
165
- else if (t === "string") {
166
- mem.initialize = "this." + name.text + " = \"\"";
167
- }
168
- else if (t === "Array") {
169
- mem.initialize = "this." + name.text + " = instantiate<" + mem.type + ">()";
170
- }
171
- else if (t === "bool" || t === "boolean") {
172
- mem.initialize = "this." + name.text + " = false";
173
- }
174
- else if (t === "JSON.Raw") {
175
- mem.initialize = "this." + name.text + " = \"\"";
176
- }
177
- else if (t === "u8" ||
178
- t === "u16" ||
179
- t === "u32" ||
180
- t === "u64" ||
181
- t === "i8" ||
182
- t === "i16" ||
183
- t === "i32" ||
184
- t === "i64") {
185
- mem.initialize = "this." + name.text + " = 0";
186
- }
187
- else if (t === "f32" ||
188
- t === "f64") {
189
- mem.initialize = "this." + name.text + " = 0.0";
190
- }
191
- schema.members.push(mem);
192
- }
193
- let SERIALIZE_RAW = "__SERIALIZE(): string {\n let out = `{";
194
- let SERIALIZE_PRETTY = "__SERIALIZE_PRETTY(): string {\n let out = `{";
195
- let INITIALIZE = "__INITIALIZE(): this {\n";
196
- let DESERIALIZE = "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n const len = key_end - key_start;\n";
197
- let indent = " ";
198
- if (!schema.members.length)
199
- return;
200
- found = false;
201
- if (schema.members[0]?.flags.includes(PropertyFlags.OmitNull)
202
- || schema.members[0]?.flags.includes(PropertyFlags.OmitIf)) {
203
- SERIALIZE_RAW += schema.members[0]?.serialize;
204
- SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize;
205
- }
206
- else {
207
- SERIALIZE_RAW += schema.members[0]?.serialize + ",";
208
- SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize + ",\\n";
209
- found = true;
210
- }
211
- if (schema.members[0]?.initialize)
212
- INITIALIZE += " " + schema.members[0]?.initialize + ";\n";
213
- for (let i = 1; i < schema.members.length; i++) {
214
- const member = schema.members[i];
215
- if (member.initialize)
216
- INITIALIZE += " " + member.initialize + ";\n";
217
- if (member.flags.includes(PropertyFlags.OmitNull)
218
- || member.flags.includes(PropertyFlags.OmitIf)) {
219
- SERIALIZE_RAW += member.serialize;
220
- SERIALIZE_PRETTY += member.serialize;
221
- }
222
- else {
223
- SERIALIZE_RAW += member.serialize + ",";
224
- SERIALIZE_PRETTY += indent + member.serialize + ",\\n";
225
- found = true;
226
- }
47
+ }
48
+ }
49
+ if (!members.length) {
50
+ let SERIALIZE_RAW_EMPTY = '__SERIALIZE(): string {\n return "{}";\n}';
51
+ //let SERIALIZE_PRETTY_EMPTY = "__SERIALIZE_PRETTY(): string {\n return \"{}\";\n}";
52
+ let INITIALIZE_EMPTY = "__INITIALIZE(): this {\n return this;\n}";
53
+ let DESERIALIZE_EMPTY =
54
+ "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n return false;\n}";
55
+ if (process.env["JSON_DEBUG"]) {
56
+ console.log(SERIALIZE_RAW_EMPTY);
57
+ //console.log(SERIALIZE_PRETTY_EMPTY);
58
+ console.log(INITIALIZE_EMPTY);
59
+ console.log(DESERIALIZE_EMPTY);
60
+ }
61
+ const SERIALIZE_RAW_METHOD_EMPTY = SimpleParser.parseClassMember(
62
+ SERIALIZE_RAW_EMPTY,
63
+ node,
64
+ );
65
+ //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
66
+ const INITIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(
67
+ INITIALIZE_EMPTY,
68
+ node,
69
+ );
70
+ const DESERIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(
71
+ DESERIALIZE_EMPTY,
72
+ node,
73
+ );
74
+ if (!node.members.find((v) => v.name.text == "__SERIALIZE"))
75
+ node.members.push(SERIALIZE_RAW_METHOD_EMPTY);
76
+ if (!node.members.find((v) => v.name.text == "__INITIALIZE"))
77
+ node.members.push(INITIALIZE_METHOD_EMPTY);
78
+ if (!node.members.find((v) => v.name.text == "__DESERIALIZE"))
79
+ node.members.push(DESERIALIZE_METHOD_EMPTY);
80
+ this.schemasList.push(schema);
81
+ }
82
+ for (const member of members) {
83
+ const name = member.name;
84
+ if (!(member instanceof FieldDeclaration)) continue;
85
+ if (!member.type) {
86
+ throw new Error(
87
+ "Fields must be strongly typed! Found " +
88
+ toString(member) +
89
+ " at " +
90
+ node.range.source.normalizedPath,
91
+ );
92
+ }
93
+ const type = toString(member.type);
94
+ if (type.startsWith("(") && type.includes("=>")) continue;
95
+ const value = member.initializer ? toString(member.initializer) : null;
96
+ if (member.flags == 32 /* CommonFlags.Static */) continue;
97
+ if (member.flags === 512 /* CommonFlags.Private */) continue;
98
+ if (member.flags === 1024 /* CommonFlags.Protected */) continue;
99
+ const mem = new Property();
100
+ mem.name = name.text;
101
+ mem.type = type;
102
+ mem.value = value;
103
+ mem.node = member;
104
+ if (type == "JSON.Raw") {
105
+ mem.flags.set(PropertyFlags.JSON_Raw, []);
106
+ }
107
+ if (member.decorators) {
108
+ for (const decorator of member.decorators) {
109
+ const decoratorName = decorator.name.text;
110
+ const args = getArgs(decorator.args);
111
+ switch (decoratorName) {
112
+ case "alias": {
113
+ if (!args.length)
114
+ throw new Error(
115
+ "Expected 1 argument but got zero at @alias in " +
116
+ node.range.source.normalizedPath,
117
+ );
118
+ mem.alias = args[0];
119
+ mem.flags.set(PropertyFlags.Alias, args);
120
+ break;
121
+ }
122
+ case "omit": {
123
+ mem.flags.set(PropertyFlags.Omit, args);
124
+ break;
125
+ }
126
+ case "omitif": {
127
+ if (!decorator.args?.length)
128
+ throw new Error(
129
+ "Expected 1 argument but got zero at @omitif in " +
130
+ node.range.source.normalizedPath,
131
+ );
132
+ mem.flags.set(PropertyFlags.OmitIf, args);
133
+ break;
134
+ }
135
+ case "omitnull": {
136
+ mem.flags.set(PropertyFlags.OmitNull, args);
137
+ break;
138
+ }
139
+ }
227
140
  }
228
- if (found) {
229
- SERIALIZE_RAW += "`;\n store<u16>(changetype<usize>(out) + ((out.length - 1) << 1), 125);\n return out;\n}";
230
- SERIALIZE_PRETTY += "`;\n store<u32>(changetype<usize>(out) + ((out.length - 2) << 1), 8192010);\n return out;\n}";
141
+ }
142
+ mem.generate();
143
+ if (this.schemasList.find((v) => v.name == type)) {
144
+ mem.initialize =
145
+ "this." +
146
+ name.text +
147
+ " = changetype<nonnull<" +
148
+ mem.type +
149
+ ">>(__new(offsetof<nonnull<" +
150
+ mem.type +
151
+ ">>(), idof<nonnull<" +
152
+ mem.type +
153
+ ">>()));\n changetype<nonnull<" +
154
+ mem.type +
155
+ ">>(this." +
156
+ name.text +
157
+ ").__INITIALIZE()";
158
+ } else if (mem.value) {
159
+ mem.initialize = "this." + name.text + " = " + mem.value;
160
+ } else if (type === "Map") {
161
+ mem.initialize = "this." + name.text + " = new " + mem.type + "()";
162
+ } else if (type === "string") {
163
+ mem.initialize = "this." + name.text + ' = ""';
164
+ } else if (type === "Array") {
165
+ mem.initialize =
166
+ "this." + name.text + " = instantiate<" + mem.type + ">()";
167
+ } else if (type === "bool" || type === "boolean") {
168
+ mem.initialize = "this." + name.text + " = false";
169
+ } else if (type === "JSON.Raw") {
170
+ mem.initialize = "this." + name.text + ' = ""';
171
+ } else if (
172
+ type === "u8" ||
173
+ type === "u16" ||
174
+ type === "u32" ||
175
+ type === "u64" ||
176
+ type === "i8" ||
177
+ type === "i16" ||
178
+ type === "i32" ||
179
+ type === "i64"
180
+ ) {
181
+ mem.initialize = "this." + name.text + " = 0";
182
+ } else if (type === "f32" || type === "f64") {
183
+ mem.initialize = "this." + name.text + " = 0.0";
184
+ }
185
+ schema.members.push(mem);
186
+ }
187
+ let SERIALIZE_RAW = "__SERIALIZE(): string {\n let out = `{";
188
+ let SERIALIZE_PRETTY = "__SERIALIZE_PRETTY(): string {\n let out = `{";
189
+ let INITIALIZE = "__INITIALIZE(): this {\n";
190
+ let DESERIALIZE =
191
+ "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n const len = key_end - key_start;\n";
192
+ let indent = " ";
193
+ if (!schema.members.length) return;
194
+ found = false;
195
+ if (
196
+ schema.members[0]?.flags.has(PropertyFlags.OmitNull) ||
197
+ schema.members[0]?.flags.has(PropertyFlags.OmitIf)
198
+ ) {
199
+ SERIALIZE_RAW += schema.members[0]?.serialize;
200
+ SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize;
201
+ } else {
202
+ SERIALIZE_RAW += schema.members[0]?.serialize + ",";
203
+ SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize + ",\\n";
204
+ found = true;
205
+ }
206
+ if (schema.members[0]?.initialize)
207
+ INITIALIZE += " " + schema.members[0]?.initialize + ";\n";
208
+ for (let i = 1; i < schema.members.length; i++) {
209
+ const member = schema.members[i];
210
+ if (member.initialize) INITIALIZE += " " + member.initialize + ";\n";
211
+ if (
212
+ member.flags.has(PropertyFlags.OmitNull) ||
213
+ member.flags.has(PropertyFlags.OmitIf)
214
+ ) {
215
+ SERIALIZE_RAW += member.serialize;
216
+ SERIALIZE_PRETTY += member.serialize;
217
+ } else {
218
+ SERIALIZE_RAW += member.serialize + ",";
219
+ SERIALIZE_PRETTY += indent + member.serialize + ",\\n";
220
+ found = true;
221
+ }
222
+ }
223
+ if (found) {
224
+ SERIALIZE_RAW +=
225
+ "`;\n store<u16>(changetype<usize>(out) + ((out.length - 1) << 1), 125);\n return out;\n}";
226
+ SERIALIZE_PRETTY +=
227
+ "`;\n store<u32>(changetype<usize>(out) + ((out.length - 2) << 1), 8192010);\n return out;\n}";
228
+ } else {
229
+ SERIALIZE_RAW += "`;\n};";
230
+ SERIALIZE_PRETTY += "`;\n};";
231
+ }
232
+ INITIALIZE += " return this;\n}";
233
+ const sortedMembers = [];
234
+ const _sorted = schema.members.sort(
235
+ (a, b) => a.name.length - b.name.length,
236
+ );
237
+ let len = 0;
238
+ let offset = 0;
239
+ sortedMembers.push([_sorted[0]]);
240
+ len = _sorted[0]?.name.length;
241
+ for (let i = 1; i < _sorted.length; i++) {
242
+ const member = _sorted[i];
243
+ if (member.alias?.length || member.name.length > len) {
244
+ sortedMembers.push([member]);
245
+ len = member.alias?.length || member.name.length;
246
+ offset++;
247
+ } else {
248
+ sortedMembers[offset].push(member);
249
+ }
250
+ }
251
+ let first = true;
252
+ for (const memberSet of sortedMembers) {
253
+ const firstMember = memberSet[0];
254
+ const name = encodeKey(firstMember.alias || firstMember.name);
255
+ if (name.length === 1) {
256
+ if (first) {
257
+ DESERIALIZE +=
258
+ " if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
259
+ first = false;
260
+ } else {
261
+ DESERIALIZE +=
262
+ "else if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
231
263
  }
232
- else {
233
- SERIALIZE_RAW += "`;\n};";
234
- SERIALIZE_PRETTY += "`;\n};";
264
+ } else if (name.length === 2) {
265
+ if (first) {
266
+ DESERIALIZE +=
267
+ " if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
268
+ first = false;
269
+ } else {
270
+ DESERIALIZE +=
271
+ "else if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
235
272
  }
236
- INITIALIZE += " return this;\n}";
237
- const sortedMembers = [];
238
- const _sorted = schema.members.sort((a, b) => a.name.length - b.name.length);
239
- let len = 0;
240
- let offset = 0;
241
- sortedMembers.push([_sorted[0]]);
242
- len = _sorted[0]?.name.length;
243
- for (let i = 1; i < _sorted.length; i++) {
244
- const member = _sorted[i];
245
- if (member.alias?.length || member.name.length > len) {
246
- sortedMembers.push([member]);
247
- len = member.alias?.length || member.name.length;
248
- offset++;
249
- }
250
- else {
251
- sortedMembers[offset].push(member);
252
- }
273
+ } else if (name.length === 4) {
274
+ if (first) {
275
+ DESERIALIZE +=
276
+ " if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
277
+ first = false;
278
+ } else {
279
+ DESERIALIZE +=
280
+ "else if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
253
281
  }
254
- let first = true;
255
- for (const memberSet of sortedMembers) {
256
- const firstMember = memberSet[0];
257
- const name = encodeKey(firstMember.alias || firstMember.name);
258
- if (name.length === 1) {
259
- if (first) {
260
- DESERIALIZE += " if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
261
- first = false;
262
- }
263
- else {
264
- DESERIALIZE += "else if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
265
- }
266
- }
267
- else if (name.length === 2) {
268
- if (first) {
269
- DESERIALIZE += " if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
270
- first = false;
271
- }
272
- else {
273
- DESERIALIZE += "else if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
274
- }
275
- }
276
- else if (name.length === 4) {
277
- if (first) {
278
- DESERIALIZE += " if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
279
- first = false;
280
- }
281
- else {
282
- DESERIALIZE += "else if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
283
- }
284
- }
285
- else {
286
- if (first) {
287
- DESERIALIZE += " if (" + name.length + " === len) {\n";
288
- first = false;
289
- }
290
- else {
291
- DESERIALIZE += "else if (" + name.length + " === len) {\n";
292
- }
293
- }
294
- let f = true;
295
- for (let i = 0; i < memberSet.length; i++) {
296
- const member = memberSet[i];
297
- if (!member.deserialize)
298
- continue;
299
- const name = encodeKey(member.alias || member.name);
300
- if (name.length === 1) {
301
- DESERIALIZE += ` case ${name.charCodeAt(0)}: {\n ${member.deserialize}\n return true;\n }\n`;
302
- }
303
- else if (name.length === 2) {
304
- DESERIALIZE += ` case ${charCodeAt32(name, 0)}: {\n ${member.deserialize}\n return true;\n }\n`;
305
- }
306
- else if (name.length === 4) {
307
- if (f) {
308
- f = false;
309
- DESERIALIZE += ` if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
310
- }
311
- else {
312
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + `else if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
313
- }
314
- }
315
- else {
316
- if (f) {
317
- f = false;
318
- DESERIALIZE += ` if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
319
- }
320
- else {
321
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + ` else if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
322
- }
323
- }
324
- }
325
- if (name.length < 3) {
326
- DESERIALIZE += ` default: {\n return false;\n }\n }\n`;
327
- }
328
- else if (name.length == 4) {
329
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + ` else {\n return false;\n }\n`;
330
- }
331
- else {
332
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + ` else {\n return false;\n }\n`;
333
- }
334
- DESERIALIZE += " } ";
282
+ } else {
283
+ if (first) {
284
+ DESERIALIZE += " if (" + name.length + " === len) {\n";
285
+ first = false;
286
+ } else {
287
+ DESERIALIZE += "else if (" + name.length + " === len) {\n";
335
288
  }
336
- DESERIALIZE += "\n return false;\n}";
337
- //console.log(sortedMembers);
338
- if (process.env["JSON_DEBUG"]) {
339
- console.log(SERIALIZE_RAW);
340
- //console.log(SERIALIZE_PRETTY);
341
- console.log(INITIALIZE);
342
- console.log(DESERIALIZE);
289
+ }
290
+ let f = true;
291
+ for (let i = 0; i < memberSet.length; i++) {
292
+ const member = memberSet[i];
293
+ if (!member.deserialize) continue;
294
+ const name = encodeKey(member.alias || member.name);
295
+ if (name.length === 1) {
296
+ DESERIALIZE += ` case ${name.charCodeAt(0)}: {\n ${member.deserialize}\n return true;\n }\n`;
297
+ } else if (name.length === 2) {
298
+ DESERIALIZE += ` case ${charCodeAt32(name, 0)}: {\n ${member.deserialize}\n return true;\n }\n`;
299
+ } else if (name.length === 4) {
300
+ if (f) {
301
+ f = false;
302
+ DESERIALIZE += ` if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
303
+ } else {
304
+ DESERIALIZE =
305
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
306
+ `else if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
307
+ }
308
+ } else {
309
+ if (f) {
310
+ f = false;
311
+ DESERIALIZE += ` if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
312
+ } else {
313
+ DESERIALIZE =
314
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
315
+ ` else if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
316
+ }
343
317
  }
344
- const SERIALIZE_RAW_METHOD = SimpleParser.parseClassMember(SERIALIZE_RAW, node);
345
- //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
346
- const INITIALIZE_METHOD = SimpleParser.parseClassMember(INITIALIZE, node);
347
- const DESERIALIZE_METHOD = SimpleParser.parseClassMember(DESERIALIZE, node);
348
- if (!node.members.find(v => v.name.text == "__SERIALIZE"))
349
- node.members.push(SERIALIZE_RAW_METHOD);
350
- if (!node.members.find(v => v.name.text == "__INITIALIZE"))
351
- node.members.push(INITIALIZE_METHOD);
352
- if (!node.members.find(v => v.name.text == "__DESERIALIZE"))
353
- node.members.push(DESERIALIZE_METHOD);
354
- this.schemasList.push(schema);
318
+ }
319
+ if (name.length < 3) {
320
+ DESERIALIZE += ` default: {\n return false;\n }\n }\n`;
321
+ } else if (name.length == 4) {
322
+ DESERIALIZE =
323
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
324
+ ` else {\n return false;\n }\n`;
325
+ } else {
326
+ DESERIALIZE =
327
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
328
+ ` else {\n return false;\n }\n`;
329
+ }
330
+ DESERIALIZE += " } ";
355
331
  }
356
- visitSource(node) {
357
- super.visitSource(node);
358
- // Only add the import statement to sources that have JSON decorated classes.
359
- if (!this.sources.has(node)) {
360
- return;
361
- }
332
+ DESERIALIZE += "\n return false;\n}";
333
+ //console.log(sortedMembers);
334
+ if (process.env["JSON_DEBUG"]) {
335
+ console.log(SERIALIZE_RAW);
336
+ //console.log(SERIALIZE_PRETTY);
337
+ console.log(INITIALIZE);
338
+ console.log(DESERIALIZE);
339
+ }
340
+ const SERIALIZE_RAW_METHOD = SimpleParser.parseClassMember(
341
+ SERIALIZE_RAW,
342
+ node,
343
+ );
344
+ //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
345
+ const INITIALIZE_METHOD = SimpleParser.parseClassMember(INITIALIZE, node);
346
+ const DESERIALIZE_METHOD = SimpleParser.parseClassMember(DESERIALIZE, node);
347
+ if (!node.members.find((v) => v.name.text == "__SERIALIZE"))
348
+ node.members.push(SERIALIZE_RAW_METHOD);
349
+ if (!node.members.find((v) => v.name.text == "__INITIALIZE"))
350
+ node.members.push(INITIALIZE_METHOD);
351
+ if (!node.members.find((v) => v.name.text == "__DESERIALIZE"))
352
+ node.members.push(DESERIALIZE_METHOD);
353
+ this.schemasList.push(schema);
354
+ }
355
+ visitSource(node) {
356
+ super.visitSource(node);
357
+ // Only add the import statement to sources that have JSON decorated classes.
358
+ if (!this.sources.has(node)) {
359
+ return;
362
360
  }
361
+ }
363
362
  }
364
363
  export default class Transformer extends Transform {
365
- // Trigger the transform after parse.
366
- afterParse(parser) {
367
- // Create new transform
368
- const transformer = new JSONTransform();
369
- // Sort the sources so that user scripts are visited last
370
- const sources = parser.sources
371
- .filter((source) => !isStdlib(source))
372
- .sort((_a, _b) => {
373
- const a = _a.internalPath;
374
- const b = _b.internalPath;
375
- if (a[0] === "~" && b[0] !== "~") {
376
- return -1;
377
- }
378
- else if (a[0] !== "~" && b[0] === "~") {
379
- return 1;
380
- }
381
- else {
382
- return 0;
383
- }
384
- });
385
- // Loop over every source
386
- for (const source of sources) {
387
- // Ignore all lib and std. Visit everything else.
388
- if (!isStdlib(source)) {
389
- transformer.visit(source);
390
- }
391
- }
392
- // Check that every parent and child class is hooked up correctly
393
- const schemas = transformer.schemasList;
394
- for (const schema of schemas) {
395
- if (schema.parent) {
396
- const parent = schemas.find((v) => v.name === schema.parent?.name);
397
- if (!parent)
398
- throw new Error(`Class ${schema.name} extends its parent class ${schema.parent}, but ${schema.parent} does not include a @json or @serializable decorator! Add the decorator and rebuild.`);
399
- }
364
+ // Trigger the transform after parse.
365
+ afterParse(parser) {
366
+ // Create new transform
367
+ const transformer = new JSONTransform();
368
+ // Sort the sources so that user scripts are visited last
369
+ const sources = parser.sources
370
+ .filter((source) => !isStdlib(source))
371
+ .sort((_a, _b) => {
372
+ const a = _a.internalPath;
373
+ const b = _b.internalPath;
374
+ if (a[0] === "~" && b[0] !== "~") {
375
+ return -1;
376
+ } else if (a[0] !== "~" && b[0] === "~") {
377
+ return 1;
378
+ } else {
379
+ return 0;
400
380
  }
381
+ });
382
+ // Loop over every source
383
+ for (const source of sources) {
384
+ // Ignore all lib and std. Visit everything else.
385
+ if (!isStdlib(source)) {
386
+ transformer.visit(source);
387
+ }
388
+ }
389
+ // Check that every parent and child class is hooked up correctly
390
+ const schemas = transformer.schemasList;
391
+ for (const schema of schemas) {
392
+ if (schema.parent) {
393
+ const parent = schemas.find((v) => v.name === schema.parent?.name);
394
+ if (!parent)
395
+ throw new Error(
396
+ `Class ${schema.name} extends its parent class ${schema.parent}, but ${schema.parent} does not include a @json or @serializable decorator! Add the decorator and rebuild.`,
397
+ );
398
+ }
401
399
  }
400
+ }
402
401
  }
403
402
  var PropertyFlags;
404
403
  (function (PropertyFlags) {
405
- PropertyFlags[PropertyFlags["None"] = 0] = "None";
406
- PropertyFlags[PropertyFlags["Omit"] = 1] = "Omit";
407
- PropertyFlags[PropertyFlags["OmitNull"] = 2] = "OmitNull";
408
- PropertyFlags[PropertyFlags["OmitIf"] = 3] = "OmitIf";
409
- PropertyFlags[PropertyFlags["Alias"] = 4] = "Alias";
410
- PropertyFlags[PropertyFlags["Flatten"] = 5] = "Flatten";
404
+ PropertyFlags[(PropertyFlags["Omit"] = 0)] = "Omit";
405
+ PropertyFlags[(PropertyFlags["OmitNull"] = 1)] = "OmitNull";
406
+ PropertyFlags[(PropertyFlags["OmitIf"] = 2)] = "OmitIf";
407
+ PropertyFlags[(PropertyFlags["Alias"] = 3)] = "Alias";
408
+ PropertyFlags[(PropertyFlags["JSON_Raw"] = 4)] = "JSON_Raw";
411
409
  })(PropertyFlags || (PropertyFlags = {}));
412
410
  class Property {
413
- constructor() {
414
- this.name = "";
415
- this.alias = null;
416
- this.type = "";
417
- this.value = null;
418
- this.flags = [];
419
- this.args = [];
420
- this.serialize = null;
421
- this.deserialize = null;
422
- this.initialize = null;
411
+ constructor() {
412
+ this.name = "";
413
+ this.alias = null;
414
+ this.type = "";
415
+ this.value = null;
416
+ this.flags = new Map();
417
+ this.args = [];
418
+ this.serialize = null;
419
+ this.deserialize = null;
420
+ this.initialize = null;
421
+ this.right_s = "";
422
+ this.right_d = "";
423
+ }
424
+ generate() {
425
+ const name = this.name;
426
+ const escapedName = escapeString(JSON.stringify(this.alias || this.name));
427
+ const type = this.type;
428
+ if (this.flags.has(PropertyFlags.Omit)) return;
429
+ if (this.flags.has(PropertyFlags.JSON_Raw)) {
430
+ this.right_s = "this." + name;
431
+ this.right_d = "data.substring(value_start, value_end);";
432
+ } else {
433
+ this.right_s = "__SERIALIZE<" + type + ">(this." + name + ")";
434
+ this.right_d =
435
+ "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end))";
423
436
  }
437
+ if (this.flags.has(PropertyFlags.OmitIf)) {
438
+ const condition = this.args[0];
439
+ this.serialize =
440
+ "${" +
441
+ condition +
442
+ ' ? "" : \'' +
443
+ escapedName +
444
+ ":' + " +
445
+ this.right_s +
446
+ ' + ","}';
447
+ this.deserialize = "this." + name + " = " + this.right_d + ";";
448
+ } else if (this.flags.has(PropertyFlags.OmitNull)) {
449
+ this.serialize =
450
+ "${changetype<usize>(this." +
451
+ name +
452
+ ") == <usize>0" +
453
+ ' ? "" : \'' +
454
+ escapedName +
455
+ ":' + " +
456
+ this.right_s +
457
+ ' + ","}';
458
+ this.deserialize = "this." + name + " = " + this.right_d + ";";
459
+ } else {
460
+ this.serialize = escapedName + ":${" + this.right_s + "}";
461
+ this.deserialize = "this." + name + " = " + this.right_d + ";";
462
+ }
463
+ }
424
464
  }
425
465
  class SchemaData {
426
- constructor() {
427
- this.name = "";
428
- this.members = [];
429
- this.parent = null;
430
- }
466
+ constructor() {
467
+ this.name = "";
468
+ this.members = [];
469
+ this.parent = null;
470
+ }
431
471
  }
432
472
  function charCodeAt32(data, offset) {
433
- return (data.charCodeAt(offset + 1) << 16) | data.charCodeAt(offset);
473
+ return (data.charCodeAt(offset + 1) << 16) | data.charCodeAt(offset);
434
474
  }
435
475
  function charCodeAt64(data, offset) {
436
- if (offset + 3 >= data.length) {
437
- throw new Error("The string must have at least 4 characters from the specified offset.");
438
- }
439
- const firstCharCode = BigInt(data.charCodeAt(offset));
440
- const secondCharCode = BigInt(data.charCodeAt(offset + 1));
441
- const thirdCharCode = BigInt(data.charCodeAt(offset + 2));
442
- const fourthCharCode = BigInt(data.charCodeAt(offset + 3));
443
- const u64Value = (fourthCharCode << 48n) | (thirdCharCode << 32n) | (secondCharCode << 16n) | firstCharCode;
444
- return u64Value;
476
+ if (offset + 3 >= data.length) {
477
+ throw new Error(
478
+ "The string must have at least 4 characters from the specified offset.",
479
+ );
480
+ }
481
+ const firstCharCode = BigInt(data.charCodeAt(offset));
482
+ const secondCharCode = BigInt(data.charCodeAt(offset + 1));
483
+ const thirdCharCode = BigInt(data.charCodeAt(offset + 2));
484
+ const fourthCharCode = BigInt(data.charCodeAt(offset + 3));
485
+ const u64Value =
486
+ (fourthCharCode << 48n) |
487
+ (thirdCharCode << 32n) |
488
+ (secondCharCode << 16n) |
489
+ firstCharCode;
490
+ return u64Value;
445
491
  }
446
492
  function encodeKey(key) {
447
- const data = JSON.stringify(key);
448
- return data.slice(1, data.length - 1);
493
+ const data = JSON.stringify(key);
494
+ return data.slice(1, data.length - 1);
449
495
  }
450
496
  function escapeString(data) {
451
- return data.replace(/\\/g, "\\\\")
452
- .replace(/\`/g, '\\`');
497
+ return data.replace(/\\/g, "\\\\").replace(/\`/g, "\\`");
453
498
  }
454
499
  function escapeSlash(data) {
455
- return data.replace(/\\/g, "\\\\")
456
- .replace(/\`/g, '\\`');
500
+ return data.replace(/\\/g, "\\\\").replace(/\`/g, "\\`");
457
501
  }
458
502
  function escapeQuote(data) {
459
- return data.replace(/\"/g, "\\\"");
503
+ return data.replace(/\"/g, '\\"');
504
+ }
505
+ function getArgs(args) {
506
+ if (!args) return [];
507
+ let out = [];
508
+ for (const arg of args) {
509
+ if (arg instanceof StringLiteralExpression) {
510
+ out.push(arg.value);
511
+ }
512
+ }
513
+ return out;
460
514
  }