metano-runtime 3.0.2 → 3.2.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 (185) hide show
  1. package/dist/system/char-members.d.ts +23 -0
  2. package/dist/system/char-members.js +46 -0
  3. package/dist/system/collections/hash-core.d.ts +5 -0
  4. package/dist/system/collections/hash-core.js +24 -0
  5. package/dist/system/collections/helpers.d.ts +16 -3
  6. package/dist/system/collections/helpers.js +28 -2
  7. package/dist/system/collections/immutable-list-builder-core.d.ts +7 -2
  8. package/dist/system/collections/immutable-list-builder-core.js +11 -0
  9. package/dist/system/collections/immutable-list-core.d.ts +8 -0
  10. package/dist/system/collections/immutable-list-core.js +19 -1
  11. package/dist/system/collections/immutable-storage.d.ts +2 -0
  12. package/dist/system/collections/immutable-storage.js +6 -1
  13. package/dist/system/collections/interfaces.d.ts +13 -0
  14. package/dist/system/collections/list.d.ts +3 -0
  15. package/dist/system/collections/list.js +7 -0
  16. package/dist/system/collections/read-only-list.d.ts +11 -0
  17. package/dist/system/collections/read-only-list.js +26 -1
  18. package/dist/system/collections/sorted-list.d.ts +5 -0
  19. package/dist/system/collections/sorted-list.js +12 -1
  20. package/dist/system/comparable-compare-to.d.ts +12 -0
  21. package/dist/system/comparable-compare-to.js +20 -0
  22. package/dist/system/decimal-parsing.d.ts +12 -0
  23. package/dist/system/decimal-parsing.js +86 -0
  24. package/dist/system/exceptions/index.d.ts +1 -0
  25. package/dist/system/exceptions/index.js +1 -0
  26. package/dist/system/exceptions/throw-error.d.ts +7 -0
  27. package/dist/system/exceptions/throw-error.js +9 -0
  28. package/dist/system/hash-code.d.ts +2 -1
  29. package/dist/system/hash-code.js +5 -2
  30. package/dist/system/index.d.ts +3 -0
  31. package/dist/system/index.js +3 -0
  32. package/dist/system/int64-math.js +2 -1
  33. package/dist/system/int64.d.ts +6 -0
  34. package/dist/system/int64.js +18 -9
  35. package/dist/system/integer-division.d.ts +12 -4
  36. package/dist/system/integer-division.js +19 -2
  37. package/dist/system/json/index.d.ts +1 -1
  38. package/dist/system/json/json-serializer.d.ts +12 -1
  39. package/dist/system/json/json-serializer.js +29 -0
  40. package/dist/system/json/json-text-writer.d.ts +24 -0
  41. package/dist/system/json/json-text-writer.js +207 -0
  42. package/dist/system/json/number-from-string.js +20 -6
  43. package/dist/system/json/numeric-converters.js +41 -0
  44. package/dist/system/json/ordinal-ignore-case.d.ts +2 -0
  45. package/dist/system/json/ordinal-ignore-case.js +1 -1
  46. package/dist/system/json/serializer-context.d.ts +13 -7
  47. package/dist/system/json/serializer-context.js +23 -11
  48. package/dist/system/json/types.d.ts +20 -0
  49. package/dist/system/linq/grouping.d.ts +12 -0
  50. package/dist/system/linq/grouping.js +42 -0
  51. package/dist/system/linq/index.d.ts +4 -3
  52. package/dist/system/linq/index.js +3 -2
  53. package/dist/system/linq/linq.js +20 -1
  54. package/dist/system/linq/lookup.d.ts +17 -0
  55. package/dist/system/linq/lookup.js +20 -0
  56. package/dist/system/linq/operators.d.ts +12 -4
  57. package/dist/system/linq/operators.js +61 -15
  58. package/dist/system/linq/terminals.d.ts +29 -2
  59. package/dist/system/linq/terminals.js +71 -3
  60. package/dist/system/linq/types.d.ts +27 -4
  61. package/dist/system/math.d.ts +27 -0
  62. package/dist/system/math.js +45 -0
  63. package/dist/system/min-max.d.ts +6 -0
  64. package/dist/system/min-max.js +10 -0
  65. package/dist/system/number-parsing.d.ts +16 -4
  66. package/dist/system/number-parsing.js +21 -4
  67. package/dist/system/string-comparison.d.ts +56 -0
  68. package/dist/system/string-comparison.js +225 -0
  69. package/dist/system/string-hash-code.d.ts +14 -0
  70. package/dist/system/string-hash-code.js +37 -0
  71. package/dist/system/string-members.d.ts +5 -4
  72. package/dist/system/string-members.js +12 -11
  73. package/dist-unchecked/system/char-members.d.ts +23 -0
  74. package/dist-unchecked/system/char-members.js +46 -0
  75. package/dist-unchecked/system/collections/hash-core.d.ts +5 -0
  76. package/dist-unchecked/system/collections/hash-core.js +24 -0
  77. package/dist-unchecked/system/collections/helpers.d.ts +16 -3
  78. package/dist-unchecked/system/collections/helpers.js +28 -2
  79. package/dist-unchecked/system/collections/immutable-list-builder-core.d.ts +7 -2
  80. package/dist-unchecked/system/collections/immutable-list-builder-core.js +11 -0
  81. package/dist-unchecked/system/collections/immutable-list-core.d.ts +8 -0
  82. package/dist-unchecked/system/collections/immutable-list-core.js +19 -1
  83. package/dist-unchecked/system/collections/immutable-storage.d.ts +2 -0
  84. package/dist-unchecked/system/collections/immutable-storage.js +6 -1
  85. package/dist-unchecked/system/collections/interfaces.d.ts +13 -0
  86. package/dist-unchecked/system/collections/list.d.ts +3 -0
  87. package/dist-unchecked/system/collections/list.js +7 -0
  88. package/dist-unchecked/system/collections/read-only-list.d.ts +11 -0
  89. package/dist-unchecked/system/collections/read-only-list.js +26 -1
  90. package/dist-unchecked/system/collections/sorted-list.d.ts +5 -0
  91. package/dist-unchecked/system/collections/sorted-list.js +12 -1
  92. package/dist-unchecked/system/comparable-compare-to.d.ts +12 -0
  93. package/dist-unchecked/system/comparable-compare-to.js +20 -0
  94. package/dist-unchecked/system/decimal-parsing.d.ts +12 -0
  95. package/dist-unchecked/system/decimal-parsing.js +86 -0
  96. package/dist-unchecked/system/exceptions/index.d.ts +1 -0
  97. package/dist-unchecked/system/exceptions/index.js +1 -0
  98. package/dist-unchecked/system/exceptions/throw-error.d.ts +7 -0
  99. package/dist-unchecked/system/exceptions/throw-error.js +9 -0
  100. package/dist-unchecked/system/hash-code.d.ts +2 -1
  101. package/dist-unchecked/system/hash-code.js +5 -2
  102. package/dist-unchecked/system/index.d.ts +3 -0
  103. package/dist-unchecked/system/index.js +3 -0
  104. package/dist-unchecked/system/int64-math.js +2 -1
  105. package/dist-unchecked/system/int64.d.ts +6 -0
  106. package/dist-unchecked/system/int64.js +18 -9
  107. package/dist-unchecked/system/integer-division.d.ts +12 -4
  108. package/dist-unchecked/system/integer-division.js +19 -2
  109. package/dist-unchecked/system/json/index.d.ts +1 -1
  110. package/dist-unchecked/system/json/json-serializer.d.ts +12 -1
  111. package/dist-unchecked/system/json/json-serializer.js +29 -0
  112. package/dist-unchecked/system/json/json-text-writer.d.ts +24 -0
  113. package/dist-unchecked/system/json/json-text-writer.js +207 -0
  114. package/dist-unchecked/system/json/number-from-string.js +20 -6
  115. package/dist-unchecked/system/json/numeric-converters.js +41 -0
  116. package/dist-unchecked/system/json/ordinal-ignore-case.d.ts +2 -0
  117. package/dist-unchecked/system/json/ordinal-ignore-case.js +1 -1
  118. package/dist-unchecked/system/json/serializer-context.d.ts +13 -7
  119. package/dist-unchecked/system/json/serializer-context.js +23 -11
  120. package/dist-unchecked/system/json/types.d.ts +20 -0
  121. package/dist-unchecked/system/linq/grouping.d.ts +12 -0
  122. package/dist-unchecked/system/linq/grouping.js +42 -0
  123. package/dist-unchecked/system/linq/index.d.ts +4 -3
  124. package/dist-unchecked/system/linq/index.js +3 -2
  125. package/dist-unchecked/system/linq/linq.js +20 -1
  126. package/dist-unchecked/system/linq/lookup.d.ts +17 -0
  127. package/dist-unchecked/system/linq/lookup.js +20 -0
  128. package/dist-unchecked/system/linq/operators.d.ts +12 -4
  129. package/dist-unchecked/system/linq/operators.js +61 -15
  130. package/dist-unchecked/system/linq/terminals.d.ts +29 -2
  131. package/dist-unchecked/system/linq/terminals.js +71 -3
  132. package/dist-unchecked/system/linq/types.d.ts +27 -4
  133. package/dist-unchecked/system/math.d.ts +27 -0
  134. package/dist-unchecked/system/math.js +45 -0
  135. package/dist-unchecked/system/min-max.d.ts +6 -0
  136. package/dist-unchecked/system/min-max.js +10 -0
  137. package/dist-unchecked/system/number-parsing.d.ts +16 -4
  138. package/dist-unchecked/system/number-parsing.js +21 -4
  139. package/dist-unchecked/system/string-comparison.d.ts +56 -0
  140. package/dist-unchecked/system/string-comparison.js +225 -0
  141. package/dist-unchecked/system/string-hash-code.d.ts +14 -0
  142. package/dist-unchecked/system/string-hash-code.js +37 -0
  143. package/dist-unchecked/system/string-members.d.ts +5 -4
  144. package/dist-unchecked/system/string-members.js +12 -11
  145. package/package.json +1 -1
  146. package/src/system/char-members.ts +57 -0
  147. package/src/system/collections/hash-core.ts +31 -0
  148. package/src/system/collections/helpers.ts +39 -4
  149. package/src/system/collections/immutable-list-builder-core.ts +16 -2
  150. package/src/system/collections/immutable-list-core.ts +23 -1
  151. package/src/system/collections/immutable-storage.ts +8 -1
  152. package/src/system/collections/interfaces.ts +16 -0
  153. package/src/system/collections/list.ts +9 -0
  154. package/src/system/collections/read-only-list.ts +35 -1
  155. package/src/system/collections/sorted-list.ts +15 -1
  156. package/src/system/comparable-compare-to.ts +23 -0
  157. package/src/system/decimal-parsing.ts +109 -0
  158. package/src/system/exceptions/index.ts +1 -0
  159. package/src/system/exceptions/throw-error.ts +9 -0
  160. package/src/system/hash-code.ts +7 -2
  161. package/src/system/index.ts +3 -0
  162. package/src/system/int64-math.ts +2 -1
  163. package/src/system/int64.ts +27 -10
  164. package/src/system/integer-division.ts +43 -6
  165. package/src/system/json/index.ts +1 -0
  166. package/src/system/json/json-serializer.ts +42 -0
  167. package/src/system/json/json-text-writer.ts +282 -0
  168. package/src/system/json/number-from-string.ts +26 -6
  169. package/src/system/json/numeric-converters.ts +55 -0
  170. package/src/system/json/ordinal-ignore-case.ts +1 -1
  171. package/src/system/json/serializer-context.ts +28 -11
  172. package/src/system/json/types.ts +21 -0
  173. package/src/system/linq/grouping.ts +77 -0
  174. package/src/system/linq/index.ts +8 -0
  175. package/src/system/linq/linq.ts +23 -1
  176. package/src/system/linq/lookup.ts +34 -0
  177. package/src/system/linq/operators.ts +78 -15
  178. package/src/system/linq/terminals.ts +85 -3
  179. package/src/system/linq/types.ts +32 -0
  180. package/src/system/math.ts +63 -0
  181. package/src/system/min-max.ts +11 -0
  182. package/src/system/number-parsing.ts +24 -4
  183. package/src/system/string-comparison.ts +299 -0
  184. package/src/system/string-hash-code.ts +44 -0
  185. package/src/system/string-members.ts +12 -11
@@ -0,0 +1,207 @@
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, unless the context writes indented text (#752): `writeIndented` puts each
7
+ * array element and each property on its own line, indented by `indentSize` copies of
8
+ * `indentCharacter` per level (a space and 2 by default), with `newLine` (`"\n"` by default)
9
+ * between lines, `": "` after a property name, and `[]` / `{}` for an empty container;
10
+ * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
11
+ * `\r` and `\t` keep their short escapes; every other control character,
12
+ * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
13
+ * printable ASCII is written `\uXXXX` (upper-case hex, one escape per
14
+ * UTF-16 code unit), and a lone surrogate is written `\uFFFD`;
15
+ * - numbers in .NET's shortest round-trip text (`1E+20`, `1E-07`, `-0`),
16
+ * a `JSON.rawJSON` leaf (an exact `decimal` / 64-bit integer) as its text;
17
+ * NaN and the infinities throw `ArgumentException`, as STJ throws for them.
18
+ */
19
+ import { formatDouble } from "../double-format.js";
20
+ import { ArgumentException } from "../exceptions/argument-exception.js";
21
+ import { rawJsonTextOf } from "./exact-json-number.js";
22
+ /** The message STJ throws for a NaN or infinite number written as JSON. */
23
+ const NON_FINITE_NUMBER_MESSAGE = ".NET number values such as positive and negative infinity cannot be written as valid JSON. " +
24
+ "To make it work when using 'JsonSerializer', consider specifying " +
25
+ "'JsonNumberHandling.AllowNamedFloatingPointLiterals' " +
26
+ "(see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).";
27
+ const COMPACT = {
28
+ lineStart: () => "",
29
+ lineEnd: () => "",
30
+ afterColon: "",
31
+ };
32
+ function indentedLayout(options) {
33
+ const unit = (options.indentCharacter ?? " ").repeat(options.indentSize ?? 2);
34
+ const newLine = options.newLine ?? "\n";
35
+ return {
36
+ lineStart: (depth) => newLine + unit.repeat(depth),
37
+ lineEnd: (depth) => newLine + unit.repeat(depth - 1),
38
+ afterColon: " ",
39
+ };
40
+ }
41
+ /**
42
+ * The JSON text of `tree`, as System.Text.Json writes it: compact, or laid out as
43
+ * `options` say (the context's `WriteIndented` family, #752).
44
+ */
45
+ export function writeJsonText(tree, options) {
46
+ const parts = [];
47
+ const layout = options?.writeIndented ? indentedLayout(options) : COMPACT;
48
+ writeValue(tree, parts, layout, 0);
49
+ return parts.join("");
50
+ }
51
+ function writeValue(value, parts, layout, depth) {
52
+ if (value == null) {
53
+ parts.push("null");
54
+ return;
55
+ }
56
+ switch (typeof value) {
57
+ case "string":
58
+ parts.push(quoted(value));
59
+ return;
60
+ case "number":
61
+ parts.push(numberText(value));
62
+ return;
63
+ case "bigint":
64
+ case "boolean":
65
+ parts.push(String(value));
66
+ return;
67
+ }
68
+ writeObject(value, parts, layout, depth);
69
+ }
70
+ function writeObject(value, parts, layout, depth) {
71
+ const rawText = rawJsonTextOf(value);
72
+ if (rawText !== undefined) {
73
+ parts.push(rawText);
74
+ return;
75
+ }
76
+ const toJson = value.toJSON;
77
+ if (typeof toJson === "function") {
78
+ writeValue(toJson.call(value), parts, layout, depth);
79
+ return;
80
+ }
81
+ if (Array.isArray(value)) {
82
+ writeArray(value, parts, layout, depth + 1);
83
+ return;
84
+ }
85
+ writeProperties(value, parts, layout, depth + 1);
86
+ }
87
+ /** `depth` is the nesting level of the array's elements. */
88
+ function writeArray(items, parts, layout, depth) {
89
+ parts.push("[");
90
+ items.forEach((item, index) => {
91
+ if (index > 0) {
92
+ parts.push(",");
93
+ }
94
+ parts.push(layout.lineStart(depth));
95
+ writeValue(item, parts, layout, depth);
96
+ });
97
+ if (items.length > 0) {
98
+ parts.push(layout.lineEnd(depth));
99
+ }
100
+ parts.push("]");
101
+ }
102
+ /**
103
+ * An object's own enumerable properties; an `undefined` one is skipped, as `JSON.stringify`
104
+ * skips it. `depth` is the nesting level of the properties.
105
+ */
106
+ function writeProperties(object, parts, layout, depth) {
107
+ let first = true;
108
+ parts.push("{");
109
+ for (const key of Object.keys(object)) {
110
+ const member = object[key];
111
+ if (member === undefined) {
112
+ continue;
113
+ }
114
+ if (!first) {
115
+ parts.push(",");
116
+ }
117
+ first = false;
118
+ parts.push(layout.lineStart(depth), quoted(key), ":", layout.afterColon);
119
+ writeValue(member, parts, layout, depth);
120
+ }
121
+ if (!first) {
122
+ parts.push(layout.lineEnd(depth));
123
+ }
124
+ parts.push("}");
125
+ }
126
+ function numberText(value) {
127
+ if (!Number.isFinite(value)) {
128
+ throw new ArgumentException(NON_FINITE_NUMBER_MESSAGE);
129
+ }
130
+ return formatDouble(value);
131
+ }
132
+ function quoted(text) {
133
+ for (let index = 0; index < text.length; index++) {
134
+ if (isEscaped(text.charCodeAt(index))) {
135
+ return `"${escaped(text)}"`;
136
+ }
137
+ }
138
+ return `"${text}"`;
139
+ }
140
+ /** Whether `JavaScriptEncoder.Default` escapes the UTF-16 code unit `code`. */
141
+ function isEscaped(code) {
142
+ switch (code) {
143
+ case 0x22: // "
144
+ case 0x26: // &
145
+ case 0x27: // '
146
+ case 0x2b: // +
147
+ case 0x3c: // <
148
+ case 0x3e: // >
149
+ case 0x5c: // backslash
150
+ case 0x60: // `
151
+ return true;
152
+ default:
153
+ return code < 0x20 || code >= 0x7f;
154
+ }
155
+ }
156
+ /** The short escape STJ keeps for `code`, or `undefined`. */
157
+ function shortEscapeOf(code) {
158
+ switch (code) {
159
+ case 0x08:
160
+ return "\\b";
161
+ case 0x09:
162
+ return "\\t";
163
+ case 0x0a:
164
+ return "\\n";
165
+ case 0x0c:
166
+ return "\\f";
167
+ case 0x0d:
168
+ return "\\r";
169
+ case 0x5c:
170
+ return "\\\\";
171
+ default:
172
+ return undefined;
173
+ }
174
+ }
175
+ function escaped(text) {
176
+ let result = "";
177
+ for (let index = 0; index < text.length; index++) {
178
+ const code = text.charCodeAt(index);
179
+ if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
180
+ result += unicodeEscape(code) + unicodeEscape(text.charCodeAt(index + 1));
181
+ index++;
182
+ }
183
+ else {
184
+ result += escapedCodeUnit(code);
185
+ }
186
+ }
187
+ return result;
188
+ }
189
+ function escapedCodeUnit(code) {
190
+ const shortEscape = shortEscapeOf(code);
191
+ if (shortEscape !== undefined) {
192
+ return shortEscape;
193
+ }
194
+ if (isHighSurrogate(code) || isLowSurrogate(code)) {
195
+ return unicodeEscape(0xfffd);
196
+ }
197
+ return isEscaped(code) ? unicodeEscape(code) : String.fromCharCode(code);
198
+ }
199
+ function unicodeEscape(code) {
200
+ return `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`;
201
+ }
202
+ function isHighSurrogate(code) {
203
+ return code >= 0xd800 && code <= 0xdbff;
204
+ }
205
+ function isLowSurrogate(code) {
206
+ return code >= 0xdc00 && code <= 0xdfff;
207
+ }
@@ -75,10 +75,10 @@ function isWithinRange(value, min, max) {
75
75
  }
76
76
  /**
77
77
  * Reads the floating-point grammar; `staysFinite` rejects a value that
78
- * overflows the target type. The value keeps double precision, as a JSON
79
- * number read into a `Single` does.
78
+ * overflows the target type, and `round` brings the double to the target's
79
+ * precision (a `Single` rounds to single precision, #695).
80
80
  */
81
- function floatingPointReader(staysFinite) {
81
+ function floatingPointReader(staysFinite, round) {
82
82
  return (text) => {
83
83
  const literal = FLOATING_POINT_LITERALS.get(text);
84
84
  if (literal !== undefined) {
@@ -89,12 +89,26 @@ function floatingPointReader(staysFinite) {
89
89
  return undefined;
90
90
  }
91
91
  const value = Number(text);
92
- return staysFinite(parts, value) ? value : undefined;
92
+ return staysFinite(parts, value) ? round(value) : undefined;
93
93
  };
94
94
  }
95
95
  function fitsDouble(_, value) {
96
96
  return Number.isFinite(value);
97
97
  }
98
+ /** The largest `Single`, `(2 − 2^-23) × 2^127`. */
99
+ const SINGLE_MAX_VALUE = 3.4028234663852886e38;
100
+ /**
101
+ * A finite double that {@link fitsSingle} accepted, rounded to single
102
+ * precision (#695). Only the threshold double itself would round to an
103
+ * infinity (a tie to even); its text was below the threshold, so it is
104
+ * `±Single.MaxValue`.
105
+ */
106
+ function roundToFiniteSingle(value) {
107
+ const single = Math.fround(value);
108
+ return Number.isFinite(single) || !Number.isFinite(value)
109
+ ? single
110
+ : Math.sign(single) * SINGLE_MAX_VALUE;
111
+ }
98
112
  /**
99
113
  * Whether the text stays below the `Single` overflow threshold. The double
100
114
  * is already rounded, so it decides every case but one: a double equal to
@@ -173,8 +187,8 @@ const INTEGER_TOKEN_READERS = /* @__PURE__ */ lazyValue(() => integerReadersOf((
173
187
  : SIGNED_INTEGER_TOKEN_PATTERN, () => (value) => value));
174
188
  const NUMBER_TEXT_READERS = /* @__PURE__ */ lazyValue(() => ({
175
189
  ...STRICT_INTEGER_READERS(),
176
- "System.Single": floatingPointReader(fitsSingle),
177
- "System.Double": floatingPointReader(fitsDouble),
190
+ "System.Single": floatingPointReader(fitsSingle, roundToFiniteSingle),
191
+ "System.Double": floatingPointReader(fitsDouble, (value) => value),
178
192
  }));
179
193
  /**
180
194
  * The number `text` spells as a `numberType`, or `undefined` when System.Text.Json
@@ -1,3 +1,4 @@
1
+ import { formatSingle } from "../double-format.js";
1
2
  import { JsonException } from "./errors.js";
2
3
  import { isDecimalText, readDecimalText } from "./decimal-text.js";
3
4
  import { exactBigIntLeafOf, exactNumberTextOf, JsonNonIntegerNumber, numberOfTreeValue, writeExactNumber, } from "./exact-json-number.js";
@@ -27,6 +28,8 @@ const passthroughConverter = {
27
28
  };
28
29
  /** The CLR name of a C# `char`, which reads as a one-code-unit `string`. */
29
30
  const CHAR_TYPE_NAME = "System.Char";
31
+ /** The CLR name of a C# `float`, whose values read rounded to single precision. */
32
+ const SINGLE_TYPE_NAME = "System.Single";
30
33
  /**
31
34
  * A `primitive`: values pass through both ways, except that a JSON string
32
35
  * for a numeric `numberType` is read by System.Text.Json's grammar when the
@@ -39,6 +42,9 @@ export function primitiveConverterOf(descriptor, readOptions, errorTypeName = de
39
42
  if (descriptor.typeName === CHAR_TYPE_NAME) {
40
43
  return charConverterOf(errorTypeName);
41
44
  }
45
+ if (numberType === SINGLE_TYPE_NAME) {
46
+ return singleConverterOf(readOptions, errorTypeName);
47
+ }
42
48
  if (numberType === undefined || !readsNumbersFromStrings(readOptions)) {
43
49
  return passthroughConverter;
44
50
  }
@@ -56,6 +62,41 @@ export function primitiveConverterOf(descriptor, readOptions, errorTypeName = de
56
62
  },
57
63
  };
58
64
  }
65
+ /**
66
+ * A `float`: a JSON number reads rounded to single precision, as
67
+ * System.Text.Json parses it into a `Single` (#695), and a string reads
68
+ * through the number grammar (which rounds too) when the context reads
69
+ * numbers from strings. A finite value writes the shortest text that reads
70
+ * back as the same `float`, as System.Text.Json writes it (`0.1`, not the
71
+ * double `0.10000000149011612`), through the exact-number leaf. A
72
+ * non-finite value passes through: System.Text.Json throws for it without
73
+ * `AllowNamedFloatingPointLiterals`, which Metano does not mirror.
74
+ */
75
+ function singleConverterOf(readOptions, errorTypeName) {
76
+ const readsStrings = readsNumbersFromStrings(readOptions);
77
+ return {
78
+ serialize: (value) => typeof value === "number" && Number.isFinite(value)
79
+ ? writeExactNumber(formatSingle(value), () => Math.fround(value))
80
+ : passthroughConverter.serialize(value),
81
+ deserialize: (value) => {
82
+ if (typeof value === "number") {
83
+ return Math.fround(value);
84
+ }
85
+ const exact = exactNumberTextOf(value);
86
+ if (exact !== undefined) {
87
+ return Math.fround(Number(exact));
88
+ }
89
+ if (typeof value !== "string" || !readsStrings) {
90
+ return value;
91
+ }
92
+ const number = readNumberTextAsNumber(value, SINGLE_TYPE_NAME);
93
+ if (number === undefined) {
94
+ throw cannotConvert(SINGLE_TYPE_NAME, errorTypeName);
95
+ }
96
+ return number;
97
+ },
98
+ };
99
+ }
59
100
  /**
60
101
  * A `long` / `ulong` — the `int64` descriptor (spec 012 FR-050), whatever
61
102
  * the read options:
@@ -12,3 +12,5 @@
12
12
  */
13
13
  /** The key under which `name` equals every name that matches it ignoring case. */
14
14
  export declare function ordinalIgnoreCaseKeyOf(name: string): string;
15
+ /** The ordinal uppercase of one code point (`character` may be a surrogate pair). */
16
+ export declare function ordinalUppercaseOf(character: string): string;
@@ -47,7 +47,7 @@ export function ordinalIgnoreCaseKeyOf(name) {
47
47
  return Array.from(name, ordinalUppercaseOf).join("");
48
48
  }
49
49
  /** The ordinal uppercase of one code point (`character` may be a surrogate pair). */
50
- function ordinalUppercaseOf(character) {
50
+ export function ordinalUppercaseOf(character) {
51
51
  const exception = ORDINAL_UPPERCASE_EXCEPTIONS().get(character);
52
52
  if (exception !== undefined) {
53
53
  return exception;
@@ -1,4 +1,4 @@
1
- import type { TypeSpec, ValueSpec, SerializerContextOptions, JsonConverter, JsonReadOptions } from "./types.ts";
1
+ import type { TypeSpec, ValueSpec, SerializerContextOptions, JsonConverter, JsonReadOptions, JsonWriteOptions } from "./types.ts";
2
2
  /**
3
3
  * Base class for generated serializer contexts. Each context holds options
4
4
  * (including custom converters) and a registry of type specs for lookup.
@@ -18,9 +18,15 @@ export declare abstract class SerializerContext {
18
18
  * default.
19
19
  */
20
20
  protected get readOptions(): JsonReadOptions;
21
+ /**
22
+ * The text formatting of every spec this context creates, mirrored from the
23
+ * C# context's `[JsonSourceGenerationOptions]` (`WriteIndented` and friends,
24
+ * #752). Generated contexts override it only for an indented context.
25
+ */
26
+ protected get writeOptions(): JsonWriteOptions;
21
27
  /**
22
28
  * Registers a spec in the internal registry and returns it, with the
23
- * context's read options attached. Intended to be called from lazy getters
29
+ * context's read and write options attached. Intended to be called from lazy getters
24
30
  * in generated subclasses:
25
31
  *
26
32
  * ```ts
@@ -42,15 +48,15 @@ export declare abstract class SerializerContext {
42
48
  * ```
43
49
  *
44
50
  * Nothing is registered: a value spec has no constructor to resolve. The
45
- * context's read options are attached, as by `createSpec`.
51
+ * context's read and write options are attached, as by `createSpec`.
46
52
  */
47
53
  protected createValueSpec<T>(spec: ValueSpec<T>): ValueSpec<T>;
48
54
  /**
49
- * `spec` with the context's read options, under any the spec declares
50
- * itself. A spec stays as given when neither has one, so default contexts
51
- * keep their specs unchanged.
55
+ * `spec` with the context's read and write options, under any the spec
56
+ * declares itself. A spec stays as given when neither has one, so default
57
+ * contexts keep their specs unchanged.
52
58
  */
53
- private withReadOptions;
59
+ private withContextOptions;
54
60
  /**
55
61
  * Looks up a spec by constructor reference. Returns undefined if the type
56
62
  * was not registered via createSpec().
@@ -1,7 +1,9 @@
1
1
  /** System.Text.Json's default read behavior: no option set. */
2
2
  const DEFAULT_READ_OPTIONS = /* @__PURE__ */ Object.freeze({});
3
- function hasNoOptions(readOptions) {
4
- return Object.keys(readOptions).length === 0;
3
+ /** System.Text.Json's default text formatting: compact text. */
4
+ const DEFAULT_WRITE_OPTIONS = /* @__PURE__ */ Object.freeze({});
5
+ function hasNoOptions(options) {
6
+ return Object.keys(options).length === 0;
5
7
  }
6
8
  /**
7
9
  * Base class for generated serializer contexts. Each context holds options
@@ -28,9 +30,17 @@ export class SerializerContext {
28
30
  get readOptions() {
29
31
  return DEFAULT_READ_OPTIONS;
30
32
  }
33
+ /**
34
+ * The text formatting of every spec this context creates, mirrored from the
35
+ * C# context's `[JsonSourceGenerationOptions]` (`WriteIndented` and friends,
36
+ * #752). Generated contexts override it only for an indented context.
37
+ */
38
+ get writeOptions() {
39
+ return DEFAULT_WRITE_OPTIONS;
40
+ }
31
41
  /**
32
42
  * Registers a spec in the internal registry and returns it, with the
33
- * context's read options attached. Intended to be called from lazy getters
43
+ * context's read and write options attached. Intended to be called from lazy getters
34
44
  * in generated subclasses:
35
45
  *
36
46
  * ```ts
@@ -40,7 +50,7 @@ export class SerializerContext {
40
50
  * ```
41
51
  */
42
52
  createSpec(spec) {
43
- const attached = this.withReadOptions(spec);
53
+ const attached = this.withContextOptions(spec);
44
54
  // Only register class-backed types (those with a constructor reference).
45
55
  // [PlainObject] specs have no `type` field — they're accessed via their
46
56
  // getter on the context, not via constructor-keyed resolve().
@@ -61,19 +71,21 @@ export class SerializerContext {
61
71
  * ```
62
72
  *
63
73
  * Nothing is registered: a value spec has no constructor to resolve. The
64
- * context's read options are attached, as by `createSpec`.
74
+ * context's read and write options are attached, as by `createSpec`.
65
75
  */
66
76
  createValueSpec(spec) {
67
- return this.withReadOptions(spec);
77
+ return this.withContextOptions(spec);
68
78
  }
69
79
  /**
70
- * `spec` with the context's read options, under any the spec declares
71
- * itself. A spec stays as given when neither has one, so default contexts
72
- * keep their specs unchanged.
80
+ * `spec` with the context's read and write options, under any the spec
81
+ * declares itself. A spec stays as given when neither has one, so default
82
+ * contexts keep their specs unchanged.
73
83
  */
74
- withReadOptions(spec) {
84
+ withContextOptions(spec) {
75
85
  const readOptions = { ...this.readOptions, ...spec.readOptions };
76
- return hasNoOptions(readOptions) ? spec : { ...spec, readOptions };
86
+ const writeOptions = { ...this.writeOptions, ...spec.writeOptions };
87
+ const withReads = hasNoOptions(readOptions) ? spec : { ...spec, readOptions };
88
+ return hasNoOptions(writeOptions) ? withReads : { ...withReads, writeOptions };
77
89
  }
78
90
  /**
79
91
  * Looks up a spec by constructor reference. Returns undefined if the type
@@ -244,6 +244,8 @@ export interface TypeSpec<T = unknown> {
244
244
  readonly typeName?: string;
245
245
  /** The context's read behavior; absent when it is System.Text.Json's default. */
246
246
  readonly readOptions?: JsonReadOptions;
247
+ /** The context's text formatting; absent when it writes compact text (the default). */
248
+ readonly writeOptions?: JsonWriteOptions;
247
249
  /**
248
250
  * TS names of this contract's properties (its base chain's included) that
249
251
  * a read sets after construction, and only when the payload carries their
@@ -309,6 +311,22 @@ export interface JsonReadOptions {
309
311
  /** The type discriminator may appear after other properties (FR-002). */
310
312
  readonly allowOutOfOrderMetadataProperties?: boolean;
311
313
  }
314
+ /**
315
+ * Context-level text formatting mirrored from `[JsonSourceGenerationOptions]`
316
+ * (`WriteIndented`, `IndentCharacter`, `IndentSize`, `NewLine`); only
317
+ * `serializeText` reads it. Every member is optional; an absent member is
318
+ * System.Text.Json's default.
319
+ */
320
+ export interface JsonWriteOptions {
321
+ /** Write each element and property on its own line. */
322
+ readonly writeIndented?: boolean;
323
+ /** The indent character, a space (the default) or a tab. */
324
+ readonly indentCharacter?: " " | "\t";
325
+ /** The indent characters per nesting level, 0 to 127; 2 by default. */
326
+ readonly indentSize?: number;
327
+ /** The line break; `"\n"` by default (System.Text.Json's is the platform's). */
328
+ readonly newLine?: "\n" | "\r\n";
329
+ }
312
330
  /**
313
331
  * Spec of a non-object `[JsonSerializable]` root (a collection, dictionary,
314
332
  * set, primitive, enum, branded or nullable type): the same descriptor that
@@ -337,6 +355,8 @@ export interface ValueSpec<T = unknown> {
337
355
  readonly typeName?: string;
338
356
  /** The context's read behavior; absent when it is System.Text.Json's default. */
339
357
  readonly readOptions?: JsonReadOptions;
358
+ /** The context's text formatting; absent when it writes compact text (the default). */
359
+ readonly writeOptions?: JsonWriteOptions;
340
360
  }
341
361
  /** Any spec the generated context exposes: an object contract or a value root. */
342
362
  export type JsonTypeInfo<T = unknown> = TypeSpec<T> | ValueSpec<T>;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The key bucketing `groupBy`, `toLookup` and `join` share: the elements of a source
3
+ * under the equality .NET uses for a key (`EqualityComparer<K>.Default`, or a user
4
+ * comparer), in the order the keys are first seen, each bucket in source order.
5
+ */
6
+ import type { IEqualityComparer } from "../collections/default-comparer.ts";
7
+ import { HashCore } from "../collections/hash-core.ts";
8
+ import type { Grouping } from "./types.ts";
9
+ /** Elements of `source` bucketed by `keySelector`; a `null` key is skipped when `skipNullKeys`. */
10
+ export declare function bucketsOf<T, K, V = T>(source: Iterable<T>, keySelector: (item: T) => K, comparer: IEqualityComparer<K> | null | undefined, elementSelector?: (item: T) => V, skipNullKeys?: boolean): HashCore<K, V[]>;
11
+ /** The groupings of `buckets`: an iterable bucket that also reads `.key`. */
12
+ export declare function groupingsOf<K, T>(buckets: HashCore<K, T[]>): Generator<Grouping<K, T>>;
@@ -0,0 +1,42 @@
1
+ import { HashCore } from "../collections/hash-core.js";
2
+ /**
3
+ * `comparer` as .NET's `Lookup` uses it: a `null` key hashes to 0 without asking the
4
+ * comparer, which may throw on it (`GetHashCode(string value) => value.Length`).
5
+ */
6
+ function nullSafe(comparer) {
7
+ return comparer === null || comparer === undefined
8
+ ? comparer
9
+ : {
10
+ equals: (a, b) => comparer.equals(a, b),
11
+ getHashCode: (key) => key === null || key === undefined ? 0 : comparer.getHashCode(key),
12
+ };
13
+ }
14
+ /** Elements of `source` bucketed by `keySelector`; a `null` key is skipped when `skipNullKeys`. */
15
+ export function bucketsOf(source, keySelector, comparer, elementSelector, skipNullKeys = false) {
16
+ const buckets = new HashCore(nullSafe(comparer));
17
+ if (elementSelector === undefined && !skipNullKeys && comparer) {
18
+ return bucketAll(source, keySelector, buckets);
19
+ }
20
+ for (const item of source) {
21
+ const key = keySelector(item);
22
+ if (skipNullKeys && (key === null || key === undefined)) {
23
+ continue;
24
+ }
25
+ buckets.append(key, elementSelector === undefined ? item : elementSelector(item));
26
+ }
27
+ return buckets;
28
+ }
29
+ function bucketAll(source, keySelector, buckets) {
30
+ for (const item of source) {
31
+ buckets.append(keySelector(item), item);
32
+ }
33
+ return buckets;
34
+ }
35
+ /** The groupings of `buckets`: an iterable bucket that also reads `.key`. */
36
+ export function* groupingsOf(buckets) {
37
+ for (const [key, items] of buckets) {
38
+ // `Grouping` is `Iterable<T> & { key }`: the bucket array itself carries the key, so
39
+ // consumers can `for…of` the grouping and read `.key`.
40
+ yield Object.assign(items, { key });
41
+ }
42
+ }
@@ -24,9 +24,10 @@ export type { Stage } from "./linq.ts";
24
24
  export type { BinaryOp, ExprBinary, ExprCall, ExprCapture, ExprConditional, ExprConvert, ExprLambda, ExprLiteral, ExprMember, ExprNew, ExprParam, ExprTree, ExprTypeRef, ExprUnary, QueryableMeta, UnaryOp, } from "./expr-tree.ts";
25
25
  export { ExprTreeVisitor, compareValues, compileLambdaBody, evaluateExprTree, readParamName, } from "./expr-tree-visitor.ts";
26
26
  export type { ExprTreeScope } from "./expr-tree-visitor.ts";
27
- export type { AnyOperator, AnyTerminal, OperatorBase, OperatorKind, TerminalBase, TerminalKind, AppendOp, ConcatOp, DistinctByOp, DistinctOp, ExceptOp, GroupByOp, Grouping, IntersectOp, OrderByDescendingOp, OrderByOp, ThenByDescendingOp, ThenByOp, PrependOp, ReverseOp, DefaultIfEmptyOp, SelectManyOp, SelectOp, SkipOp, SkipWhileOp, TakeOp, TakeWhileOp, UnionOp, WhereOp, ZipOp, AggregateTerm, AllTerm, AnyTerm, AverageTerm, AverageInt64Term, ContainsTerm, CountTerm, ElementAtTerm, ElementAtOrDefaultTerm, FirstOrDefaultTerm, FirstTerm, LastOrDefaultTerm, LastTerm, MaxTerm, MaxInt64Term, MaxByTerm, MinTerm, MinInt64Term, MinByTerm, SingleTerm, SingleOrDefaultTerm, SumTerm, SumInt64Term, ToArrayTerm, ToMapTerm, ToSetTerm, ToListTerm, ToDictionaryTerm, ToHashSetTerm, } from "./types.ts";
28
- export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, zip, defaultIfEmpty, } from "./operators.ts";
29
- export { toArray, toMap, toSet, toList, toDictionary, toHashSet, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.ts";
27
+ export type { AnyOperator, AnyTerminal, OperatorBase, OperatorKind, TerminalBase, TerminalKind, AppendOp, ConcatOp, DistinctByOp, DistinctOp, ExceptOp, GroupByOp, Grouping, IntersectOp, OrderByDescendingOp, OrderByOp, ThenByDescendingOp, ThenByOp, PrependOp, ReverseOp, DefaultIfEmptyOp, SelectManyOp, SelectOp, SkipOp, SkipWhileOp, TakeOp, TakeWhileOp, UnionOp, WhereOp, ZipOp, AggregateTerm, AllTerm, AnyTerm, AverageTerm, AverageInt64Term, ContainsTerm, CountTerm, ElementAtTerm, ElementAtOrDefaultTerm, FirstOrDefaultTerm, FirstTerm, LastOrDefaultTerm, LastTerm, MaxTerm, MaxInt64Term, MaxByTerm, MinTerm, MinInt64Term, MinByTerm, SingleTerm, SingleOrDefaultTerm, SumTerm, SumInt64Term, ToArrayTerm, ToMapTerm, ToSetTerm, ToListTerm, ToDictionaryTerm, ToHashSetTerm, ToLookupTerm, SequenceEqualTerm, JoinOp, } from "./types.ts";
28
+ export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, join, zip, defaultIfEmpty, } from "./operators.ts";
29
+ export { toArray, toMap, toSet, toList, toDictionary, toHashSet, toLookup, sequenceEqual, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.ts";
30
30
  export { averageInt64, averageNullableInt64, maxInt64Of, maxNullableInt64Of, maxUInt64Of, minInt64Of, minNullableInt64Of, minUInt64Of, sumInt64, } from "./int64-terminals.ts";
31
+ export { Lookup } from "./lookup.ts";
31
32
  export { averageDecimal, averageNullableDecimal, sumDecimal } from "./decimal-terminals.ts";
32
33
  export type { DecimalConstructor, DecimalValue } from "./decimal-terminals.ts";
@@ -21,7 +21,8 @@
21
21
  */
22
22
  export { LINQ_STAGES, getStages, linq, stages } from "./linq.js";
23
23
  export { ExprTreeVisitor, compareValues, compileLambdaBody, evaluateExprTree, readParamName, } from "./expr-tree-visitor.js";
24
- export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, zip, defaultIfEmpty, } from "./operators.js";
25
- export { toArray, toMap, toSet, toList, toDictionary, toHashSet, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.js";
24
+ export { where, select, selectMany, take, skip, takeWhile, skipWhile, distinct, distinctBy, concat, union, intersect, except, append, prepend, reverse, orderBy, orderByDescending, thenBy, thenByDescending, groupBy, join, zip, defaultIfEmpty, } from "./operators.js";
25
+ export { toArray, toMap, toSet, toList, toDictionary, toHashSet, toLookup, sequenceEqual, first, firstOrDefault, last, lastOrDefault, single, singleOrDefault, any, all, count, sum, min, minNullable, max, maxNullable, minBy, minByNullable, maxBy, maxByNullable, average, averageNullable, contains, aggregate, elementAt, elementAtOrDefault, } from "./terminals.js";
26
26
  export { averageInt64, averageNullableInt64, maxInt64Of, maxNullableInt64Of, maxUInt64Of, minInt64Of, minNullableInt64Of, minUInt64Of, sumInt64, } from "./int64-terminals.js";
27
+ export { Lookup } from "./lookup.js";
27
28
  export { averageDecimal, averageNullableDecimal, sumDecimal } from "./decimal-terminals.js";
@@ -1,5 +1,6 @@
1
1
  export function linq(source, ...ops) {
2
- const result = ops.reduce((acc, op) => op.apply(acc), source);
2
+ const start = typeof source === "string" ? codeUnitsOf(source) : source;
3
+ const result = ops.reduce((acc, op) => op.apply(acc), start);
3
4
  // Attach the original stage list to the materialized result so an
4
5
  // IQueryable-style consumer can introspect the chain. Skipped for
5
6
  // primitive results (terminals like `count` / `sum` return numbers
@@ -44,3 +45,21 @@ export function stages(...ops) {
44
45
  return ops;
45
46
  }
46
47
  /* eslint-enable @typescript-eslint/no-explicit-any */
48
+ /**
49
+ * The UTF-16 code units of `text`, read lazily: a C# string enumerates them,
50
+ * where a JS string's own iterator yields code points, so a surrogate pair
51
+ * would be one element (#695). No array is built, so an early-exit operator
52
+ * (`first`, `any`, `take`) reads only the units it needs.
53
+ */
54
+ function codeUnitsOf(text) {
55
+ return {
56
+ [Symbol.iterator]: () => {
57
+ let index = 0;
58
+ return {
59
+ next: () => index < text.length
60
+ ? { done: false, value: text[index++] }
61
+ : { done: true, value: undefined },
62
+ };
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `System.Linq.ILookup<TKey, TElement>`, the result of `ToLookup`: the elements grouped by
3
+ * key, enumerated as groupings in first-seen key order. Keys are compared as `groupBy`
4
+ * compares them.
5
+ */
6
+ import type { HashCore } from "../collections/hash-core.ts";
7
+ import type { Grouping } from "./types.ts";
8
+ export declare class Lookup<K, T> implements Iterable<Grouping<K, T>> {
9
+ readonly _buckets: HashCore<K, T[]>;
10
+ constructor(buckets: HashCore<K, T[]>);
11
+ /** The number of distinct keys. */
12
+ get count(): number;
13
+ /** The elements under `key`, in source order; an empty sequence when the key is absent. */
14
+ get(key: K): Iterable<T>;
15
+ contains(key: K): boolean;
16
+ [Symbol.iterator](): Iterator<Grouping<K, T>>;
17
+ }
@@ -0,0 +1,20 @@
1
+ import { groupingsOf } from "./grouping.js";
2
+ export class Lookup {
3
+ constructor(buckets) {
4
+ Object.defineProperty(this, "_buckets", { value: buckets });
5
+ }
6
+ /** The number of distinct keys. */
7
+ get count() {
8
+ return this._buckets.size;
9
+ }
10
+ /** The elements under `key`, in source order; an empty sequence when the key is absent. */
11
+ get(key) {
12
+ return this._buckets.get(key) ?? [];
13
+ }
14
+ contains(key) {
15
+ return this._buckets.has(key);
16
+ }
17
+ [Symbol.iterator]() {
18
+ return groupingsOf(this._buckets);
19
+ }
20
+ }