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
@@ -0,0 +1,524 @@
1
+ /**
2
+ * The spec plans (#456, split out by #462): each contract's wire properties
3
+ * and converters compiled once per set of custom converters and kind of tree
4
+ * numbers, and the `serializeWithSpec` / `deserializeWithSpec` /
5
+ * `*WithValueSpec` entry points that run them. Converters receive the plans
6
+ * as their context (`converters.ts` imports only their type), so the two
7
+ * modules import each other in one direction at run time.
8
+ */
9
+ import type {
10
+ TypeSpec,
11
+ PropertySpec,
12
+ JsonConverter,
13
+ PolymorphismSpec,
14
+ TypeDiscriminator,
15
+ ValueSpec,
16
+ } from "./types.ts";
17
+ import type { ValueConverter } from "./value-converter.ts";
18
+ // Only the contract walks (the hot path: one container per object) open and
19
+ // close containers with enter/exit; the collection converters keep the
20
+ // closure-based `readContainer` / `writeContainer` (#456).
21
+ import { enterReadContainer, enterWriteContainer, exitContainer } from "./container-depth.ts";
22
+ import { cannotConvertTo, contractNameOf } from "./contract-name.ts";
23
+ import { valueTypeNameOf } from "./null-reads.ts";
24
+ import { type ConverterSetCache, createConverterSetCache } from "./converter-set-cache.ts";
25
+ import { JsonException } from "./errors.ts";
26
+ import { numberOfTreeValue } from "./exact-json-number.ts";
27
+ import type { ErrorTypeName } from "./numeric-converters.ts";
28
+ import {
29
+ hasTaggedRegistration,
30
+ resolveDeserializeTarget,
31
+ resolveSerializeTarget,
32
+ } from "./polymorphism.ts";
33
+ import { type PropertyLookup, propertyLookupPlanOf } from "./property-lookup.ts";
34
+ import { resolveConverter } from "./converters.ts";
35
+
36
+ // ─── Core serialize/deserialize by spec ──────────────────────────────────────
37
+
38
+ /**
39
+ * Collects all properties from a spec chain, walking the base hierarchy.
40
+ * Base properties come first, own properties last: the declaration order a
41
+ * factory reads, **not** the wire order (see `collectWireProperties`). An
42
+ * override appears once per spec that declares it.
43
+ */
44
+ export function collectProperties(spec: TypeSpec): readonly PropertySpec[] {
45
+ const base = spec.base ? collectProperties(spec.base) : [];
46
+ return [...base, ...spec.properties];
47
+ }
48
+
49
+ /**
50
+ * The properties a spec writes and reads, in System.Text.Json's wire order
51
+ * (FR-009): the spec's own properties, then its base's, recursively. A JSON
52
+ * name appears once, from its most-derived declaration, and a base
53
+ * declaration whose `ts` name a more-derived spec lists in
54
+ * `ignoredProperties` (a `[JsonIgnore]` override) is left out. When any
55
+ * property has an `order` (`[JsonPropertyOrder]`), the list is then sorted by
56
+ * it, stably, across the whole chain (measured: `{"Der2":20,"Base3":3,"Der1":10,
57
+ * "Base1":1,"Der3":30,"Base2":2}` for orders -5, -5, 0, 0, 1, 5).
58
+ */
59
+ export function collectWireProperties(spec: TypeSpec): readonly PropertySpec[] {
60
+ const wire: PropertySpec[] = [];
61
+ const writtenNames = new Set<string>();
62
+ const ignoredNames = new Set<string>();
63
+
64
+ for (const contract of specChainOf(spec)) {
65
+ const visible = contract.properties.filter(
66
+ (property) => !ignoredNames.has(property.ts) && !writtenNames.has(property.json),
67
+ );
68
+
69
+ for (const property of visible) {
70
+ writtenNames.add(property.json);
71
+ wire.push(property);
72
+ }
73
+
74
+ for (const name of contract.ignoredProperties ?? []) {
75
+ ignoredNames.add(name);
76
+ }
77
+ }
78
+
79
+ return wire.some(hasExplicitOrder) ? wire.sort(byPropertyOrder) : wire;
80
+ }
81
+
82
+ function hasExplicitOrder(property: PropertySpec): boolean {
83
+ return property.order !== undefined;
84
+ }
85
+
86
+ function byPropertyOrder(left: PropertySpec, right: PropertySpec): number {
87
+ return (left.order ?? 0) - (right.order ?? 0);
88
+ }
89
+
90
+ /** The spec and its bases, most-derived first. */
91
+ function* specChainOf(spec: TypeSpec): Generator<TypeSpec> {
92
+ yield spec;
93
+
94
+ if (spec.base) {
95
+ yield* specChainOf(spec.base);
96
+ }
97
+ }
98
+
99
+ // ─── Spec plans ──────────────────────────────────────────────────────────────
100
+
101
+ /**
102
+ * Everything the reads and writes of one spec share, compiled on its first
103
+ * use (#456): the wire properties (`collectWireProperties`, with ignored
104
+ * overrides), their converters resolved under the spec's read options
105
+ * (numbers from strings included), and the case-insensitive key index. A
106
+ * polymorphic base dispatches per value through its own cached dispatch
107
+ * index (`polymorphism.ts`), then runs the chosen contract's plan.
108
+ *
109
+ * Writes use the converters resolved for reads: read options never change
110
+ * how a value is written (FR-048 item 5).
111
+ */
112
+ export interface SpecPlan {
113
+ /** Writes through the spec, dispatching a polymorphic base (FR-005, FR-006). */
114
+ readonly serialize: (value: unknown) => Record<string, unknown>;
115
+ /** Reads through the spec, dispatching a polymorphic base (FR-007). */
116
+ readonly deserialize: (data: unknown) => unknown;
117
+ /** Writes `value` with exactly the spec's properties, after the tag when one is given. */
118
+ readonly writeContract: (value: unknown, typeMetadata?: TypeMetadata) => Record<string, unknown>;
119
+ /**
120
+ * Reads `raw` with exactly the spec's properties and builds it with the
121
+ * spec's factory. `metadataKey` is the discriminator a polymorphic read
122
+ * consumed.
123
+ */
124
+ readonly readContract: (raw: Record<string, unknown>, metadataKey?: string) => unknown;
125
+ }
126
+
127
+ /**
128
+ * One property of a plan, with its resolved converter, and whether the
129
+ * contract sets it after construction only when the payload carries it
130
+ * (`TypeSpec.assignIfPresent`).
131
+ */
132
+ interface PropertyPlan {
133
+ readonly property: PropertySpec;
134
+ readonly converter: ValueConverter;
135
+ readonly assignIfPresent: boolean;
136
+ }
137
+
138
+ /**
139
+ * How the tree being read holds its numbers: `parsed`, each a `number`, as
140
+ * `JSON.parse` builds it; `exact`, some as leaves, as `readJsonText` builds
141
+ * it (#457): a `JsonNumberText` for those with more significant digits than
142
+ * a double holds and, for a spec that reads a 64-bit integer, a
143
+ * `JsonNonIntegerNumber` for the other ones with a fraction or an exponent
144
+ * (`NumberTextLeaves`).
145
+ */
146
+ export type TreeNumbers = "parsed" | "exact";
147
+
148
+ /**
149
+ * The plans compiled under one set of custom converters for one kind of
150
+ * tree numbers, each built once.
151
+ */
152
+ export interface SpecPlans {
153
+ readonly customConverters: readonly JsonConverter[];
154
+ readonly treeNumbers: TreeNumbers;
155
+ planOf(spec: TypeSpec): SpecPlan;
156
+ valueConverterOf(spec: ValueSpec): ValueConverter;
157
+ }
158
+
159
+ /**
160
+ * The plans of every custom-converter set, per kind of tree numbers. A plan
161
+ * holds converters resolved against its set, so the set is part of the key:
162
+ * plans are cached per spec inside each set's entry
163
+ * (`converter-set-cache.ts`). Only `deserializeText` reads exact trees, so
164
+ * the `exact` plans exist only for the specs it reads that way.
165
+ */
166
+ const specPlansByTreeNumbers: Readonly<Record<TreeNumbers, ConverterSetCache<SpecPlans>>> = {
167
+ parsed: /* @__PURE__ */ createConverterSetCache((converters) =>
168
+ createSpecPlans(converters, "parsed"),
169
+ ),
170
+ exact: /* @__PURE__ */ createConverterSetCache((converters) =>
171
+ createSpecPlans(converters, "exact"),
172
+ ),
173
+ };
174
+
175
+ function specPlansFor(
176
+ customConverters: readonly JsonConverter[] | undefined,
177
+ treeNumbers: TreeNumbers = "parsed",
178
+ ): SpecPlans {
179
+ return specPlansByTreeNumbers[treeNumbers].entryFor(customConverters);
180
+ }
181
+
182
+ function createSpecPlans(
183
+ customConverters: readonly JsonConverter[],
184
+ treeNumbers: TreeNumbers,
185
+ ): SpecPlans {
186
+ const specPlans = new WeakMap<TypeSpec, SpecPlan>();
187
+ const valueConverters = new WeakMap<ValueSpec, ValueConverter>();
188
+
189
+ const plans: SpecPlans = {
190
+ customConverters,
191
+ treeNumbers,
192
+ planOf: (spec) => cachedIn(specPlans, spec, () => compileSpecPlan(spec, plans)),
193
+ valueConverterOf: (spec) =>
194
+ cachedIn(valueConverters, spec, () =>
195
+ resolveConverter(spec.descriptor, plans, spec.readOptions),
196
+ ),
197
+ };
198
+
199
+ return plans;
200
+ }
201
+
202
+ /**
203
+ * How a property's conversion error names the declaring contract, as
204
+ * System.Text.Json does (#485): `{"At":"03:04:60"}` on a `HolderTimeOnly`
205
+ * names `HolderTimeOnly`, while a value root or an element names the
206
+ * temporal type itself.
207
+ */
208
+ function contractErrorNameOf(spec: TypeSpec): ErrorTypeName {
209
+ return () => contractNameOf(spec);
210
+ }
211
+
212
+ /**
213
+ * Compiles `spec` without calling into it: nested specs and derived
214
+ * contracts are resolved when a value first reaches them, so the plan of a
215
+ * recursive spec never compiles itself.
216
+ *
217
+ * Every property's converter is resolved here, on the spec's first use, so a
218
+ * malformed descriptor (a hand-written spec error) fails then, even when the
219
+ * value lacks that property.
220
+ */
221
+ function compileSpecPlan(spec: TypeSpec, plans: SpecPlans): SpecPlan {
222
+ const properties = collectWireProperties(spec);
223
+
224
+ const assignedIfPresent = new Set(spec.assignIfPresent);
225
+
226
+ const propertyPlans = properties.map<PropertyPlan>((property) => ({
227
+ property,
228
+ converter: resolveConverter(property.type, plans, spec.readOptions, contractErrorNameOf(spec)),
229
+ assignIfPresent: assignedIfPresent.has(property.ts),
230
+ }));
231
+
232
+ const writeContract = contractWriterOf(propertyPlans);
233
+ const readContract = contractReaderOf(spec, propertyPlans);
234
+ const { polymorphism } = spec;
235
+
236
+ if (!polymorphism) {
237
+ return {
238
+ serialize: (value) => writeContract(value),
239
+ deserialize: (data) => readContract(requireJsonObject(data, spec)),
240
+ writeContract,
241
+ readContract,
242
+ };
243
+ }
244
+
245
+ return {
246
+ serialize: (value) => serializePolymorphic(value, spec, polymorphism, plans),
247
+ deserialize: (data) => deserializePolymorphic(data, spec, polymorphism, plans),
248
+ writeContract,
249
+ readContract,
250
+ };
251
+ }
252
+
253
+ /**
254
+ * Serialize a TS object to a JSON-safe plain object using the given spec. A
255
+ * polymorphic spec first chooses the derived contract and writes its tag
256
+ * before every property (FR-005); the chosen contract is never dispatched
257
+ * again (FR-006).
258
+ */
259
+ export function serializeWithSpec(
260
+ value: unknown,
261
+ spec: TypeSpec,
262
+ customConverters?: readonly JsonConverter[],
263
+ ): Record<string, unknown> {
264
+ return specPlansFor(customConverters).planOf(spec).serialize(value);
265
+ }
266
+
267
+ function serializePolymorphic(
268
+ value: unknown,
269
+ spec: TypeSpec,
270
+ polymorphism: PolymorphismSpec,
271
+ plans: SpecPlans,
272
+ ): Record<string, unknown> {
273
+ const target = resolveSerializeTarget(value, spec, polymorphism);
274
+
275
+ const typeMetadata =
276
+ target.tag === undefined ? undefined : { name: polymorphism.discriminator, tag: target.tag };
277
+
278
+ return plans.planOf(target.spec).writeContract(value, typeMetadata);
279
+ }
280
+
281
+ /** The type discriminator a polymorphic write puts first. */
282
+ interface TypeMetadata {
283
+ readonly name: string;
284
+ readonly tag: TypeDiscriminator;
285
+ }
286
+
287
+ /** Writes a value with exactly the given properties, after the tag when one is given. */
288
+ function contractWriterOf(propertyPlans: readonly PropertyPlan[]): SpecPlan["writeContract"] {
289
+ const writeProperties = propertyWriterOf(propertyPlans);
290
+
291
+ return (value, typeMetadata) => {
292
+ enterWriteContainer();
293
+
294
+ try {
295
+ const result: Record<string, unknown> = {};
296
+
297
+ if (typeMetadata) {
298
+ result[typeMetadata.name] = typeMetadata.tag;
299
+ }
300
+
301
+ writeProperties(value as Record<string, unknown>, result);
302
+
303
+ return result;
304
+ } finally {
305
+ exitContainer();
306
+ }
307
+ };
308
+ }
309
+
310
+ /** Writes every property of `source` into `result`, in wire order. */
311
+ function propertyWriterOf(
312
+ propertyPlans: readonly PropertyPlan[],
313
+ ): (source: Record<string, unknown>, result: Record<string, unknown>) => void {
314
+ return (source, result) => {
315
+ for (const { property, converter } of propertyPlans) {
316
+ const tsValue = source[property.ts];
317
+
318
+ if (tsValue == null && property.omitWhenNull) {
319
+ continue;
320
+ }
321
+
322
+ if (tsValue == null && property.optional) {
323
+ result[property.json] = null;
324
+ continue;
325
+ }
326
+
327
+ result[property.json] = converter.serialize(tsValue);
328
+ }
329
+ };
330
+ }
331
+
332
+ /**
333
+ * Deserialize unknown data (from JSON.parse) into a typed instance using the
334
+ * spec. A polymorphic spec reads the derived contract its tag selects
335
+ * (FR-007). `treeNumbers` says how `data` holds its numbers; a root number
336
+ * leaf reads as the number it is, which no contract accepts.
337
+ */
338
+ export function deserializeWithSpec<T>(
339
+ data: unknown,
340
+ spec: TypeSpec<T>,
341
+ customConverters?: readonly JsonConverter[],
342
+ treeNumbers: TreeNumbers = "parsed",
343
+ ): T {
344
+ const plan = specPlansFor(customConverters, treeNumbers).planOf(spec);
345
+ const root = treeNumbers === "exact" ? numberOfTreeValue(data) : data;
346
+
347
+ // The plan reads `spec` or one of its registered derived contracts, so it builds a `T`.
348
+ return plan.deserialize(root) as T;
349
+ }
350
+
351
+ function deserializePolymorphic(
352
+ data: unknown,
353
+ spec: TypeSpec,
354
+ polymorphism: PolymorphismSpec,
355
+ plans: SpecPlans,
356
+ ): unknown {
357
+ const raw = requireJsonObject(data, spec);
358
+ const target = resolveDeserializeTarget(raw, spec, polymorphism);
359
+ const metadataKey = consumedMetadataKeyOf(polymorphism);
360
+
361
+ return plans.planOf(target).readContract(raw, metadataKey);
362
+ }
363
+
364
+ /**
365
+ * The discriminator a polymorphic read consumes as metadata, never as a
366
+ * property; none for a hierarchy without tags, which reads like a
367
+ * non-polymorphic contract.
368
+ */
369
+ function consumedMetadataKeyOf(polymorphism: PolymorphismSpec): string | undefined {
370
+ return hasTaggedRegistration(polymorphism) ? polymorphism.discriminator : undefined;
371
+ }
372
+
373
+ /** `data` as a JSON object; any other JSON value cannot be converted to the contract. */
374
+ function requireJsonObject(data: unknown, spec: TypeSpec): Record<string, unknown> {
375
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
376
+ throw cannotConvertTo(spec);
377
+ }
378
+
379
+ return data as Record<string, unknown>;
380
+ }
381
+
382
+ /**
383
+ * Reads a JSON object with exactly the given properties of `spec` and builds
384
+ * it with `spec`'s factory, under `spec`'s read options.
385
+ */
386
+ function contractReaderOf(
387
+ spec: TypeSpec,
388
+ propertyPlans: readonly PropertyPlan[],
389
+ ): SpecPlan["readContract"] {
390
+ const properties = propertyPlans.map(({ property }) => property);
391
+ const lookupPlan = propertyLookupPlanOf(properties, spec.readOptions);
392
+ const readProperties = propertyReaderOf(spec, propertyPlans);
393
+ const assignPresentMembers = presentMemberAssignerOf(propertyPlans);
394
+
395
+ return (raw, metadataKey) => {
396
+ enterReadContainer("object");
397
+
398
+ try {
399
+ const deserialized = readProperties(lookupPlan(raw, metadataKey));
400
+
401
+ return assignPresentMembers(spec.factory(deserialized), deserialized);
402
+ } finally {
403
+ exitContainer();
404
+ }
405
+ };
406
+ }
407
+
408
+ /**
409
+ * Sets every member of the contract's `assignIfPresent` list the payload
410
+ * carried on the constructed value, in wire order (System.Text.Json follows
411
+ * the payload's order; the order only shows through setter side effects).
412
+ */
413
+ function presentMemberAssignerOf(
414
+ propertyPlans: readonly PropertyPlan[],
415
+ ): (value: unknown, deserialized: Record<string, unknown>) => unknown {
416
+ const names = propertyPlans
417
+ .filter(({ assignIfPresent }) => assignIfPresent)
418
+ .map(({ property }) => property.ts);
419
+
420
+ if (names.length === 0) {
421
+ return (value) => value;
422
+ }
423
+
424
+ return (value, deserialized) => {
425
+ const target = value as Record<string, unknown>;
426
+
427
+ for (const name of names) {
428
+ if (name in deserialized) {
429
+ target[name] = deserialized[name];
430
+ }
431
+ }
432
+
433
+ return value;
434
+ };
435
+ }
436
+
437
+ /**
438
+ * Reads every property through `jsonValueOf` into the factory's input. An
439
+ * absent (missing or `null`) optional property reads as `null`; a missing
440
+ * required one throws; a missing one of the contract's `assignIfPresent`
441
+ * list is left out; a `null` on a non-nullable value-type property throws
442
+ * naming the declaring contract, as System.Text.Json does (#471).
443
+ */
444
+ function propertyReaderOf(
445
+ spec: TypeSpec,
446
+ propertyPlans: readonly PropertyPlan[],
447
+ ): (jsonValueOf: PropertyLookup) => Record<string, unknown> {
448
+ return (jsonValueOf) => {
449
+ const deserialized: Record<string, unknown> = {};
450
+
451
+ for (const { property, converter, assignIfPresent } of propertyPlans) {
452
+ const jsonValue = jsonValueOf(property);
453
+
454
+ if (jsonValue === undefined && assignIfPresent) {
455
+ continue;
456
+ }
457
+
458
+ const isAbsent = jsonValue == null;
459
+
460
+ if (isAbsent && property.optional) {
461
+ deserialized[property.ts] = null;
462
+ continue;
463
+ }
464
+
465
+ if (
466
+ jsonValue === null &&
467
+ !property.optional &&
468
+ valueTypeNameOf(property.type) !== undefined
469
+ ) {
470
+ throw cannotConvertTo(spec);
471
+ }
472
+
473
+ if (jsonValue === undefined) {
474
+ throw new JsonException(`Missing required property: "${property.json}"`);
475
+ }
476
+
477
+ deserialized[property.ts] = converter.deserialize(jsonValue);
478
+ }
479
+
480
+ return deserialized;
481
+ };
482
+ }
483
+
484
+ // ─── Value specs ─────────────────────────────────────────────────────────────
485
+
486
+ /**
487
+ * Serializes a non-object root through its descriptor, exactly as a property
488
+ * of that type would be (custom converters still match by kind).
489
+ */
490
+ export function serializeWithValueSpec(
491
+ value: unknown,
492
+ spec: ValueSpec,
493
+ customConverters?: readonly JsonConverter[],
494
+ ): unknown {
495
+ return specPlansFor(customConverters).valueConverterOf(spec).serialize(value);
496
+ }
497
+
498
+ /**
499
+ * Deserializes a non-object root through its descriptor, under the spec's
500
+ * read options. `treeNumbers` says how `data` holds its numbers.
501
+ */
502
+ export function deserializeWithValueSpec(
503
+ data: unknown,
504
+ spec: ValueSpec,
505
+ customConverters?: readonly JsonConverter[],
506
+ treeNumbers: TreeNumbers = "parsed",
507
+ ): unknown {
508
+ return specPlansFor(customConverters, treeNumbers).valueConverterOf(spec).deserialize(data);
509
+ }
510
+
511
+ // ─── Memoization ─────────────────────────────────────────────────────────────
512
+
513
+ function cachedIn<K extends object, V>(cache: WeakMap<K, V>, key: K, build: () => V): V {
514
+ const cached = cache.get(key);
515
+
516
+ if (cached !== undefined) {
517
+ return cached;
518
+ }
519
+
520
+ const built = build();
521
+ cache.set(key, built);
522
+
523
+ return built;
524
+ }
@@ -55,9 +55,8 @@ export type PrimitiveDescriptor = WithClrTypeName & {
55
55
  * conversion errors and decides the signedness of the integer grammars.
56
56
  * A `[Branded]` type over a 64-bit integer adds its companion `create`
57
57
  * factory (the valid `[JsonFactory]` member when one exists) and `typeName`,
58
- * which the read applies after the exact digit, as the branded descriptor
59
- * does. FR-050 does not describe that factory case; the review of slice
60
- * 012e (#450) added it.
58
+ * which the read applies after the exact digits, as the branded descriptor
59
+ * does (added by the review of slice 012e, #450).
61
60
  */
62
61
  export type Int64Descriptor = {
63
62
  readonly kind: "int64";
@@ -134,6 +133,11 @@ export type SequenceCollectionDescriptor = {
134
133
  | "sortedSet";
135
134
  readonly element: TypeDescriptor;
136
135
  readonly create: (items: unknown[]) => Iterable<unknown>;
136
+ /**
137
+ * The CLR name of a value-type collection (`ImmutableArray<T>`), whose
138
+ * JSON `null` throws naming it, as System.Text.Json does (#713).
139
+ */
140
+ readonly typeName?: string;
137
141
  };
138
142
 
139
143
  /**
@@ -192,10 +196,11 @@ export type EnumDescriptor = WithClrTypeName & {
192
196
  export type NumericEnumDescriptor = WithClrTypeName & {
193
197
  readonly kind: "numericEnum";
194
198
  /**
195
- * The enum's underlying integer type, set on a dictionary key: an integer
196
- * key name is range-checked by it (#479). `System.Int32` when absent. A
197
- * 64-bit enum (`System.Int64` / `System.UInt64`) names it in every slot:
198
- * its values are `bigint`s, read and written through the int64 path (#701).
199
+ * The enum's underlying integer type, `System.Int32` when absent. A value
200
+ * read and an integer key name are range-checked by it (#369, #479); the
201
+ * generator names it in every slot for any type but `int`, and on a
202
+ * dictionary key always. A 64-bit enum (`System.Int64` / `System.UInt64`)
203
+ * holds `bigint`s, read and written through the int64 path (#701).
199
204
  */
200
205
  readonly numberType?: IntegerTypeName;
201
206
  readonly values: Record<string, string | number | bigint>;
@@ -299,8 +304,9 @@ export interface TypeSpec<T = unknown> {
299
304
  /**
300
305
  * The CLR name System.Text.Json prints for this struct contract
301
306
  * (`MyApp.SPoint`, `MyApp.Outer+Inner`, ``MyApp.Pair`1[System.Int32]``);
302
- * the generator emits it next to `valueType`. Errors name the constructor
303
- * without it.
307
+ * the generator emits it next to `valueType`, and on a non-polymorphic
308
+ * `[PlainObject]` contract, which has no constructor to name (#512).
309
+ * Errors name the constructor without it.
304
310
  */
305
311
  readonly typeName?: string;
306
312
  /** The context's read behavior; absent when it is System.Text.Json's default. */
@@ -0,0 +1,62 @@
1
+ import { InvalidOperationException } from "./exceptions/index.ts";
2
+
3
+ type LazyState<T> =
4
+ | { readonly kind: "pending"; readonly factory: () => T }
5
+ | { readonly kind: "running" }
6
+ | { readonly kind: "created"; readonly value: T }
7
+ | { readonly kind: "failed"; readonly error: unknown };
8
+
9
+ /**
10
+ * `System.Lazy<T>` with a factory: the factory runs on the first read of `value`, once. A
11
+ * factory that throws throws the same exception on every later read (the default
12
+ * `ExecutionAndPublication` mode caches it), and one that reads `value` itself throws
13
+ * `InvalidOperationException`.
14
+ */
15
+ export class Lazy<T> {
16
+ private state: LazyState<T>;
17
+
18
+ constructor(factory: () => T) {
19
+ this.state = { kind: "pending", factory };
20
+ }
21
+
22
+ /** `Lazy<T>.IsValueCreated`: `true` once the factory returned. */
23
+ get isValueCreated(): boolean {
24
+ return this.state.kind === "created";
25
+ }
26
+
27
+ /** `Lazy<T>.Value`. */
28
+ get value(): T {
29
+ const state = this.state;
30
+
31
+ if (state.kind === "created") {
32
+ return state.value;
33
+ }
34
+
35
+ if (state.kind === "failed") {
36
+ throw state.error;
37
+ }
38
+
39
+ if (state.kind === "running") {
40
+ throw new InvalidOperationException(
41
+ "ValueFactory attempted to access the Value property of this instance.",
42
+ );
43
+ }
44
+
45
+ return this.create(state.factory);
46
+ }
47
+
48
+ private create(factory: () => T): T {
49
+ this.state = { kind: "running" };
50
+
51
+ try {
52
+ const value = factory();
53
+
54
+ this.state = { kind: "created", value };
55
+
56
+ return value;
57
+ } catch (error) {
58
+ this.state = { kind: "failed", error };
59
+ throw error;
60
+ }
61
+ }
62
+ }