metano-runtime 2.9.0 → 2.10.1
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/system/json/container-depth.d.ts +20 -0
- package/dist/system/json/container-depth.js +57 -0
- package/dist/system/json/contract-name.d.ts +10 -0
- package/dist/system/json/contract-name.js +13 -0
- package/dist/system/json/converters.d.ts +18 -3
- package/dist/system/json/converters.js +148 -56
- package/dist/system/json/errors.d.ts +20 -0
- package/dist/system/json/errors.js +20 -0
- package/dist/system/json/index.d.ts +3 -2
- package/dist/system/json/index.js +2 -1
- package/dist/system/json/polymorphism.d.ts +24 -0
- package/dist/system/json/polymorphism.js +349 -0
- package/dist/system/json/types.d.ts +57 -1
- package/package.json +1 -1
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** The JSON container a read enters, named as STJ's reader names it. */
|
|
2
|
+
export type JsonContainer = "object" | "array";
|
|
3
|
+
/**
|
|
4
|
+
* Runs `write` inside one more JSON container; the 65th nested container
|
|
5
|
+
* throws `JsonException` instead of overflowing the stack on a cycle.
|
|
6
|
+
*
|
|
7
|
+
* This is a hybrid of System.Text.Json's two write modes (measured on .NET
|
|
8
|
+
* 10, DECIDED-20 b): the boundary is the source-generated fast path's, where
|
|
9
|
+
* only containers count (64 nested objects are written, the 65th throws
|
|
10
|
+
* `InvalidOperationException`), while the exception and message are the
|
|
11
|
+
* metadata / reflection mode's, which also throws when a non-null scalar is
|
|
12
|
+
* written inside the 64th container.
|
|
13
|
+
*/
|
|
14
|
+
export declare function writeContainer<T>(write: () => T): T;
|
|
15
|
+
/**
|
|
16
|
+
* Runs `read` inside one more JSON container of the parsed value. The 65th
|
|
17
|
+
* nested container throws STJ's reader message (measured on .NET 10: 64
|
|
18
|
+
* nested containers are read, the 65th throws).
|
|
19
|
+
*/
|
|
20
|
+
export declare function readContainer<T>(container: JsonContainer, read: () => T): T;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { JsonException } from "./errors.js";
|
|
2
|
+
/** System.Text.Json's default `JsonSerializerOptions.MaxDepth`. */
|
|
3
|
+
const MAX_JSON_DEPTH = 64;
|
|
4
|
+
/** The STJ metadata-mode message for a write deeper than the maximum depth (FR-016). */
|
|
5
|
+
const WRITE_DEPTH_MESSAGE = "A possible object cycle was detected. This can either be due to a cycle or if the object " +
|
|
6
|
+
`depth is larger than the maximum allowed depth of ${MAX_JSON_DEPTH}. Consider using ` +
|
|
7
|
+
"ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.";
|
|
8
|
+
/**
|
|
9
|
+
* The number of JSON containers (objects, arrays, dictionaries) currently
|
|
10
|
+
* open. The counter is process-global: it is safe only because no
|
|
11
|
+
* serialize or deserialize call yields (no `await`, no callback deferred
|
|
12
|
+
* past the call), so one call's containers are always closed before another
|
|
13
|
+
* call starts. A custom converter that calls back into the serializer for a
|
|
14
|
+
* separate root inherits the outer depth, where STJ's
|
|
15
|
+
* `JsonSerializer.Serialize(…)` inside a converter starts a fresh writer at
|
|
16
|
+
* depth 0.
|
|
17
|
+
*/
|
|
18
|
+
const openContainers = { count: 0 };
|
|
19
|
+
/**
|
|
20
|
+
* Runs `write` inside one more JSON container; the 65th nested container
|
|
21
|
+
* throws `JsonException` instead of overflowing the stack on a cycle.
|
|
22
|
+
*
|
|
23
|
+
* This is a hybrid of System.Text.Json's two write modes (measured on .NET
|
|
24
|
+
* 10, DECIDED-20 b): the boundary is the source-generated fast path's, where
|
|
25
|
+
* only containers count (64 nested objects are written, the 65th throws
|
|
26
|
+
* `InvalidOperationException`), while the exception and message are the
|
|
27
|
+
* metadata / reflection mode's, which also throws when a non-null scalar is
|
|
28
|
+
* written inside the 64th container.
|
|
29
|
+
*/
|
|
30
|
+
export function writeContainer(write) {
|
|
31
|
+
return withinContainer(write, () => new JsonException(WRITE_DEPTH_MESSAGE));
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Runs `read` inside one more JSON container of the parsed value. The 65th
|
|
35
|
+
* nested container throws STJ's reader message (measured on .NET 10: 64
|
|
36
|
+
* nested containers are read, the 65th throws).
|
|
37
|
+
*/
|
|
38
|
+
export function readContainer(container, read) {
|
|
39
|
+
return withinContainer(read, () => new JsonException(readDepthMessage(container)));
|
|
40
|
+
}
|
|
41
|
+
/** STJ's reader message for a container past the maximum depth. */
|
|
42
|
+
function readDepthMessage(container) {
|
|
43
|
+
return (`The maximum configured depth of ${MAX_JSON_DEPTH} has been exceeded. ` +
|
|
44
|
+
`Cannot read next JSON ${container}.`);
|
|
45
|
+
}
|
|
46
|
+
function withinContainer(run, depthExceeded) {
|
|
47
|
+
if (openContainers.count >= MAX_JSON_DEPTH) {
|
|
48
|
+
throw depthExceeded();
|
|
49
|
+
}
|
|
50
|
+
openContainers.count++;
|
|
51
|
+
try {
|
|
52
|
+
return run();
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
openContainers.count--;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { TypeSpec } from "./types.ts";
|
|
2
|
+
import { JsonException } from "./errors.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The C# type name a contract reports in errors: its constructor's name, the
|
|
5
|
+
* `typeName` of a polymorphic base without a constructor (an interface or a
|
|
6
|
+
* `[PlainObject]` base), and `Object` for any other `[PlainObject]` contract.
|
|
7
|
+
*/
|
|
8
|
+
export declare function contractNameOf(spec: TypeSpec): string;
|
|
9
|
+
/** System.Text.Json's error for a JSON value that does not fit the contract. */
|
|
10
|
+
export declare function cannotConvertTo(spec: TypeSpec): JsonException;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { JsonException } from "./errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* The C# type name a contract reports in errors: its constructor's name, the
|
|
4
|
+
* `typeName` of a polymorphic base without a constructor (an interface or a
|
|
5
|
+
* `[PlainObject]` base), and `Object` for any other `[PlainObject]` contract.
|
|
6
|
+
*/
|
|
7
|
+
export function contractNameOf(spec) {
|
|
8
|
+
return spec.type?.name ?? spec.polymorphism?.typeName ?? "Object";
|
|
9
|
+
}
|
|
10
|
+
/** System.Text.Json's error for a JSON value that does not fit the contract. */
|
|
11
|
+
export function cannotConvertTo(spec) {
|
|
12
|
+
return new JsonException(`The JSON value could not be converted to ${contractNameOf(spec)}.`);
|
|
13
|
+
}
|
|
@@ -9,14 +9,29 @@ export declare function resolveConverter(descriptor: TypeDescriptor, customConve
|
|
|
9
9
|
};
|
|
10
10
|
/**
|
|
11
11
|
* Collects all properties from a spec chain, walking the base hierarchy.
|
|
12
|
-
* Base properties come first, own properties last
|
|
12
|
+
* Base properties come first, own properties last: the declaration order a
|
|
13
|
+
* factory reads, **not** the wire order (see `collectWireProperties`). An
|
|
14
|
+
* override appears once per spec that declares it.
|
|
13
15
|
*/
|
|
14
16
|
export declare function collectProperties(spec: TypeSpec): readonly PropertySpec[];
|
|
15
17
|
/**
|
|
16
|
-
*
|
|
18
|
+
* The properties a spec writes and reads, in System.Text.Json's wire order
|
|
19
|
+
* (FR-009): the spec's own properties, then its base's, recursively. A JSON
|
|
20
|
+
* name appears once, from its most-derived declaration, and a base
|
|
21
|
+
* declaration whose `ts` name a more-derived spec lists in
|
|
22
|
+
* `ignoredProperties` (a `[JsonIgnore]` override) is left out.
|
|
23
|
+
*/
|
|
24
|
+
export declare function collectWireProperties(spec: TypeSpec): readonly PropertySpec[];
|
|
25
|
+
/**
|
|
26
|
+
* Serialize a TS object to a JSON-safe plain object using the given spec. A
|
|
27
|
+
* polymorphic spec first chooses the derived contract and writes its tag
|
|
28
|
+
* before every property (FR-005); the chosen contract is never dispatched
|
|
29
|
+
* again (FR-006).
|
|
17
30
|
*/
|
|
18
31
|
export declare function serializeWithSpec(value: unknown, spec: TypeSpec, customConverters?: readonly JsonConverter[]): Record<string, unknown>;
|
|
19
32
|
/**
|
|
20
|
-
* Deserialize unknown data (from JSON.parse) into a typed instance using the
|
|
33
|
+
* Deserialize unknown data (from JSON.parse) into a typed instance using the
|
|
34
|
+
* spec. A polymorphic spec reads the derived contract its tag selects
|
|
35
|
+
* (FR-007).
|
|
21
36
|
*/
|
|
22
37
|
export declare function deserializeWithSpec<T>(data: unknown, spec: TypeSpec<T>, customConverters?: readonly JsonConverter[]): T;
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { HashSet } from "../collections/hash-set.js";
|
|
2
|
+
import { readContainer, writeContainer } from "./container-depth.js";
|
|
3
|
+
import { cannotConvertTo } from "./contract-name.js";
|
|
4
|
+
import { JsonException } from "./errors.js";
|
|
5
|
+
import { resolveDeserializeTarget, resolveSerializeTarget } from "./polymorphism.js";
|
|
2
6
|
// ─── Converter Resolution ────────────────────────────────────────────────────
|
|
3
7
|
/**
|
|
4
8
|
* Resolves the serialize/deserialize pair for a given type descriptor, checking
|
|
@@ -90,26 +94,42 @@ function mapConverter(descriptor, customConverters) {
|
|
|
90
94
|
serialize: (value) => {
|
|
91
95
|
if (value == null)
|
|
92
96
|
return null;
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
97
|
+
return writeContainer(() => {
|
|
98
|
+
const map = value;
|
|
99
|
+
const result = {};
|
|
100
|
+
for (const [k, v] of map) {
|
|
101
|
+
const serializedKey = String(keyConv.serialize(k));
|
|
102
|
+
result[serializedKey] = valueConv.serialize(v);
|
|
103
|
+
}
|
|
104
|
+
return result;
|
|
105
|
+
});
|
|
100
106
|
},
|
|
101
107
|
deserialize: (value) => {
|
|
102
108
|
if (value == null)
|
|
103
109
|
return null;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
107
|
-
map.set(keyConv.deserialize(k), valueConv.deserialize(v));
|
|
110
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
111
|
+
throw unexpectedJsonKind("object", value);
|
|
108
112
|
}
|
|
109
|
-
return
|
|
113
|
+
return readContainer("object", () => {
|
|
114
|
+
const map = new Map();
|
|
115
|
+
for (const [k, v] of Object.entries(value)) {
|
|
116
|
+
map.set(keyConv.deserialize(k), valueConv.deserialize(v));
|
|
117
|
+
}
|
|
118
|
+
return map;
|
|
119
|
+
});
|
|
110
120
|
},
|
|
111
121
|
};
|
|
112
122
|
}
|
|
123
|
+
// ─── Collection input ────────────────────────────────────────────────────────
|
|
124
|
+
/**
|
|
125
|
+
* The error for a non-null JSON value of the wrong kind for a collection or
|
|
126
|
+
* dictionary (#425). STJ names the CLR collection type, which a descriptor
|
|
127
|
+
* does not carry.
|
|
128
|
+
*/
|
|
129
|
+
function unexpectedJsonKind(expected, value) {
|
|
130
|
+
const actual = Array.isArray(value) ? "array" : typeof value;
|
|
131
|
+
return new JsonException(`Expected ${expected} for deserialization, got ${actual}`);
|
|
132
|
+
}
|
|
113
133
|
/**
|
|
114
134
|
* Writes any iterable (an array, a `Set`, a generator, a LINQ pipe for
|
|
115
135
|
* `IEnumerable<T>`) as a JSON array, converting each element (FR-038).
|
|
@@ -117,17 +137,25 @@ function mapConverter(descriptor, customConverters) {
|
|
|
117
137
|
function serializeIterable(value, elemConv) {
|
|
118
138
|
if (value == null)
|
|
119
139
|
return null;
|
|
120
|
-
return Array.from(value, (item) => elemConv.serialize(item));
|
|
140
|
+
return writeContainer(() => Array.from(value, (item) => elemConv.serialize(item)));
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Reads a JSON array element by element. Any other JSON value throws
|
|
144
|
+
* `JsonException` (#425); `null` reads as `null`.
|
|
145
|
+
*/
|
|
146
|
+
function deserializeArray(value, elemConv) {
|
|
147
|
+
if (value == null)
|
|
148
|
+
return null;
|
|
149
|
+
if (!Array.isArray(value)) {
|
|
150
|
+
throw unexpectedJsonKind("array", value);
|
|
151
|
+
}
|
|
152
|
+
return readContainer("array", () => value.map((item) => elemConv.deserialize(item)));
|
|
121
153
|
}
|
|
122
154
|
function arrayConverter(descriptor, customConverters) {
|
|
123
155
|
const elemConv = resolveConverter(descriptor.element, customConverters);
|
|
124
156
|
return {
|
|
125
157
|
serialize: (value) => serializeIterable(value, elemConv),
|
|
126
|
-
deserialize: (value) =>
|
|
127
|
-
if (value == null)
|
|
128
|
-
return null;
|
|
129
|
-
return value.map((item) => elemConv.deserialize(item));
|
|
130
|
-
},
|
|
158
|
+
deserialize: (value) => deserializeArray(value, elemConv),
|
|
131
159
|
};
|
|
132
160
|
}
|
|
133
161
|
// ─── HashSet ─────────────────────────────────────────────────────────────────
|
|
@@ -136,10 +164,8 @@ function hashSetConverter(descriptor, customConverters) {
|
|
|
136
164
|
return {
|
|
137
165
|
serialize: (value) => serializeIterable(value, elemConv),
|
|
138
166
|
deserialize: (value) => {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
const items = value.map((item) => elemConv.deserialize(item));
|
|
142
|
-
return new HashSet(items);
|
|
167
|
+
const items = deserializeArray(value, elemConv);
|
|
168
|
+
return items === null ? null : new HashSet(items);
|
|
143
169
|
},
|
|
144
170
|
};
|
|
145
171
|
}
|
|
@@ -157,7 +183,7 @@ function enumConverter(descriptor) {
|
|
|
157
183
|
serialize: (value) => value, // already a string
|
|
158
184
|
deserialize: (value) => {
|
|
159
185
|
if (typeof value !== "string" || !validValues.has(value)) {
|
|
160
|
-
throw new
|
|
186
|
+
throw new JsonException(`Invalid enum value: ${JSON.stringify(value)}. ` +
|
|
161
187
|
`Expected one of: ${[...validValues].join(", ")}`);
|
|
162
188
|
}
|
|
163
189
|
return value;
|
|
@@ -171,7 +197,7 @@ function numericEnumConverter(descriptor) {
|
|
|
171
197
|
serialize: (value) => value, // already a number
|
|
172
198
|
deserialize: (value) => {
|
|
173
199
|
if (typeof value !== "number" || !validValues.has(value)) {
|
|
174
|
-
throw new
|
|
200
|
+
throw new JsonException(`Invalid numeric enum value: ${JSON.stringify(value)}. ` +
|
|
175
201
|
`Expected one of: ${[...validValues].join(", ")}`);
|
|
176
202
|
}
|
|
177
203
|
return value;
|
|
@@ -204,53 +230,119 @@ function refConverter(descriptor, customConverters) {
|
|
|
204
230
|
// ─── Core serialize/deserialize by spec ──────────────────────────────────────
|
|
205
231
|
/**
|
|
206
232
|
* Collects all properties from a spec chain, walking the base hierarchy.
|
|
207
|
-
* Base properties come first, own properties last
|
|
233
|
+
* Base properties come first, own properties last: the declaration order a
|
|
234
|
+
* factory reads, **not** the wire order (see `collectWireProperties`). An
|
|
235
|
+
* override appears once per spec that declares it.
|
|
208
236
|
*/
|
|
209
237
|
export function collectProperties(spec) {
|
|
210
238
|
const base = spec.base ? collectProperties(spec.base) : [];
|
|
211
239
|
return [...base, ...spec.properties];
|
|
212
240
|
}
|
|
213
241
|
/**
|
|
214
|
-
*
|
|
242
|
+
* The properties a spec writes and reads, in System.Text.Json's wire order
|
|
243
|
+
* (FR-009): the spec's own properties, then its base's, recursively. A JSON
|
|
244
|
+
* name appears once, from its most-derived declaration, and a base
|
|
245
|
+
* declaration whose `ts` name a more-derived spec lists in
|
|
246
|
+
* `ignoredProperties` (a `[JsonIgnore]` override) is left out.
|
|
215
247
|
*/
|
|
216
|
-
export function
|
|
217
|
-
const
|
|
218
|
-
const
|
|
219
|
-
const
|
|
220
|
-
for (const
|
|
221
|
-
const
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
248
|
+
export function collectWireProperties(spec) {
|
|
249
|
+
const wire = [];
|
|
250
|
+
const writtenNames = new Set();
|
|
251
|
+
const ignoredNames = new Set();
|
|
252
|
+
for (const contract of specChainOf(spec)) {
|
|
253
|
+
const visible = contract.properties.filter((property) => !ignoredNames.has(property.ts) && !writtenNames.has(property.json));
|
|
254
|
+
for (const property of visible) {
|
|
255
|
+
writtenNames.add(property.json);
|
|
256
|
+
wire.push(property);
|
|
225
257
|
}
|
|
226
|
-
const
|
|
227
|
-
|
|
258
|
+
for (const name of contract.ignoredProperties ?? []) {
|
|
259
|
+
ignoredNames.add(name);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return wire;
|
|
263
|
+
}
|
|
264
|
+
/** The spec and its bases, most-derived first. */
|
|
265
|
+
function* specChainOf(spec) {
|
|
266
|
+
yield spec;
|
|
267
|
+
if (spec.base) {
|
|
268
|
+
yield* specChainOf(spec.base);
|
|
228
269
|
}
|
|
229
|
-
return result;
|
|
230
270
|
}
|
|
231
271
|
/**
|
|
232
|
-
*
|
|
272
|
+
* Serialize a TS object to a JSON-safe plain object using the given spec. A
|
|
273
|
+
* polymorphic spec first chooses the derived contract and writes its tag
|
|
274
|
+
* before every property (FR-005); the chosen contract is never dispatched
|
|
275
|
+
* again (FR-006).
|
|
233
276
|
*/
|
|
234
|
-
export function
|
|
235
|
-
|
|
236
|
-
|
|
277
|
+
export function serializeWithSpec(value, spec, customConverters) {
|
|
278
|
+
const { polymorphism } = spec;
|
|
279
|
+
if (!polymorphism) {
|
|
280
|
+
return serializeContract(value, spec, customConverters);
|
|
237
281
|
}
|
|
238
|
-
const
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
282
|
+
const target = resolveSerializeTarget(value, spec, polymorphism);
|
|
283
|
+
const typeMetadata = target.tag === undefined ? undefined : { name: polymorphism.discriminator, tag: target.tag };
|
|
284
|
+
return serializeContract(value, target.spec, customConverters, typeMetadata);
|
|
285
|
+
}
|
|
286
|
+
/** Writes `value` with exactly `spec`'s properties, after the tag when one is given. */
|
|
287
|
+
function serializeContract(value, spec, customConverters, typeMetadata) {
|
|
288
|
+
return writeContainer(() => {
|
|
289
|
+
const obj = value;
|
|
290
|
+
const result = {};
|
|
291
|
+
if (typeMetadata) {
|
|
292
|
+
result[typeMetadata.name] = typeMetadata.tag;
|
|
293
|
+
}
|
|
294
|
+
for (const prop of collectWireProperties(spec)) {
|
|
295
|
+
const tsValue = obj[prop.ts];
|
|
296
|
+
if (tsValue == null && prop.optional) {
|
|
297
|
+
result[prop.json] = null;
|
|
246
298
|
continue;
|
|
247
299
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
}
|
|
300
|
+
const conv = resolveConverter(prop.type, customConverters);
|
|
301
|
+
result[prop.json] = conv.serialize(tsValue);
|
|
251
302
|
}
|
|
252
|
-
|
|
253
|
-
|
|
303
|
+
return result;
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Deserialize unknown data (from JSON.parse) into a typed instance using the
|
|
308
|
+
* spec. A polymorphic spec reads the derived contract its tag selects
|
|
309
|
+
* (FR-007).
|
|
310
|
+
*/
|
|
311
|
+
export function deserializeWithSpec(data, spec, customConverters) {
|
|
312
|
+
const raw = requireJsonObject(data, spec);
|
|
313
|
+
const { polymorphism } = spec;
|
|
314
|
+
if (!polymorphism) {
|
|
315
|
+
return deserializeContract(raw, spec, customConverters);
|
|
316
|
+
}
|
|
317
|
+
const target = resolveDeserializeTarget(raw, spec, polymorphism);
|
|
318
|
+
// The target is `spec` or one of its registered derived contracts, so it builds a `T`.
|
|
319
|
+
return deserializeContract(raw, target, customConverters);
|
|
320
|
+
}
|
|
321
|
+
/** `data` as a JSON object; any other JSON value cannot be converted to the contract. */
|
|
322
|
+
function requireJsonObject(data, spec) {
|
|
323
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) {
|
|
324
|
+
throw cannotConvertTo(spec);
|
|
254
325
|
}
|
|
255
|
-
return
|
|
326
|
+
return data;
|
|
327
|
+
}
|
|
328
|
+
/** Reads `raw` with exactly `spec`'s properties and builds it with `spec`'s factory. */
|
|
329
|
+
function deserializeContract(raw, spec, customConverters) {
|
|
330
|
+
return readContainer("object", () => {
|
|
331
|
+
const deserialized = {};
|
|
332
|
+
for (const prop of collectWireProperties(spec)) {
|
|
333
|
+
const jsonValue = raw[prop.json];
|
|
334
|
+
if (jsonValue === undefined || jsonValue === null) {
|
|
335
|
+
if (prop.optional) {
|
|
336
|
+
deserialized[prop.ts] = null;
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (jsonValue === undefined) {
|
|
340
|
+
throw new JsonException(`Missing required property: "${prop.json}"`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
const conv = resolveConverter(prop.type, customConverters);
|
|
344
|
+
deserialized[prop.ts] = conv.deserialize(jsonValue);
|
|
345
|
+
}
|
|
346
|
+
return spec.factory(deserialized);
|
|
347
|
+
});
|
|
256
348
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown for JSON that does not match its contract, mirroring
|
|
3
|
+
* `System.Text.Json.JsonException`: a value of the wrong JSON kind, a missing
|
|
4
|
+
* required property, an invalid enum value, or a document nested deeper than
|
|
5
|
+
* the maximum depth. Messages carry no `Path` / `LineNumber` suffix
|
|
6
|
+
* (DECIDED-5).
|
|
7
|
+
*/
|
|
8
|
+
export declare class JsonException extends Error {
|
|
9
|
+
readonly name = "JsonException";
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Thrown for a polymorphic contract that cannot handle a payload or a value,
|
|
13
|
+
* mirroring `System.NotSupportedException` as System.Text.Json throws it: a
|
|
14
|
+
* payload without a type discriminator for an abstract or interface base, or
|
|
15
|
+
* a runtime type the base does not register. Messages carry no `Path` /
|
|
16
|
+
* `LineNumber` suffix (DECIDED-5).
|
|
17
|
+
*/
|
|
18
|
+
export declare class NotSupportedException extends Error {
|
|
19
|
+
readonly name = "NotSupportedException";
|
|
20
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown for JSON that does not match its contract, mirroring
|
|
3
|
+
* `System.Text.Json.JsonException`: a value of the wrong JSON kind, a missing
|
|
4
|
+
* required property, an invalid enum value, or a document nested deeper than
|
|
5
|
+
* the maximum depth. Messages carry no `Path` / `LineNumber` suffix
|
|
6
|
+
* (DECIDED-5).
|
|
7
|
+
*/
|
|
8
|
+
export class JsonException extends Error {
|
|
9
|
+
name = "JsonException";
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Thrown for a polymorphic contract that cannot handle a payload or a value,
|
|
13
|
+
* mirroring `System.NotSupportedException` as System.Text.Json throws it: a
|
|
14
|
+
* payload without a type discriminator for an abstract or interface base, or
|
|
15
|
+
* a runtime type the base does not register. Messages carry no `Path` /
|
|
16
|
+
* `LineNumber` suffix (DECIDED-5).
|
|
17
|
+
*/
|
|
18
|
+
export class NotSupportedException extends Error {
|
|
19
|
+
name = "NotSupportedException";
|
|
20
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export type { TypeDescriptor, PrimitiveDescriptor, RefDescriptor, TemporalDescriptor, DecimalDescriptor, MapDescriptor, ArrayDescriptor, HashSetDescriptor, BrandedDescriptor, EnumDescriptor, NumericEnumDescriptor, NullableDescriptor, PropertySpec, TypeSpec, ValueSpec, JsonTypeInfo, JsonConverter, SerializerContextOptions, } from "./types.ts";
|
|
1
|
+
export type { TypeDescriptor, PrimitiveDescriptor, RefDescriptor, TemporalDescriptor, DecimalDescriptor, MapDescriptor, ArrayDescriptor, HashSetDescriptor, BrandedDescriptor, EnumDescriptor, NumericEnumDescriptor, NullableDescriptor, PropertySpec, TypeSpec, ValueSpec, JsonTypeInfo, TypeDiscriminator, UnknownDerivedTypeHandling, DerivedTypeSpec, PolymorphismSpec, JsonReadOptions, JsonConverter, SerializerContextOptions, } from "./types.ts";
|
|
2
2
|
export { SerializerContext } from "./serializer-context.ts";
|
|
3
3
|
export { JsonSerializer, BoundSerializer } from "./json-serializer.ts";
|
|
4
4
|
export { PropertyNamingPolicy } from "./property-naming-policy.ts";
|
|
5
|
-
export { collectProperties } from "./converters.ts";
|
|
5
|
+
export { collectProperties, collectWireProperties } from "./converters.ts";
|
|
6
|
+
export { JsonException, NotSupportedException } from "./errors.ts";
|
|
6
7
|
export { UnionGuardRegistry, registerUnionGuard, getUnionGuard, } from "./union-guard-registry.ts";
|
|
7
8
|
export { publicJsonShape } from "./public-json-shape.ts";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { SerializerContext } from "./serializer-context.js";
|
|
2
2
|
export { JsonSerializer, BoundSerializer } from "./json-serializer.js";
|
|
3
3
|
export { PropertyNamingPolicy } from "./property-naming-policy.js";
|
|
4
|
-
export { collectProperties } from "./converters.js";
|
|
4
|
+
export { collectProperties, collectWireProperties } from "./converters.js";
|
|
5
|
+
export { JsonException, NotSupportedException } from "./errors.js";
|
|
5
6
|
export { UnionGuardRegistry, registerUnionGuard, getUnionGuard, } from "./union-guard-registry.js";
|
|
6
7
|
export { publicJsonShape } from "./public-json-shape.js";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { PolymorphismSpec, TypeDiscriminator, TypeSpec } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* The contract a polymorphic base writes a value with, and the tag written
|
|
4
|
+
* before its properties (absent: no tag).
|
|
5
|
+
*/
|
|
6
|
+
export interface SerializeTarget {
|
|
7
|
+
readonly spec: TypeSpec;
|
|
8
|
+
readonly tag?: TypeDiscriminator;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Chooses the contract and tag a polymorphic base writes `value` with
|
|
12
|
+
* (FR-005, FR-019): a class instance by its constructor (a registered type
|
|
13
|
+
* first, then the base itself), a plain object by the `[PlainObject]` variant
|
|
14
|
+
* guards in test order, anything else by `unknownDerivedType`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function resolveSerializeTarget(value: unknown, spec: TypeSpec, polymorphism: PolymorphismSpec): SerializeTarget;
|
|
17
|
+
/**
|
|
18
|
+
* Chooses the contract a polymorphic base reads `raw` with (FR-007): the
|
|
19
|
+
* contract of a known tag, the base for a missing tag (or an ignored unknown
|
|
20
|
+
* one) of a concrete base. Throws System.Text.Json's exceptions otherwise,
|
|
21
|
+
* including for misplaced metadata: a later discriminator, `$id` / `$ref` /
|
|
22
|
+
* `$values`, or any other `$`-prefixed key.
|
|
23
|
+
*/
|
|
24
|
+
export declare function resolveDeserializeTarget(raw: Record<string, unknown>, spec: TypeSpec, polymorphism: PolymorphismSpec): TypeSpec;
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { cannotConvertTo, contractNameOf } from "./contract-name.js";
|
|
2
|
+
import { JsonException, NotSupportedException } from "./errors.js";
|
|
3
|
+
const dispatchIndexes = new WeakMap();
|
|
4
|
+
function dispatchIndexOf(polymorphism) {
|
|
5
|
+
const cached = dispatchIndexes.get(polymorphism);
|
|
6
|
+
if (cached) {
|
|
7
|
+
return cached;
|
|
8
|
+
}
|
|
9
|
+
const index = buildDispatchIndex(polymorphism);
|
|
10
|
+
dispatchIndexes.set(polymorphism, index);
|
|
11
|
+
return index;
|
|
12
|
+
}
|
|
13
|
+
function buildDispatchIndex(polymorphism) {
|
|
14
|
+
const variants = polymorphism.derived.map((entry) => ({
|
|
15
|
+
tag: entry.tag,
|
|
16
|
+
spec: entry.spec(),
|
|
17
|
+
test: entry.test,
|
|
18
|
+
}));
|
|
19
|
+
const byConstructor = new Map();
|
|
20
|
+
const byTag = new Map();
|
|
21
|
+
for (const variant of variants) {
|
|
22
|
+
if (variant.spec.type) {
|
|
23
|
+
byConstructor.set(variant.spec.type, { spec: variant.spec, tag: variant.tag });
|
|
24
|
+
}
|
|
25
|
+
if (variant.tag !== undefined) {
|
|
26
|
+
byTag.set(variant.tag, variant.spec);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const testOrder = polymorphism.testOrder ?? variants.map((_, position) => position);
|
|
30
|
+
const structural = testOrder
|
|
31
|
+
.map((position) => variants[position])
|
|
32
|
+
.filter((variant) => variant?.test !== undefined);
|
|
33
|
+
return { byConstructor, byTag, structural };
|
|
34
|
+
}
|
|
35
|
+
// ─── Serialize ───────────────────────────────────────────────────────────────
|
|
36
|
+
/**
|
|
37
|
+
* Chooses the contract and tag a polymorphic base writes `value` with
|
|
38
|
+
* (FR-005, FR-019): a class instance by its constructor (a registered type
|
|
39
|
+
* first, then the base itself), a plain object by the `[PlainObject]` variant
|
|
40
|
+
* guards in test order, anything else by `unknownDerivedType`.
|
|
41
|
+
*/
|
|
42
|
+
export function resolveSerializeTarget(value, spec, polymorphism) {
|
|
43
|
+
const index = dispatchIndexOf(polymorphism);
|
|
44
|
+
const target = isPlainObject(value)
|
|
45
|
+
? matchStructuralVariant(value, spec, polymorphism, index)
|
|
46
|
+
: matchConstructor(constructorOf(value), spec, index);
|
|
47
|
+
return target ?? unknownDerivedTypeTarget(value, spec, polymorphism, index);
|
|
48
|
+
}
|
|
49
|
+
/** A value whose prototype is `Object.prototype` or `null`: it has no runtime type. */
|
|
50
|
+
function isPlainObject(value) {
|
|
51
|
+
if (typeof value !== "object" || value === null) {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
const prototype = Object.getPrototypeOf(value);
|
|
55
|
+
return prototype === Object.prototype || prototype === null;
|
|
56
|
+
}
|
|
57
|
+
function constructorOf(value) {
|
|
58
|
+
return Object.getPrototypeOf(value).constructor;
|
|
59
|
+
}
|
|
60
|
+
function matchConstructor(runtimeType, spec, index) {
|
|
61
|
+
const registered = index.byConstructor.get(runtimeType);
|
|
62
|
+
if (registered) {
|
|
63
|
+
return registered;
|
|
64
|
+
}
|
|
65
|
+
return runtimeType === spec.type ? { spec } : undefined;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The first `[PlainObject]` variant whose guard accepts `value`. With none,
|
|
69
|
+
* a concrete base without a constructor (a `[PlainObject]` base) writes the
|
|
70
|
+
* value as the base itself, with no tag.
|
|
71
|
+
*/
|
|
72
|
+
function matchStructuralVariant(value, spec, polymorphism, index) {
|
|
73
|
+
const variant = index.structural.find((candidate) => candidate.test(value));
|
|
74
|
+
if (variant) {
|
|
75
|
+
return variant;
|
|
76
|
+
}
|
|
77
|
+
const isConcretePlainObjectBase = !polymorphism.abstract && spec.type === undefined;
|
|
78
|
+
return isConcretePlainObjectBase ? { spec } : undefined;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The target of a runtime type the base does not register (FR-005), per
|
|
82
|
+
* `unknownDerivedType`: fail, the base contract with no tag, or the nearest
|
|
83
|
+
* registered ancestor (else the base contract).
|
|
84
|
+
*/
|
|
85
|
+
function unknownDerivedTypeTarget(value, spec, polymorphism, index) {
|
|
86
|
+
switch (polymorphism.unknownDerivedType ?? "failSerialization") {
|
|
87
|
+
case "failSerialization":
|
|
88
|
+
throw new NotSupportedException(`Runtime type '${runtimeTypeNameOf(value)}' is not supported by polymorphic type ` +
|
|
89
|
+
`'${contractNameOf(spec)}'.`);
|
|
90
|
+
case "fallBackToBaseType":
|
|
91
|
+
return { spec };
|
|
92
|
+
case "fallBackToNearestAncestor":
|
|
93
|
+
return nearestRegisteredAncestorOf(value, index) ?? { spec };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The registration of the nearest ancestor class of `value`'s constructor,
|
|
98
|
+
* abstract registrations included (FR-017). A plain object has none: its
|
|
99
|
+
* most specific matching guard already is its nearest ancestor (FR-019).
|
|
100
|
+
*/
|
|
101
|
+
function nearestRegisteredAncestorOf(value, index) {
|
|
102
|
+
if (isPlainObject(value)) {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
for (const ancestor of ancestorConstructorsOf(constructorOf(value))) {
|
|
106
|
+
const registered = index.byConstructor.get(ancestor);
|
|
107
|
+
if (registered) {
|
|
108
|
+
return registered;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
/** The constructors `runtimeType` extends, nearest first. */
|
|
114
|
+
function* ancestorConstructorsOf(runtimeType) {
|
|
115
|
+
const parent = Object.getPrototypeOf(runtimeType);
|
|
116
|
+
if (parent === null || parent === Function.prototype) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
yield parent;
|
|
120
|
+
yield* ancestorConstructorsOf(parent);
|
|
121
|
+
}
|
|
122
|
+
/** The runtime type name STJ would report: the constructor's name, `Object` for a plain object. */
|
|
123
|
+
function runtimeTypeNameOf(value) {
|
|
124
|
+
if (isPlainObject(value)) {
|
|
125
|
+
return "Object";
|
|
126
|
+
}
|
|
127
|
+
const runtimeType = constructorOf(value);
|
|
128
|
+
return runtimeType?.name || "Object";
|
|
129
|
+
}
|
|
130
|
+
// ─── Deserialize ─────────────────────────────────────────────────────────────
|
|
131
|
+
/** The prefix System.Text.Json reserves for metadata property names. */
|
|
132
|
+
const METADATA_PREFIX = "$";
|
|
133
|
+
/** The metadata property of a preserved array. */
|
|
134
|
+
const VALUES_KEY = "$values";
|
|
135
|
+
/** Metadata names System.Text.Json knows besides the discriminator, unsupported here. */
|
|
136
|
+
const REFERENCE_METADATA_NAMES = new Set(["$id", "$ref"]);
|
|
137
|
+
/** A metadata property that is unsupported, or not the first key of the payload. */
|
|
138
|
+
const NOT_FIRST_METADATA_MESSAGE = "The metadata property is either not supported by the type or is not the first property in " +
|
|
139
|
+
"the deserialized JSON object.";
|
|
140
|
+
/** Any other key that starts with `$` in a polymorphic payload. */
|
|
141
|
+
const DOLLAR_PROPERTY_MESSAGE = "Properties that start with '$' are not allowed in types that support metadata. Either " +
|
|
142
|
+
"replace the character or disable reference preservation and polymorphic deserialization.";
|
|
143
|
+
/** `$values` as the first key of a polymorphic payload. */
|
|
144
|
+
const LEADING_VALUES_MESSAGE = "A '$values' metadata property must always be preceded by other metadata properties, such " +
|
|
145
|
+
"as '$id' or '$type'.";
|
|
146
|
+
const ARRAY_INDEX_PATTERN = /^(?:0|[1-9]\d*)$/;
|
|
147
|
+
const MAX_ARRAY_INDEX = 4_294_967_294;
|
|
148
|
+
const INT32_MIN = -2_147_483_648;
|
|
149
|
+
const INT32_MAX = 2_147_483_647;
|
|
150
|
+
/**
|
|
151
|
+
* Chooses the contract a polymorphic base reads `raw` with (FR-007): the
|
|
152
|
+
* contract of a known tag, the base for a missing tag (or an ignored unknown
|
|
153
|
+
* one) of a concrete base. Throws System.Text.Json's exceptions otherwise,
|
|
154
|
+
* including for misplaced metadata: a later discriminator, `$id` / `$ref` /
|
|
155
|
+
* `$values`, or any other `$`-prefixed key.
|
|
156
|
+
*/
|
|
157
|
+
export function resolveDeserializeTarget(raw, spec, polymorphism) {
|
|
158
|
+
const keys = documentOrderKeysOf(raw);
|
|
159
|
+
const allowsOutOfOrderTag = spec.readOptions?.allowOutOfOrderMetadataProperties ?? false;
|
|
160
|
+
return allowsOutOfOrderTag
|
|
161
|
+
? resolveWithTagAnywhere(raw, keys, spec, polymorphism)
|
|
162
|
+
: resolveWithLeadingTag(raw, keys, spec, polymorphism);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The default: the tag counts only as the first key. Metadata in the first
|
|
166
|
+
* position is checked before a missing tag is reported; every later key is
|
|
167
|
+
* checked after the contract is chosen.
|
|
168
|
+
*/
|
|
169
|
+
function resolveWithLeadingTag(raw, keys, spec, polymorphism) {
|
|
170
|
+
const { discriminator } = polymorphism;
|
|
171
|
+
const [firstKey] = keys;
|
|
172
|
+
const hasLeadingTag = firstKey === discriminator;
|
|
173
|
+
if (!hasLeadingTag && firstKey !== undefined) {
|
|
174
|
+
throwIfLeadingMetadata(firstKey);
|
|
175
|
+
}
|
|
176
|
+
const tag = hasLeadingTag ? readTag(raw[discriminator], spec) : undefined;
|
|
177
|
+
const target = contractOfTag(tag, spec, polymorphism);
|
|
178
|
+
const laterKeys = hasLeadingTag ? keys.slice(1) : keys;
|
|
179
|
+
for (const key of laterKeys) {
|
|
180
|
+
throwIfMetadata(key, discriminator, NOT_FIRST_METADATA_MESSAGE);
|
|
181
|
+
}
|
|
182
|
+
return target;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* `allowOutOfOrderMetadataProperties`: every key is checked in document
|
|
186
|
+
* order (the tag's JSON kind where it appears), and the contract is chosen
|
|
187
|
+
* after the walk. A `$values` key makes System.Text.Json expect a preserved
|
|
188
|
+
* array: a data key before it, or any non-metadata key after it, fails with
|
|
189
|
+
* its two-reason message; an object that ends with `$values` pending fails
|
|
190
|
+
* after its tag is resolved, or with the leading-`$values` message when it
|
|
191
|
+
* has no tag (measured on .NET 10).
|
|
192
|
+
*/
|
|
193
|
+
function resolveWithTagAnywhere(raw, keys, spec, polymorphism) {
|
|
194
|
+
const walk = { tag: undefined, sawDataKey: false, valuesPending: false };
|
|
195
|
+
for (const key of keys) {
|
|
196
|
+
visitOutOfOrderKey(key, raw, spec, polymorphism.discriminator, walk);
|
|
197
|
+
}
|
|
198
|
+
if (!walk.valuesPending) {
|
|
199
|
+
return contractOfTag(walk.tag, spec, polymorphism);
|
|
200
|
+
}
|
|
201
|
+
if (walk.tag === undefined) {
|
|
202
|
+
throw new JsonException(LEADING_VALUES_MESSAGE);
|
|
203
|
+
}
|
|
204
|
+
throwIfUnrecognizedTag(walk.tag, polymorphism);
|
|
205
|
+
throw new JsonException(NOT_FIRST_METADATA_MESSAGE);
|
|
206
|
+
}
|
|
207
|
+
function visitOutOfOrderKey(key, raw, spec, discriminator, walk) {
|
|
208
|
+
if (key === discriminator) {
|
|
209
|
+
walk.tag = readTag(raw[discriminator], spec);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (REFERENCE_METADATA_NAMES.has(key)) {
|
|
213
|
+
throw new JsonException(NOT_FIRST_METADATA_MESSAGE);
|
|
214
|
+
}
|
|
215
|
+
if (key === VALUES_KEY) {
|
|
216
|
+
if (walk.sawDataKey) {
|
|
217
|
+
throw new JsonException(outOfOrderValuesMessage(key, spec));
|
|
218
|
+
}
|
|
219
|
+
walk.valuesPending = true;
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (walk.valuesPending) {
|
|
223
|
+
throw new JsonException(outOfOrderValuesMessage(key, spec));
|
|
224
|
+
}
|
|
225
|
+
throwIfMetadata(key, discriminator, NOT_FIRST_METADATA_MESSAGE);
|
|
226
|
+
walk.sawDataKey = true;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* STJ's two-reason message when `$values` and a non-metadata `propertyName`
|
|
230
|
+
* share an object read with out-of-order metadata allowed.
|
|
231
|
+
*/
|
|
232
|
+
function outOfOrderValuesMessage(propertyName, spec) {
|
|
233
|
+
return ("Deserialization failed for one of these reasons:\n" +
|
|
234
|
+
"1. A JSON object containing metadata for a nested array includes a non-metadata property " +
|
|
235
|
+
`'${propertyName}'.\n` +
|
|
236
|
+
`2. The JSON value could not be converted to ${contractNameOf(spec)}.`);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* The keys of a parsed object in JSON document order, as far as JS keeps it:
|
|
240
|
+
* array-index keys (`"0"`, `"1"`, …) are enumerated first whatever their
|
|
241
|
+
* position, so they are left out. They never start with `$`, so the metadata
|
|
242
|
+
* checks lose nothing; only an index key written before the tag goes
|
|
243
|
+
* unnoticed (a documented divergence).
|
|
244
|
+
*/
|
|
245
|
+
function documentOrderKeysOf(raw) {
|
|
246
|
+
return Object.keys(raw).filter((key) => !isArrayIndex(key));
|
|
247
|
+
}
|
|
248
|
+
function isArrayIndex(key) {
|
|
249
|
+
return ARRAY_INDEX_PATTERN.test(key) && Number(key) <= MAX_ARRAY_INDEX;
|
|
250
|
+
}
|
|
251
|
+
/** `$id` / `$ref` / `$values` as the first key fail before a missing tag is reported. */
|
|
252
|
+
function throwIfLeadingMetadata(key) {
|
|
253
|
+
if (key === VALUES_KEY) {
|
|
254
|
+
throw new JsonException(LEADING_VALUES_MESSAGE);
|
|
255
|
+
}
|
|
256
|
+
if (REFERENCE_METADATA_NAMES.has(key)) {
|
|
257
|
+
throw new JsonException(NOT_FIRST_METADATA_MESSAGE);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Rejects a key System.Text.Json reads as misplaced metadata: the
|
|
262
|
+
* discriminator, `$id` / `$ref` (unsupported or not first), `$values` (with
|
|
263
|
+
* `valuesMessage`), or any other key that starts with `$`.
|
|
264
|
+
*/
|
|
265
|
+
function throwIfMetadata(key, discriminator, valuesMessage) {
|
|
266
|
+
const message = metadataErrorMessageOf(key, discriminator, valuesMessage);
|
|
267
|
+
if (message !== undefined) {
|
|
268
|
+
throw new JsonException(message);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function metadataErrorMessageOf(key, discriminator, valuesMessage) {
|
|
272
|
+
if (key === discriminator || REFERENCE_METADATA_NAMES.has(key)) {
|
|
273
|
+
return NOT_FIRST_METADATA_MESSAGE;
|
|
274
|
+
}
|
|
275
|
+
if (key === VALUES_KEY) {
|
|
276
|
+
return valuesMessage;
|
|
277
|
+
}
|
|
278
|
+
return key.startsWith(METADATA_PREFIX) ? DOLLAR_PROPERTY_MESSAGE : undefined;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The contract a tag selects (FR-007); `undefined` is a missing tag. An
|
|
282
|
+
* unknown tag reads like a missing one under `ignoreUnrecognizedTags`.
|
|
283
|
+
*/
|
|
284
|
+
function contractOfTag(tag, spec, polymorphism) {
|
|
285
|
+
if (tag === undefined) {
|
|
286
|
+
return contractWithoutTag(spec, polymorphism);
|
|
287
|
+
}
|
|
288
|
+
const derived = dispatchIndexOf(polymorphism).byTag.get(tag);
|
|
289
|
+
if (derived) {
|
|
290
|
+
return derived;
|
|
291
|
+
}
|
|
292
|
+
throwIfUnrecognizedTag(tag, polymorphism);
|
|
293
|
+
return contractWithoutTag(spec, polymorphism);
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Rejects a tag no derived type registers, unless `ignoreUnrecognizedTags`
|
|
297
|
+
* lets it through. Only the tag itself is checked: an object that ends with
|
|
298
|
+
* `$values` pending fails as misplaced metadata even on an abstract base
|
|
299
|
+
* (measured on .NET 10), so the missing-tag rule must not run there.
|
|
300
|
+
*/
|
|
301
|
+
function throwIfUnrecognizedTag(tag, polymorphism) {
|
|
302
|
+
const isRegistered = dispatchIndexOf(polymorphism).byTag.has(tag);
|
|
303
|
+
if (isRegistered || polymorphism.ignoreUnrecognizedTags) {
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
throw new JsonException(`Read unrecognized type discriminator id '${tag}'.`);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* A missing tag reads the base contract of a concrete base; an abstract or
|
|
310
|
+
* interface base cannot be read.
|
|
311
|
+
*/
|
|
312
|
+
function contractWithoutTag(spec, polymorphism) {
|
|
313
|
+
if (polymorphism.abstract) {
|
|
314
|
+
throw new NotSupportedException(`The JSON payload for polymorphic interface or abstract type '${contractNameOf(spec)}' ` +
|
|
315
|
+
"must specify a type discriminator.");
|
|
316
|
+
}
|
|
317
|
+
return spec;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* A tag is a JSON string or a JSON number that fits an `Int32`, which
|
|
321
|
+
* System.Text.Json reads it as; any other number cannot be converted to the
|
|
322
|
+
* base, and any other JSON value is not a valid metadata property.
|
|
323
|
+
*/
|
|
324
|
+
function readTag(value, spec) {
|
|
325
|
+
if (typeof value === "string") {
|
|
326
|
+
return value;
|
|
327
|
+
}
|
|
328
|
+
if (typeof value !== "number") {
|
|
329
|
+
throw new JsonException("The '$id', '$ref' or '$type' metadata properties must be JSON strings. " +
|
|
330
|
+
`Current token type is '${tokenTypeOf(value)}'.`);
|
|
331
|
+
}
|
|
332
|
+
if (!isInt32(value)) {
|
|
333
|
+
throw cannotConvertTo(spec);
|
|
334
|
+
}
|
|
335
|
+
return value;
|
|
336
|
+
}
|
|
337
|
+
function isInt32(value) {
|
|
338
|
+
return Number.isInteger(value) && value >= INT32_MIN && value <= INT32_MAX;
|
|
339
|
+
}
|
|
340
|
+
/** The `JsonTokenType` name System.Text.Json reports for a non-scalar parsed value. */
|
|
341
|
+
function tokenTypeOf(value) {
|
|
342
|
+
if (value === null) {
|
|
343
|
+
return "Null";
|
|
344
|
+
}
|
|
345
|
+
if (typeof value === "boolean") {
|
|
346
|
+
return value ? "True" : "False";
|
|
347
|
+
}
|
|
348
|
+
return Array.isArray(value) ? "StartArray" : "StartObject";
|
|
349
|
+
}
|
|
@@ -93,8 +93,64 @@ export interface TypeSpec<T = unknown> {
|
|
|
93
93
|
readonly base?: TypeSpec;
|
|
94
94
|
/** Constructs T from a Record<ts-field-name, deserialized-value> */
|
|
95
95
|
readonly factory: (props: Record<string, unknown>) => T;
|
|
96
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Own properties, in wire order (base properties come from the base spec).
|
|
98
|
+
* For a spec without `base` whose C# base has no spec, the inlined
|
|
99
|
+
* properties of the ancestors follow, nearest first (FR-009).
|
|
100
|
+
*/
|
|
97
101
|
readonly properties: readonly PropertySpec[];
|
|
102
|
+
/**
|
|
103
|
+
* TS names of base properties this contract hides with a `[JsonIgnore]`
|
|
104
|
+
* override: no spec of its base chain writes or reads them for this
|
|
105
|
+
* contract (System.Text.Json writes none of them).
|
|
106
|
+
*/
|
|
107
|
+
readonly ignoredProperties?: readonly string[];
|
|
108
|
+
/**
|
|
109
|
+
* Present on a polymorphic base (`[JsonDerivedType]`): serializing and
|
|
110
|
+
* deserializing through this spec dispatch to a derived contract. A
|
|
111
|
+
* derived contract reached by dispatch is never dispatched again.
|
|
112
|
+
*/
|
|
113
|
+
readonly polymorphism?: PolymorphismSpec;
|
|
114
|
+
/** The context's read behavior; absent when it is System.Text.Json's default. */
|
|
115
|
+
readonly readOptions?: JsonReadOptions;
|
|
116
|
+
}
|
|
117
|
+
/** A `[JsonDerivedType]` tag: a JSON string or a JSON number, never equal to each other. */
|
|
118
|
+
export type TypeDiscriminator = string | number;
|
|
119
|
+
/** `JsonUnknownDerivedTypeHandling`: what a write does with an unregistered runtime type. */
|
|
120
|
+
export type UnknownDerivedTypeHandling = "failSerialization" | "fallBackToBaseType" | "fallBackToNearestAncestor";
|
|
121
|
+
/** One `[JsonDerivedType]` registration of a polymorphic base (possibly the base itself). */
|
|
122
|
+
export interface DerivedTypeSpec {
|
|
123
|
+
/** Absent for an untagged registration. */
|
|
124
|
+
readonly tag?: TypeDiscriminator;
|
|
125
|
+
/** Lazy: base and derived getters reference each other. */
|
|
126
|
+
readonly spec: () => TypeSpec;
|
|
127
|
+
/** `[PlainObject]` variants only: the guard that selects this variant on write. */
|
|
128
|
+
readonly test?: (value: unknown) => boolean;
|
|
129
|
+
}
|
|
130
|
+
/** The data-only `[JsonPolymorphic]` / `[JsonDerivedType]` description of a base. */
|
|
131
|
+
export interface PolymorphismSpec {
|
|
132
|
+
/** The discriminator property name, verbatim (never passed through a naming policy). */
|
|
133
|
+
readonly discriminator: string;
|
|
134
|
+
/** The C# base is abstract or an interface: a missing or ignored tag cannot read the base. */
|
|
135
|
+
readonly abstract?: boolean;
|
|
136
|
+
/** The C# simple name for messages, when the base has no constructor (interface, `[PlainObject]`). */
|
|
137
|
+
readonly typeName?: string;
|
|
138
|
+
/** The registrations, in attribute order. */
|
|
139
|
+
readonly derived: readonly DerivedTypeSpec[];
|
|
140
|
+
/** Indices into `derived` in guard test order; absent when it is attribute order. */
|
|
141
|
+
readonly testOrder?: readonly number[];
|
|
142
|
+
/** Default `"failSerialization"`. */
|
|
143
|
+
readonly unknownDerivedType?: UnknownDerivedTypeHandling;
|
|
144
|
+
/** An unknown tag reads the base (a concrete base) instead of throwing. */
|
|
145
|
+
readonly ignoreUnrecognizedTags?: boolean;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Context-level read behavior mirrored from `[JsonSourceGenerationOptions]`.
|
|
149
|
+
* Every member is optional; an absent member is System.Text.Json's default.
|
|
150
|
+
*/
|
|
151
|
+
export interface JsonReadOptions {
|
|
152
|
+
/** The type discriminator may appear after other properties (FR-002). */
|
|
153
|
+
readonly allowOutOfOrderMetadataProperties?: boolean;
|
|
98
154
|
}
|
|
99
155
|
/**
|
|
100
156
|
* Spec of a non-object `[JsonSerializable]` root (a collection, dictionary,
|