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
@@ -162,18 +162,27 @@ export function uint64FromDecimal(value) {
162
162
  }
163
163
  /** Decimal to an integer of 32 bits or fewer: truncate exactly, then check even when unchecked. */
164
164
  export function narrowFromDecimal(value, bits, signed) {
165
- const message = () => {
166
- const type = bits === 8
167
- ? signed
168
- ? "a signed byte"
169
- : "an unsigned byte"
170
- : `${signed ? "an Int" : "a UInt"}${bits}`;
171
- return `Value was either too large or too small for ${type}.`;
172
- };
173
- const integer = truncatedDecimal(value, message);
165
+ const type = bits === 8
166
+ ? signed
167
+ ? "a signed byte"
168
+ : "an unsigned byte"
169
+ : `${signed ? "an Int" : "a UInt"}${bits}`;
174
170
  const width = BigInt(bits);
175
171
  const min = signed ? -(1n << (width - 1n)) : 0n;
176
172
  const max = signed ? (1n << (width - 1n)) - 1n : (1n << width) - 1n;
173
+ return truncatedDecimalInRange(value, min, max, type);
174
+ }
175
+ /**
176
+ * `(char)m`: the UTF-16 code of the truncated `decimal` (#695).
177
+ *
178
+ * @throws OverflowException("Value was either too large or too small for a character.") outside 0–65535.
179
+ */
180
+ export function charCodeFromDecimal(value) {
181
+ return truncatedDecimalInRange(value, 0n, 0xffffn, "a character");
182
+ }
183
+ function truncatedDecimalInRange(value, min, max, type) {
184
+ const message = () => `Value was either too large or too small for ${type}.`;
185
+ const integer = truncatedDecimal(value, message);
177
186
  return Number(requireRange(integer, min, max, message));
178
187
  }
179
188
  /** `(long)b`: throws OverflowException outside the range, in every context. */
@@ -9,12 +9,20 @@
9
9
  * for integral operands (`-7 / 2` is `-3`). A `null` (or `undefined`) operand yields
10
10
  * `null`, matching C#'s lifted `int?` division.
11
11
  *
12
- * Overflow is not modelled: `int.MinValue / -1` returns `2147483648` instead of
13
- * throwing `OverflowException`, and a `long` quotient beyond `Number.MAX_SAFE_INTEGER`
14
- * loses precision, like every other `long` value mapped to `number`.
15
- *
16
12
  * @throws DivideByZeroException, with .NET's message, when `divisor` is zero,
17
13
  * where a bare `Math.trunc(dividend / divisor)` would yield `Infinity` or `NaN`.
14
+ * @throws OverflowException for `int.MinValue / -1`, whose quotient does not fit `int`.
18
15
  */
19
16
  export declare function intDiv(dividend: number, divisor: number): number;
20
17
  export declare function intDiv(dividend: number | null | undefined, divisor: number | null | undefined): number | null;
18
+ /**
19
+ * `a % b` over `int` or `uint` operands with a divisor that is not a constant:
20
+ * the remainder with the dividend's sign, as JavaScript's `%` computes it, but
21
+ * throwing where .NET throws instead of yielding `NaN` or `0` (#695). A `null`
22
+ * (or `undefined`) operand yields `null`, matching C#'s lifted `int?` remainder.
23
+ *
24
+ * @throws DivideByZeroException, with .NET's message, when `divisor` is zero.
25
+ * @throws OverflowException for `int.MinValue % -1`, as .NET does.
26
+ */
27
+ export declare function intRem(dividend: number, divisor: number): number;
28
+ export declare function intRem(dividend: number | null | undefined, divisor: number | null | undefined): number | null;
@@ -5,13 +5,30 @@
5
5
  * where C# gives `3`.
6
6
  */
7
7
  import { DivideByZeroException } from "./exceptions/divide-by-zero-exception.js";
8
+ import { OverflowException } from "./exceptions/overflow-exception.js";
9
+ const INT32_MIN = -2147483648;
8
10
  export function intDiv(dividend, divisor) {
9
11
  if (dividend == null || divisor == null) {
10
12
  return null;
11
13
  }
14
+ requireInt32Division(dividend, divisor);
15
+ // C# integers have no negative zero: `+ 0` turns the `-0` of `-1 / 3` into `0`.
16
+ return Math.trunc(dividend / divisor) + 0;
17
+ }
18
+ export function intRem(dividend, divisor) {
19
+ if (dividend == null || divisor == null) {
20
+ return null;
21
+ }
22
+ requireInt32Division(dividend, divisor);
23
+ // `+ 0` turns the `-0` of `-4 % 2` into `0`.
24
+ return (dividend % divisor) + 0;
25
+ }
26
+ /** Throws what .NET throws for an `int` `/` or `%`: a zero divisor, or `int.MinValue` by `-1`. */
27
+ function requireInt32Division(dividend, divisor) {
12
28
  if (divisor === 0) {
13
29
  throw new DivideByZeroException();
14
30
  }
15
- // C# integers have no negative zero: `+ 0` turns the `-0` of `-1 / 3` into `0`.
16
- return Math.trunc(dividend / divisor) + 0;
31
+ if (dividend === INT32_MIN && divisor === -1) {
32
+ throw new OverflowException();
33
+ }
17
34
  }
@@ -3,7 +3,8 @@ import { JsonException } from "./errors.ts";
3
3
  /**
4
4
  * The C# type name a contract reports in errors: its constructor's name, the
5
5
  * `typeName` of a polymorphic base without a constructor (an interface or a
6
- * `[PlainObject]` base), and `Object` for any other `[PlainObject]` contract.
6
+ * `[PlainObject]` base), the CLR `typeName` of any other `[PlainObject]`
7
+ * contract (#512), and `Object` for a hand-written spec with none of them.
7
8
  */
8
9
  export declare function contractNameOf(spec: TypeSpec): string;
9
10
  /** System.Text.Json's error for a JSON value that does not fit the spec. */
@@ -3,10 +3,11 @@ import { isValueSpec } from "./spec-kind.js";
3
3
  /**
4
4
  * The C# type name a contract reports in errors: its constructor's name, the
5
5
  * `typeName` of a polymorphic base without a constructor (an interface or a
6
- * `[PlainObject]` base), and `Object` for any other `[PlainObject]` contract.
6
+ * `[PlainObject]` base), the CLR `typeName` of any other `[PlainObject]`
7
+ * contract (#512), and `Object` for a hand-written spec with none of them.
7
8
  */
8
9
  export function contractNameOf(spec) {
9
- return spec.type?.name ?? spec.polymorphism?.typeName ?? "Object";
10
+ return spec.type?.name ?? spec.polymorphism?.typeName ?? spec.typeName ?? "Object";
10
11
  }
11
12
  /**
12
13
  * The type a conversion error names: the CLR name a value-type spec carries
@@ -1,52 +1,15 @@
1
- import type { TypeSpec, PropertySpec, JsonConverter, ValueSpec } from "./types.ts";
2
- /**
3
- * Collects all properties from a spec chain, walking the base hierarchy.
4
- * Base properties come first, own properties last: the declaration order a
5
- * factory reads, **not** the wire order (see `collectWireProperties`). An
6
- * override appears once per spec that declares it.
7
- */
8
- export declare function collectProperties(spec: TypeSpec): readonly PropertySpec[];
9
- /**
10
- * The properties a spec writes and reads, in System.Text.Json's wire order
11
- * (FR-009): the spec's own properties, then its base's, recursively. A JSON
12
- * name appears once, from its most-derived declaration, and a base
13
- * declaration whose `ts` name a more-derived spec lists in
14
- * `ignoredProperties` (a `[JsonIgnore]` override) is left out. When any
15
- * property has an `order` (`[JsonPropertyOrder]`), the list is then sorted by
16
- * it, stably, across the whole chain (measured: `{"Der2":20,"Base3":3,"Der1":10,
17
- * "Base1":1,"Der3":30,"Base2":2}` for orders -5, -5, 0, 0, 1, 5).
18
- */
19
- export declare function collectWireProperties(spec: TypeSpec): readonly PropertySpec[];
20
- /**
21
- * How the tree being read holds its numbers: `parsed`, each a `number`, as
22
- * `JSON.parse` builds it; `exact`, some as leaves, as `readJsonText` builds
23
- * it (#457): a `JsonNumberText` for those with more significant digits than
24
- * a double holds and, for a spec that reads a 64-bit integer, a
25
- * `JsonNonIntegerNumber` for the other ones with a fraction or an exponent
26
- * (`NumberTextLeaves`).
27
- */
28
- export type TreeNumbers = "parsed" | "exact";
29
- /**
30
- * Serialize a TS object to a JSON-safe plain object using the given spec. A
31
- * polymorphic spec first chooses the derived contract and writes its tag
32
- * before every property (FR-005); the chosen contract is never dispatched
33
- * again (FR-006).
34
- */
35
- export declare function serializeWithSpec(value: unknown, spec: TypeSpec, customConverters?: readonly JsonConverter[]): Record<string, unknown>;
36
- /**
37
- * Deserialize unknown data (from JSON.parse) into a typed instance using the
38
- * spec. A polymorphic spec reads the derived contract its tag selects
39
- * (FR-007). `treeNumbers` says how `data` holds its numbers; a root number
40
- * leaf reads as the number it is, which no contract accepts.
41
- */
42
- export declare function deserializeWithSpec<T>(data: unknown, spec: TypeSpec<T>, customConverters?: readonly JsonConverter[], treeNumbers?: TreeNumbers): T;
43
- /**
44
- * Serializes a non-object root through its descriptor, exactly as a property
45
- * of that type would be (custom converters still match by kind).
46
- */
47
- export declare function serializeWithValueSpec(value: unknown, spec: ValueSpec, customConverters?: readonly JsonConverter[]): unknown;
48
- /**
49
- * Deserializes a non-object root through its descriptor, under the spec's
50
- * read options. `treeNumbers` says how `data` holds its numbers.
51
- */
52
- export declare function deserializeWithValueSpec(data: unknown, spec: ValueSpec, customConverters?: readonly JsonConverter[], treeNumbers?: TreeNumbers): unknown;
1
+ import type { TypeDescriptor, JsonReadOptions } from "./types.ts";
2
+ import type { ValueConverter } from "./value-converter.ts";
3
+ import { type ErrorTypeName } from "./numeric-converters.ts";
4
+ import type { SpecPlans } from "./spec-plans.ts";
5
+ /**
6
+ * Resolves the serialize/deserialize pair for a given type descriptor, checking
7
+ * the custom converters of `plans` first (user overrides), then falling back to
8
+ * built-in ones. `readOptions` are the read options of the spec being read
9
+ * (FR-048); a `ref` reads with its target spec's own options. `errorTypeName`
10
+ * names the type a built-in conversion error reports: a property names the
11
+ * declaring contract, every other position names the value's own CLR type
12
+ * (#485). Under exact tree numbers, only the built-in converters that read a
13
+ * number's exact text see a number leaf (`withNumberTextsAsDoubles`).
14
+ */
15
+ export declare function resolveConverter(descriptor: TypeDescriptor, plans: SpecPlans, readOptions?: JsonReadOptions, errorTypeName?: ErrorTypeName): ValueConverter;
@@ -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";