metano-runtime 3.0.1 → 3.1.0

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.
Files changed (211) hide show
  1. package/dist/system/char-members.d.ts +51 -0
  2. package/dist/system/char-members.js +108 -0
  3. package/dist/system/collections/array-helpers.d.ts +28 -0
  4. package/dist/system/collections/array-helpers.js +105 -0
  5. package/dist/system/collections/hash-core.d.ts +5 -0
  6. package/dist/system/collections/hash-core.js +24 -0
  7. package/dist/system/collections/helpers.d.ts +16 -3
  8. package/dist/system/collections/helpers.js +28 -2
  9. package/dist/system/collections/immutable-list-builder-core.d.ts +7 -2
  10. package/dist/system/collections/immutable-list-builder-core.js +11 -0
  11. package/dist/system/collections/immutable-list-core.d.ts +8 -0
  12. package/dist/system/collections/immutable-list-core.js +19 -1
  13. package/dist/system/collections/immutable-storage.d.ts +2 -0
  14. package/dist/system/collections/immutable-storage.js +6 -1
  15. package/dist/system/collections/index.d.ts +2 -0
  16. package/dist/system/collections/index.js +2 -0
  17. package/dist/system/collections/interfaces.d.ts +13 -0
  18. package/dist/system/collections/list.d.ts +3 -0
  19. package/dist/system/collections/list.js +8 -11
  20. package/dist/system/collections/read-only-list.d.ts +11 -0
  21. package/dist/system/collections/read-only-list.js +26 -1
  22. package/dist/system/collections/sorted-list.d.ts +5 -0
  23. package/dist/system/collections/sorted-list.js +12 -1
  24. package/dist/system/collections/string-comparer.d.ts +14 -0
  25. package/dist/system/collections/string-comparer.js +45 -0
  26. package/dist/system/decimal-parsing.d.ts +12 -0
  27. package/dist/system/decimal-parsing.js +86 -0
  28. package/dist/system/exceptions/index.d.ts +1 -0
  29. package/dist/system/exceptions/index.js +1 -0
  30. package/dist/system/exceptions/throw-error.d.ts +7 -0
  31. package/dist/system/exceptions/throw-error.js +9 -0
  32. package/dist/system/index.d.ts +5 -0
  33. package/dist/system/index.js +5 -0
  34. package/dist/system/int64.d.ts +6 -0
  35. package/dist/system/int64.js +18 -9
  36. package/dist/system/integer-division.d.ts +12 -4
  37. package/dist/system/integer-division.js +19 -2
  38. package/dist/system/json/contract-name.d.ts +2 -1
  39. package/dist/system/json/contract-name.js +3 -2
  40. package/dist/system/json/converters.d.ts +15 -52
  41. package/dist/system/json/converters.js +33 -317
  42. package/dist/system/json/dictionary-keys.js +1 -3
  43. package/dist/system/json/index.d.ts +1 -1
  44. package/dist/system/json/index.js +1 -1
  45. package/dist/system/json/json-serializer.d.ts +12 -1
  46. package/dist/system/json/json-serializer.js +29 -1
  47. package/dist/system/json/json-text-writer.d.ts +17 -0
  48. package/dist/system/json/json-text-writer.js +175 -0
  49. package/dist/system/json/null-reads.d.ts +2 -1
  50. package/dist/system/json/null-reads.js +3 -1
  51. package/dist/system/json/number-from-string.d.ts +2 -0
  52. package/dist/system/json/number-from-string.js +24 -6
  53. package/dist/system/json/numeric-converters.d.ts +4 -4
  54. package/dist/system/json/numeric-converters.js +46 -8
  55. package/dist/system/json/numeric-enum-members.d.ts +3 -3
  56. package/dist/system/json/numeric-enum-members.js +2 -4
  57. package/dist/system/json/spec-plans.d.ts +102 -0
  58. package/dist/system/json/spec-plans.js +312 -0
  59. package/dist/system/json/types.d.ts +15 -9
  60. package/dist/system/lazy.d.ts +15 -0
  61. package/dist/system/lazy.js +43 -0
  62. package/dist/system/linq/grouping.d.ts +12 -0
  63. package/dist/system/linq/grouping.js +42 -0
  64. package/dist/system/linq/index.d.ts +4 -3
  65. package/dist/system/linq/index.js +3 -2
  66. package/dist/system/linq/linq.js +20 -1
  67. package/dist/system/linq/lookup.d.ts +17 -0
  68. package/dist/system/linq/lookup.js +20 -0
  69. package/dist/system/linq/operators.d.ts +35 -5
  70. package/dist/system/linq/operators.js +82 -31
  71. package/dist/system/linq/terminals.d.ts +41 -2
  72. package/dist/system/linq/terminals.js +122 -2
  73. package/dist/system/linq/types.d.ts +48 -4
  74. package/dist/system/math.d.ts +7 -0
  75. package/dist/system/math.js +14 -0
  76. package/dist/system/number-members.d.ts +10 -0
  77. package/dist/system/number-members.js +25 -0
  78. package/dist/system/number-parsing.d.ts +16 -4
  79. package/dist/system/number-parsing.js +21 -4
  80. package/dist/system/string-builder.d.ts +30 -0
  81. package/dist/system/string-builder.js +86 -0
  82. package/dist/system/task-completion-source.d.ts +37 -0
  83. package/dist/system/task-completion-source.js +81 -0
  84. package/dist-unchecked/system/char-members.d.ts +51 -0
  85. package/dist-unchecked/system/char-members.js +108 -0
  86. package/dist-unchecked/system/collections/array-helpers.d.ts +28 -0
  87. package/dist-unchecked/system/collections/array-helpers.js +105 -0
  88. package/dist-unchecked/system/collections/hash-core.d.ts +5 -0
  89. package/dist-unchecked/system/collections/hash-core.js +24 -0
  90. package/dist-unchecked/system/collections/helpers.d.ts +16 -3
  91. package/dist-unchecked/system/collections/helpers.js +28 -2
  92. package/dist-unchecked/system/collections/immutable-list-builder-core.d.ts +7 -2
  93. package/dist-unchecked/system/collections/immutable-list-builder-core.js +11 -0
  94. package/dist-unchecked/system/collections/immutable-list-core.d.ts +8 -0
  95. package/dist-unchecked/system/collections/immutable-list-core.js +19 -1
  96. package/dist-unchecked/system/collections/immutable-storage.d.ts +2 -0
  97. package/dist-unchecked/system/collections/immutable-storage.js +6 -1
  98. package/dist-unchecked/system/collections/index.d.ts +2 -0
  99. package/dist-unchecked/system/collections/index.js +2 -0
  100. package/dist-unchecked/system/collections/interfaces.d.ts +13 -0
  101. package/dist-unchecked/system/collections/list.d.ts +3 -0
  102. package/dist-unchecked/system/collections/list.js +8 -11
  103. package/dist-unchecked/system/collections/read-only-list.d.ts +11 -0
  104. package/dist-unchecked/system/collections/read-only-list.js +26 -1
  105. package/dist-unchecked/system/collections/sorted-list.d.ts +5 -0
  106. package/dist-unchecked/system/collections/sorted-list.js +12 -1
  107. package/dist-unchecked/system/collections/string-comparer.d.ts +14 -0
  108. package/dist-unchecked/system/collections/string-comparer.js +45 -0
  109. package/dist-unchecked/system/decimal-parsing.d.ts +12 -0
  110. package/dist-unchecked/system/decimal-parsing.js +86 -0
  111. package/dist-unchecked/system/exceptions/index.d.ts +1 -0
  112. package/dist-unchecked/system/exceptions/index.js +1 -0
  113. package/dist-unchecked/system/exceptions/throw-error.d.ts +7 -0
  114. package/dist-unchecked/system/exceptions/throw-error.js +9 -0
  115. package/dist-unchecked/system/index.d.ts +5 -0
  116. package/dist-unchecked/system/index.js +5 -0
  117. package/dist-unchecked/system/int64.d.ts +6 -0
  118. package/dist-unchecked/system/int64.js +18 -9
  119. package/dist-unchecked/system/integer-division.d.ts +12 -4
  120. package/dist-unchecked/system/integer-division.js +19 -2
  121. package/dist-unchecked/system/json/contract-name.d.ts +2 -1
  122. package/dist-unchecked/system/json/contract-name.js +3 -2
  123. package/dist-unchecked/system/json/converters.d.ts +15 -52
  124. package/dist-unchecked/system/json/converters.js +33 -317
  125. package/dist-unchecked/system/json/dictionary-keys.js +1 -3
  126. package/dist-unchecked/system/json/index.d.ts +1 -1
  127. package/dist-unchecked/system/json/index.js +1 -1
  128. package/dist-unchecked/system/json/json-serializer.d.ts +12 -1
  129. package/dist-unchecked/system/json/json-serializer.js +29 -1
  130. package/dist-unchecked/system/json/json-text-writer.d.ts +17 -0
  131. package/dist-unchecked/system/json/json-text-writer.js +175 -0
  132. package/dist-unchecked/system/json/null-reads.d.ts +2 -1
  133. package/dist-unchecked/system/json/null-reads.js +3 -1
  134. package/dist-unchecked/system/json/number-from-string.d.ts +2 -0
  135. package/dist-unchecked/system/json/number-from-string.js +24 -6
  136. package/dist-unchecked/system/json/numeric-converters.d.ts +4 -4
  137. package/dist-unchecked/system/json/numeric-converters.js +46 -8
  138. package/dist-unchecked/system/json/numeric-enum-members.d.ts +3 -3
  139. package/dist-unchecked/system/json/numeric-enum-members.js +2 -4
  140. package/dist-unchecked/system/json/spec-plans.d.ts +102 -0
  141. package/dist-unchecked/system/json/spec-plans.js +312 -0
  142. package/dist-unchecked/system/json/types.d.ts +15 -9
  143. package/dist-unchecked/system/lazy.d.ts +15 -0
  144. package/dist-unchecked/system/lazy.js +43 -0
  145. package/dist-unchecked/system/linq/grouping.d.ts +12 -0
  146. package/dist-unchecked/system/linq/grouping.js +42 -0
  147. package/dist-unchecked/system/linq/index.d.ts +4 -3
  148. package/dist-unchecked/system/linq/index.js +3 -2
  149. package/dist-unchecked/system/linq/linq.js +20 -1
  150. package/dist-unchecked/system/linq/lookup.d.ts +17 -0
  151. package/dist-unchecked/system/linq/lookup.js +20 -0
  152. package/dist-unchecked/system/linq/operators.d.ts +35 -5
  153. package/dist-unchecked/system/linq/operators.js +82 -31
  154. package/dist-unchecked/system/linq/terminals.d.ts +41 -2
  155. package/dist-unchecked/system/linq/terminals.js +122 -2
  156. package/dist-unchecked/system/linq/types.d.ts +48 -4
  157. package/dist-unchecked/system/math.d.ts +7 -0
  158. package/dist-unchecked/system/math.js +14 -0
  159. package/dist-unchecked/system/number-members.d.ts +10 -0
  160. package/dist-unchecked/system/number-members.js +25 -0
  161. package/dist-unchecked/system/number-parsing.d.ts +16 -4
  162. package/dist-unchecked/system/number-parsing.js +21 -4
  163. package/dist-unchecked/system/string-builder.d.ts +30 -0
  164. package/dist-unchecked/system/string-builder.js +86 -0
  165. package/dist-unchecked/system/task-completion-source.d.ts +37 -0
  166. package/dist-unchecked/system/task-completion-source.js +81 -0
  167. package/package.json +1 -1
  168. package/src/system/char-members.ts +131 -0
  169. package/src/system/collections/array-helpers.ts +139 -0
  170. package/src/system/collections/hash-core.ts +31 -0
  171. package/src/system/collections/helpers.ts +39 -4
  172. package/src/system/collections/immutable-list-builder-core.ts +16 -2
  173. package/src/system/collections/immutable-list-core.ts +23 -1
  174. package/src/system/collections/immutable-storage.ts +8 -1
  175. package/src/system/collections/index.ts +2 -0
  176. package/src/system/collections/interfaces.ts +16 -0
  177. package/src/system/collections/list.ts +10 -15
  178. package/src/system/collections/read-only-list.ts +35 -1
  179. package/src/system/collections/sorted-list.ts +15 -1
  180. package/src/system/collections/string-comparer.ts +57 -0
  181. package/src/system/decimal-parsing.ts +109 -0
  182. package/src/system/exceptions/index.ts +1 -0
  183. package/src/system/exceptions/throw-error.ts +9 -0
  184. package/src/system/index.ts +5 -0
  185. package/src/system/int64.ts +27 -10
  186. package/src/system/integer-division.ts +43 -6
  187. package/src/system/json/contract-name.ts +3 -2
  188. package/src/system/json/converters.ts +38 -526
  189. package/src/system/json/dictionary-keys.ts +6 -4
  190. package/src/system/json/index.ts +1 -1
  191. package/src/system/json/json-serializer.ts +42 -1
  192. package/src/system/json/json-text-writer.ts +224 -0
  193. package/src/system/json/null-reads.ts +3 -1
  194. package/src/system/json/number-from-string.ts +31 -6
  195. package/src/system/json/numeric-converters.ts +60 -8
  196. package/src/system/json/numeric-enum-members.ts +4 -6
  197. package/src/system/json/spec-plans.ts +524 -0
  198. package/src/system/json/types.ts +15 -9
  199. package/src/system/lazy.ts +62 -0
  200. package/src/system/linq/grouping.ts +77 -0
  201. package/src/system/linq/index.ts +14 -0
  202. package/src/system/linq/linq.ts +23 -1
  203. package/src/system/linq/lookup.ts +34 -0
  204. package/src/system/linq/operators.ts +109 -17
  205. package/src/system/linq/terminals.ts +161 -2
  206. package/src/system/linq/types.ts +66 -3
  207. package/src/system/math.ts +19 -0
  208. package/src/system/number-members.ts +29 -0
  209. package/src/system/number-parsing.ts +24 -4
  210. package/src/system/string-builder.ts +117 -0
  211. package/src/system/task-completion-source.ts +106 -0
@@ -1,21 +1,18 @@
1
1
  import { byteArrayConverter } from "./byte-array-converter.js";
2
- // Only the contract walks (the hot path: one container per object) open and
3
- // close containers with enter/exit; the collection converters keep the
4
- // closure-based `readContainer` / `writeContainer` (#456).
5
- import { enterReadContainer, enterWriteContainer, exitContainer, readContainer, writeContainer, } from "./container-depth.js";
6
- import { cannotConvertTo, cannotConvertToTypeName } from "./contract-name.js";
2
+ // The collection converters keep the closure-based `readContainer` /
3
+ // `writeContainer`; only the contract walks of `spec-plans.ts` (the hot path:
4
+ // one container per object) open and close containers with enter/exit (#456).
5
+ import { readContainer, writeContainer } from "./container-depth.js";
6
+ import { cannotConvertToTypeName } from "./contract-name.js";
7
7
  import { dictionaryKeyConverterOf } from "./dictionary-keys.js";
8
8
  import { readNull, valueTypeNameOf } from "./null-reads.js";
9
- import { createConverterSetCache } from "./converter-set-cache.js";
10
9
  import { JsonException } from "./errors.js";
11
10
  import { exactBigIntLeafOf, numberOfTreeValue, treeWithDoubles } from "./exact-json-number.js";
12
11
  import { forwardsNumberTexts } from "./exact-number-reads.js";
13
- import { holdsBigInts, isNumericEnumValue, numericEnumMembers, } from "./numeric-enum-members.js";
12
+ import { DEFAULT_ENUM_INTEGER_TYPE, holdsBigInts, } from "./numeric-enum-members.js";
13
+ import { isUnsignedIntegerType, isWithinIntegerRange } from "./number-from-string.js";
14
14
  import { decimalConverterOf, int64ConverterOf, nullableTypeName, declaredTypeName, primitiveConverterOf, } from "./numeric-converters.js";
15
15
  import { temporalConverterOf } from "./temporal-reads.js";
16
- import { contractNameOf } from "./contract-name.js";
17
- import { hasTaggedRegistration, resolveDeserializeTarget, resolveSerializeTarget, } from "./polymorphism.js";
18
- import { propertyLookupPlanOf } from "./property-lookup.js";
19
16
  // ─── Converter Resolution ────────────────────────────────────────────────────
20
17
  /**
21
18
  * Resolves the serialize/deserialize pair for a given type descriptor, checking
@@ -27,7 +24,7 @@ import { propertyLookupPlanOf } from "./property-lookup.js";
27
24
  * (#485). Under exact tree numbers, only the built-in converters that read a
28
25
  * number's exact text see a number leaf (`withNumberTextsAsDoubles`).
29
26
  */
30
- function resolveConverter(descriptor, plans, readOptions, errorTypeName = declaredTypeName) {
27
+ export function resolveConverter(descriptor, plans, readOptions, errorTypeName = declaredTypeName) {
31
28
  return customOrBuiltinConverter(descriptor, plans, () => getBuiltinConverter(descriptor, plans, readOptions, errorTypeName));
32
29
  }
33
30
  /** The custom converter of the descriptor's kind, else `builtinOf()`, under the plans' tree numbers. */
@@ -278,11 +275,16 @@ function enumConverter(descriptor) {
278
275
  };
279
276
  }
280
277
  // ─── Enum (Numeric) ──────────────────────────────────────────────────────────
278
+ /**
279
+ * A numeric enum reads any integer of its underlying type, whether a member
280
+ * declares it or not, as System.Text.Json does (#369): a `[Flags]`
281
+ * combination (`3` for `Read | Write`) and an undeclared value (`42`) both
282
+ * read. Any other JSON value, an integer outside the underlying type
283
+ * included, throws System.Text.Json's conversion error naming the enum.
284
+ */
281
285
  function numericEnumConverter(descriptor) {
282
- const validValues = new Set(numericEnumMembers(descriptor).map(([, value]) => value));
283
286
  const reader = holdsBigInts(descriptor) ? int64EnumReader(descriptor) : undefined;
284
- const invalidValue = (value) => new JsonException(`Invalid numeric enum value: ${typeof value === "bigint" ? value : JSON.stringify(value)}. ` +
285
- `Expected one of: ${[...validValues].join(", ")}`);
287
+ const numberType = descriptor.numberType ?? DEFAULT_ENUM_INTEGER_TYPE;
286
288
  return {
287
289
  // A 32-bit enum value is already a number.
288
290
  serialize: (value) => (reader ? reader.serialize(value) : value),
@@ -291,14 +293,27 @@ function numericEnumConverter(descriptor) {
291
293
  if (value === null) {
292
294
  throw cannotConvertToTypeName(descriptor.typeName);
293
295
  }
294
- const read = reader ? reader.deserialize(value) : value;
295
- if (!isNumericEnumValue(read) || !validValues.has(read)) {
296
- throw invalidValue(read);
296
+ if (reader) {
297
+ return reader.deserialize(value);
298
+ }
299
+ if (!isIntegerOfType(value, numberType)) {
300
+ throw cannotConvertToTypeName(descriptor.typeName);
297
301
  }
298
- return read;
302
+ return value;
299
303
  },
300
304
  };
301
305
  }
306
+ /**
307
+ * Whether `value` is a `number` holding an integer within `numberType`'s
308
+ * range. An unsigned type takes no sign, not even `-0`'s (measured: STJ
309
+ * throws for `-0` into a `byte` enum, as for a `ulong`).
310
+ */
311
+ function isIntegerOfType(value, numberType) {
312
+ return (typeof value === "number" &&
313
+ Number.isInteger(value) &&
314
+ !(Object.is(value, -0) && isUnsignedIntegerType(numberType)) &&
315
+ isWithinIntegerRange(BigInt(value), numberType));
316
+ }
302
317
  /**
303
318
  * A 64-bit enum's values are `bigint`s (#701): they are written as their
304
319
  * exact digits and read from the exact token, in the underlying type's
@@ -365,296 +380,6 @@ function refConverter(descriptor, plans) {
365
380
  },
366
381
  };
367
382
  }
368
- // ─── Core serialize/deserialize by spec ──────────────────────────────────────
369
- /**
370
- * Collects all properties from a spec chain, walking the base hierarchy.
371
- * Base properties come first, own properties last: the declaration order a
372
- * factory reads, **not** the wire order (see `collectWireProperties`). An
373
- * override appears once per spec that declares it.
374
- */
375
- export function collectProperties(spec) {
376
- const base = spec.base ? collectProperties(spec.base) : [];
377
- return [...base, ...spec.properties];
378
- }
379
- /**
380
- * The properties a spec writes and reads, in System.Text.Json's wire order
381
- * (FR-009): the spec's own properties, then its base's, recursively. A JSON
382
- * name appears once, from its most-derived declaration, and a base
383
- * declaration whose `ts` name a more-derived spec lists in
384
- * `ignoredProperties` (a `[JsonIgnore]` override) is left out. When any
385
- * property has an `order` (`[JsonPropertyOrder]`), the list is then sorted by
386
- * it, stably, across the whole chain (measured: `{"Der2":20,"Base3":3,"Der1":10,
387
- * "Base1":1,"Der3":30,"Base2":2}` for orders -5, -5, 0, 0, 1, 5).
388
- */
389
- export function collectWireProperties(spec) {
390
- const wire = [];
391
- const writtenNames = new Set();
392
- const ignoredNames = new Set();
393
- for (const contract of specChainOf(spec)) {
394
- const visible = contract.properties.filter((property) => !ignoredNames.has(property.ts) && !writtenNames.has(property.json));
395
- for (const property of visible) {
396
- writtenNames.add(property.json);
397
- wire.push(property);
398
- }
399
- for (const name of contract.ignoredProperties ?? []) {
400
- ignoredNames.add(name);
401
- }
402
- }
403
- return wire.some(hasExplicitOrder) ? wire.sort(byPropertyOrder) : wire;
404
- }
405
- function hasExplicitOrder(property) {
406
- return property.order !== undefined;
407
- }
408
- function byPropertyOrder(left, right) {
409
- return (left.order ?? 0) - (right.order ?? 0);
410
- }
411
- /** The spec and its bases, most-derived first. */
412
- function* specChainOf(spec) {
413
- yield spec;
414
- if (spec.base) {
415
- yield* specChainOf(spec.base);
416
- }
417
- }
418
- /**
419
- * The plans of every custom-converter set, per kind of tree numbers. A plan
420
- * holds converters resolved against its set, so the set is part of the key:
421
- * plans are cached per spec inside each set's entry
422
- * (`converter-set-cache.ts`). Only `deserializeText` reads exact trees, so
423
- * the `exact` plans exist only for the specs it reads that way.
424
- */
425
- const specPlansByTreeNumbers = {
426
- parsed: /* @__PURE__ */ createConverterSetCache((converters) => createSpecPlans(converters, "parsed")),
427
- exact: /* @__PURE__ */ createConverterSetCache((converters) => createSpecPlans(converters, "exact")),
428
- };
429
- function specPlansFor(customConverters, treeNumbers = "parsed") {
430
- return specPlansByTreeNumbers[treeNumbers].entryFor(customConverters);
431
- }
432
- function createSpecPlans(customConverters, treeNumbers) {
433
- const specPlans = new WeakMap();
434
- const valueConverters = new WeakMap();
435
- const plans = {
436
- customConverters,
437
- treeNumbers,
438
- planOf: (spec) => cachedIn(specPlans, spec, () => compileSpecPlan(spec, plans)),
439
- valueConverterOf: (spec) => cachedIn(valueConverters, spec, () => resolveConverter(spec.descriptor, plans, spec.readOptions)),
440
- };
441
- return plans;
442
- }
443
- /**
444
- * How a property's conversion error names the declaring contract, as
445
- * System.Text.Json does (#485): `{"At":"03:04:60"}` on a `HolderTimeOnly`
446
- * names `HolderTimeOnly`, while a value root or an element names the
447
- * temporal type itself.
448
- */
449
- function contractErrorNameOf(spec) {
450
- return () => contractNameOf(spec);
451
- }
452
- /**
453
- * Compiles `spec` without calling into it: nested specs and derived
454
- * contracts are resolved when a value first reaches them, so the plan of a
455
- * recursive spec never compiles itself.
456
- *
457
- * Every property's converter is resolved here, on the spec's first use, so a
458
- * malformed descriptor (a hand-written spec error) fails then, even when the
459
- * value lacks that property.
460
- */
461
- function compileSpecPlan(spec, plans) {
462
- const properties = collectWireProperties(spec);
463
- const assignedIfPresent = new Set(spec.assignIfPresent);
464
- const propertyPlans = properties.map((property) => ({
465
- property,
466
- converter: resolveConverter(property.type, plans, spec.readOptions, contractErrorNameOf(spec)),
467
- assignIfPresent: assignedIfPresent.has(property.ts),
468
- }));
469
- const writeContract = contractWriterOf(propertyPlans);
470
- const readContract = contractReaderOf(spec, propertyPlans);
471
- const { polymorphism } = spec;
472
- if (!polymorphism) {
473
- return {
474
- serialize: (value) => writeContract(value),
475
- deserialize: (data) => readContract(requireJsonObject(data, spec)),
476
- writeContract,
477
- readContract,
478
- };
479
- }
480
- return {
481
- serialize: (value) => serializePolymorphic(value, spec, polymorphism, plans),
482
- deserialize: (data) => deserializePolymorphic(data, spec, polymorphism, plans),
483
- writeContract,
484
- readContract,
485
- };
486
- }
487
- /**
488
- * Serialize a TS object to a JSON-safe plain object using the given spec. A
489
- * polymorphic spec first chooses the derived contract and writes its tag
490
- * before every property (FR-005); the chosen contract is never dispatched
491
- * again (FR-006).
492
- */
493
- export function serializeWithSpec(value, spec, customConverters) {
494
- return specPlansFor(customConverters).planOf(spec).serialize(value);
495
- }
496
- function serializePolymorphic(value, spec, polymorphism, plans) {
497
- const target = resolveSerializeTarget(value, spec, polymorphism);
498
- const typeMetadata = target.tag === undefined ? undefined : { name: polymorphism.discriminator, tag: target.tag };
499
- return plans.planOf(target.spec).writeContract(value, typeMetadata);
500
- }
501
- /** Writes a value with exactly the given properties, after the tag when one is given. */
502
- function contractWriterOf(propertyPlans) {
503
- const writeProperties = propertyWriterOf(propertyPlans);
504
- return (value, typeMetadata) => {
505
- enterWriteContainer();
506
- try {
507
- const result = {};
508
- if (typeMetadata) {
509
- result[typeMetadata.name] = typeMetadata.tag;
510
- }
511
- writeProperties(value, result);
512
- return result;
513
- }
514
- finally {
515
- exitContainer();
516
- }
517
- };
518
- }
519
- /** Writes every property of `source` into `result`, in wire order. */
520
- function propertyWriterOf(propertyPlans) {
521
- return (source, result) => {
522
- for (const { property, converter } of propertyPlans) {
523
- const tsValue = source[property.ts];
524
- if (tsValue == null && property.omitWhenNull) {
525
- continue;
526
- }
527
- if (tsValue == null && property.optional) {
528
- result[property.json] = null;
529
- continue;
530
- }
531
- result[property.json] = converter.serialize(tsValue);
532
- }
533
- };
534
- }
535
- /**
536
- * Deserialize unknown data (from JSON.parse) into a typed instance using the
537
- * spec. A polymorphic spec reads the derived contract its tag selects
538
- * (FR-007). `treeNumbers` says how `data` holds its numbers; a root number
539
- * leaf reads as the number it is, which no contract accepts.
540
- */
541
- export function deserializeWithSpec(data, spec, customConverters, treeNumbers = "parsed") {
542
- const plan = specPlansFor(customConverters, treeNumbers).planOf(spec);
543
- const root = treeNumbers === "exact" ? numberOfTreeValue(data) : data;
544
- // The plan reads `spec` or one of its registered derived contracts, so it builds a `T`.
545
- return plan.deserialize(root);
546
- }
547
- function deserializePolymorphic(data, spec, polymorphism, plans) {
548
- const raw = requireJsonObject(data, spec);
549
- const target = resolveDeserializeTarget(raw, spec, polymorphism);
550
- const metadataKey = consumedMetadataKeyOf(polymorphism);
551
- return plans.planOf(target).readContract(raw, metadataKey);
552
- }
553
- /**
554
- * The discriminator a polymorphic read consumes as metadata, never as a
555
- * property; none for a hierarchy without tags, which reads like a
556
- * non-polymorphic contract.
557
- */
558
- function consumedMetadataKeyOf(polymorphism) {
559
- return hasTaggedRegistration(polymorphism) ? polymorphism.discriminator : undefined;
560
- }
561
- /** `data` as a JSON object; any other JSON value cannot be converted to the contract. */
562
- function requireJsonObject(data, spec) {
563
- if (data === null || typeof data !== "object" || Array.isArray(data)) {
564
- throw cannotConvertTo(spec);
565
- }
566
- return data;
567
- }
568
- /**
569
- * Reads a JSON object with exactly the given properties of `spec` and builds
570
- * it with `spec`'s factory, under `spec`'s read options.
571
- */
572
- function contractReaderOf(spec, propertyPlans) {
573
- const properties = propertyPlans.map(({ property }) => property);
574
- const lookupPlan = propertyLookupPlanOf(properties, spec.readOptions);
575
- const readProperties = propertyReaderOf(spec, propertyPlans);
576
- const assignPresentMembers = presentMemberAssignerOf(propertyPlans);
577
- return (raw, metadataKey) => {
578
- enterReadContainer("object");
579
- try {
580
- const deserialized = readProperties(lookupPlan(raw, metadataKey));
581
- return assignPresentMembers(spec.factory(deserialized), deserialized);
582
- }
583
- finally {
584
- exitContainer();
585
- }
586
- };
587
- }
588
- /**
589
- * Sets every member of the contract's `assignIfPresent` list the payload
590
- * carried on the constructed value, in wire order (System.Text.Json follows
591
- * the payload's order; the order only shows through setter side effects).
592
- */
593
- function presentMemberAssignerOf(propertyPlans) {
594
- const names = propertyPlans
595
- .filter(({ assignIfPresent }) => assignIfPresent)
596
- .map(({ property }) => property.ts);
597
- if (names.length === 0) {
598
- return (value) => value;
599
- }
600
- return (value, deserialized) => {
601
- const target = value;
602
- for (const name of names) {
603
- if (name in deserialized) {
604
- target[name] = deserialized[name];
605
- }
606
- }
607
- return value;
608
- };
609
- }
610
- /**
611
- * Reads every property through `jsonValueOf` into the factory's input. An
612
- * absent (missing or `null`) optional property reads as `null`; a missing
613
- * required one throws; a missing one of the contract's `assignIfPresent`
614
- * list is left out; a `null` on a non-nullable value-type property throws
615
- * naming the declaring contract, as System.Text.Json does (#471).
616
- */
617
- function propertyReaderOf(spec, propertyPlans) {
618
- return (jsonValueOf) => {
619
- const deserialized = {};
620
- for (const { property, converter, assignIfPresent } of propertyPlans) {
621
- const jsonValue = jsonValueOf(property);
622
- if (jsonValue === undefined && assignIfPresent) {
623
- continue;
624
- }
625
- const isAbsent = jsonValue == null;
626
- if (isAbsent && property.optional) {
627
- deserialized[property.ts] = null;
628
- continue;
629
- }
630
- if (jsonValue === null &&
631
- !property.optional &&
632
- valueTypeNameOf(property.type) !== undefined) {
633
- throw cannotConvertTo(spec);
634
- }
635
- if (jsonValue === undefined) {
636
- throw new JsonException(`Missing required property: "${property.json}"`);
637
- }
638
- deserialized[property.ts] = converter.deserialize(jsonValue);
639
- }
640
- return deserialized;
641
- };
642
- }
643
- // ─── Value specs ─────────────────────────────────────────────────────────────
644
- /**
645
- * Serializes a non-object root through its descriptor, exactly as a property
646
- * of that type would be (custom converters still match by kind).
647
- */
648
- export function serializeWithValueSpec(value, spec, customConverters) {
649
- return specPlansFor(customConverters).valueConverterOf(spec).serialize(value);
650
- }
651
- /**
652
- * Deserializes a non-object root through its descriptor, under the spec's
653
- * read options. `treeNumbers` says how `data` holds its numbers.
654
- */
655
- export function deserializeWithValueSpec(data, spec, customConverters, treeNumbers = "parsed") {
656
- return specPlansFor(customConverters, treeNumbers).valueConverterOf(spec).deserialize(data);
657
- }
658
383
  // ─── Memoization ─────────────────────────────────────────────────────────────
659
384
  /** `create()` on first call, its result afterwards (a failed call is retried). */
660
385
  function lazy(create) {
@@ -666,12 +391,3 @@ function lazy(create) {
666
391
  return memo.value;
667
392
  };
668
393
  }
669
- function cachedIn(cache, key, build) {
670
- const cached = cache.get(key);
671
- if (cached !== undefined) {
672
- return cached;
673
- }
674
- const built = build();
675
- cache.set(key, built);
676
- return built;
677
- }
@@ -1,7 +1,7 @@
1
1
  import { readDecimalText } from "./decimal-text.js";
2
2
  import { cannotConvertToTypeName } from "./contract-name.js";
3
3
  import { readEnumIntegerText, readExactNumberText, readNumberTextAsNumber, } from "./number-from-string.js";
4
- import { holdsBigInts, numericEnumMembers } from "./numeric-enum-members.js";
4
+ import { DEFAULT_ENUM_INTEGER_TYPE, holdsBigInts, numericEnumMembers, } from "./numeric-enum-members.js";
5
5
  import { ordinalIgnoreCaseKeyOf } from "./ordinal-ignore-case.js";
6
6
  import { temporalTextOf } from "./temporal-text.js";
7
7
  import { readTemporalText } from "./temporal-reads.js";
@@ -15,8 +15,6 @@ const BOOLEAN_KEYS = /* @__PURE__ */ lazyValue(() => new Map([
15
15
  ]));
16
16
  /** `Guid` property names are read in the `D` format only (`8-4-4-4-12`). */
17
17
  const GUID_D_FORMAT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
- /** The underlying type of an enum key whose descriptor names none, the C# default. */
19
- const DEFAULT_ENUM_INTEGER_TYPE = "System.Int32";
20
18
  const ENUM_NAME_SEPARATOR = ",";
21
19
  const booleanKeyConverter = /* @__PURE__ */ keyConverter((value) => (value ? "True" : "False"), (name) => BOOLEAN_KEYS().get(ordinalIgnoreCaseKeyOf(name)), BOOLEAN_TYPE_NAME);
22
20
  const guidKeyConverter = /* @__PURE__ */ keyConverter(String, (name) => (GUID_D_FORMAT.test(name) ? name.toLowerCase() : undefined), GUID_TYPE_NAME);
@@ -2,6 +2,6 @@ export type { TypeDescriptor, PrimitiveDescriptor, Int64Descriptor, RefDescripto
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, collectWireProperties } from "./converters.ts";
5
+ export { collectProperties, collectWireProperties } from "./spec-plans.ts";
6
6
  export { JsonException, NotSupportedException } from "./errors.ts";
7
7
  export { publicJsonShape } from "./public-json-shape.ts";
@@ -1,6 +1,6 @@
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, collectWireProperties } from "./converters.js";
4
+ export { collectProperties, collectWireProperties } from "./spec-plans.js";
5
5
  export { JsonException, NotSupportedException } from "./errors.js";
6
6
  export { publicJsonShape } from "./public-json-shape.js";
@@ -1,4 +1,4 @@
1
- import type { TypeSpec, ValueSpec, JsonConverter } from "./types.ts";
1
+ import type { TypeSpec, ValueSpec, JsonTypeInfo, JsonConverter } from "./types.ts";
2
2
  import type { SerializerContext } from "./serializer-context.ts";
3
3
  /**
4
4
  * A bound serializer that uses a SerializerContext to resolve custom converters
@@ -13,6 +13,8 @@ export declare class BoundSerializer {
13
13
  serialize<T>(value: T | null, spec: TypeSpec<T>): Record<string, unknown> | null;
14
14
  /** Serialize a non-object root (collection, map, primitive, …) to a JSON-safe value. */
15
15
  serialize<T>(value: T, spec: ValueSpec<T>): unknown;
16
+ /** Serialize a value to JSON text, as System.Text.Json writes it. */
17
+ serializeText<T>(value: T | null, spec: JsonTypeInfo<T>): string;
16
18
  /**
17
19
  * Deserialize a parsed JSON value into a typed instance; JSON `null` reads
18
20
  * as `null`, except for a struct contract (`valueType`), which throws
@@ -65,6 +67,15 @@ export declare class JsonSerializer {
65
67
  static serialize<T>(value: T | null, spec: TypeSpec<T>, converters?: readonly JsonConverter[]): Record<string, unknown> | null;
66
68
  /** Serialize a non-object root (collection, map, primitive, …) to a JSON-safe value. */
67
69
  static serialize<T>(value: T, spec: ValueSpec<T>, converters?: readonly JsonConverter[]): unknown;
70
+ /**
71
+ * Serialize a value to JSON text using the given spec, as System.Text.Json's
72
+ * `Serialize(value, JsonTypeInfo<T>)` writes it: no whitespace, strings
73
+ * escaped by its default encoder (`<` is `\u003C`, `é` is `\u00E9`),
74
+ * numbers in .NET's round-trip text (`1E+20`), `decimal` and 64-bit
75
+ * integers with their exact digits, `null` as `null`. NaN and the
76
+ * infinities throw `ArgumentException`, as STJ throws for them.
77
+ */
78
+ static serializeText<T>(value: T | null, spec: JsonTypeInfo<T>, converters?: readonly JsonConverter[]): string;
68
79
  /**
69
80
  * Deserialize a parsed JSON value (`JSON.parse`'s tree) into a typed
70
81
  * instance using the given spec. `JSON.parse` has already rounded every
@@ -1,8 +1,10 @@
1
- import { serializeWithSpec, deserializeWithSpec, serializeWithValueSpec, deserializeWithValueSpec, } from "./converters.js";
1
+ import { serializeWithSpec, deserializeWithSpec, serializeWithValueSpec, deserializeWithValueSpec, } from "./spec-plans.js";
2
2
  import { specNumberTextLeaves } from "./exact-number-reads.js";
3
3
  import { mayHoldNumberTextLeaf, parseJsonText, readJsonText } from "./json-text-reader.js";
4
4
  import { readNull } from "./null-reads.js";
5
5
  import { isValueSpec } from "./spec-kind.js";
6
+ import { writeJsonText } from "./json-text-writer.js";
7
+ import { throwIfNull } from "../argument-guards.js";
6
8
  /**
7
9
  * Serializes through either spec kind: an object contract walks its
8
10
  * properties, and writes a `null` value as JSON `null` (FR-037); a value root
@@ -46,6 +48,8 @@ function deserializeWithInfo(data, spec, converters, treeNumbers) {
46
48
  * text throws STJ's `JsonException` on every path.
47
49
  */
48
50
  function deserializeTextWithInfo(text, spec, converters) {
51
+ throwIfNull(text, "json");
52
+ throwIfNull(spec, "jsonTypeInfo");
49
53
  const leaves = specNumberTextLeaves(spec);
50
54
  const readsExactTree = leaves !== undefined && mayHoldNumberTextLeaf(text, leaves);
51
55
  if (readsExactTree) {
@@ -53,6 +57,15 @@ function deserializeTextWithInfo(text, spec, converters) {
53
57
  }
54
58
  return deserializeWithInfo(parseJsonText(text), spec, converters);
55
59
  }
60
+ /**
61
+ * Writes JSON text as System.Text.Json's `Serialize(value, JsonTypeInfo<T>)`
62
+ * does (#741): the tree `serialize` builds, written by `writeJsonText`
63
+ * (STJ's escaping and number text, not `JSON.stringify`'s).
64
+ */
65
+ function serializeTextWithInfo(value, spec, converters) {
66
+ throwIfNull(spec, "jsonTypeInfo");
67
+ return writeJsonText(serializeWithInfo(value, spec, converters));
68
+ }
56
69
  /**
57
70
  * A bound serializer that uses a SerializerContext to resolve custom converters
58
71
  * and look up specs by constructor.
@@ -65,6 +78,10 @@ export class BoundSerializer {
65
78
  serialize(value, spec) {
66
79
  return serializeWithInfo(value, spec, this.context.converters);
67
80
  }
81
+ /** Serialize a value to JSON text, as System.Text.Json writes it. */
82
+ serializeText(value, spec) {
83
+ return serializeTextWithInfo(value, spec, this.context.converters);
84
+ }
68
85
  deserialize(data, spec) {
69
86
  return deserializeWithInfo(data, spec, this.context.converters);
70
87
  }
@@ -101,6 +118,17 @@ export class JsonSerializer {
101
118
  static serialize(value, spec, converters) {
102
119
  return serializeWithInfo(value, spec, converters);
103
120
  }
121
+ /**
122
+ * Serialize a value to JSON text using the given spec, as System.Text.Json's
123
+ * `Serialize(value, JsonTypeInfo<T>)` writes it: no whitespace, strings
124
+ * escaped by its default encoder (`<` is `\u003C`, `é` is `\u00E9`),
125
+ * numbers in .NET's round-trip text (`1E+20`), `decimal` and 64-bit
126
+ * integers with their exact digits, `null` as `null`. NaN and the
127
+ * infinities throw `ArgumentException`, as STJ throws for them.
128
+ */
129
+ static serializeText(value, spec, converters) {
130
+ return serializeTextWithInfo(value, spec, converters);
131
+ }
104
132
  static deserialize(data, spec, converters) {
105
133
  return deserializeWithInfo(data, spec, converters);
106
134
  }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Writes the tree `JsonSerializer.serialize` returns as the JSON text
3
+ * System.Text.Json's `JsonSerializer.Serialize(value, JsonTypeInfo<T>)`
4
+ * writes with its default options (#741, measured on .NET 10):
5
+ *
6
+ * - no whitespace;
7
+ * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
8
+ * `\r` and `\t` keep their short escapes; every other control character,
9
+ * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
10
+ * printable ASCII is written `\uXXXX` (upper-case hex, one escape per
11
+ * UTF-16 code unit), and a lone surrogate is written `\uFFFD`;
12
+ * - numbers in .NET's shortest round-trip text (`1E+20`, `1E-07`, `-0`),
13
+ * a `JSON.rawJSON` leaf (an exact `decimal` / 64-bit integer) as its text;
14
+ * NaN and the infinities throw `ArgumentException`, as STJ throws for them.
15
+ */
16
+ /** The JSON text of `tree`, as System.Text.Json writes it. */
17
+ export declare function writeJsonText(tree: unknown): string;