metano-runtime 2.6.1 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from "./system";
2
- export * from "./type-checking";
1
+ export * from "./system/index.ts";
2
+ export * from "./type-checking/index.ts";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export * from "./system";
2
- export * from "./type-checking";
1
+ export * from "./system/index.js";
2
+ export * from "./type-checking/index.js";
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Runtime helpers for the C# `Dictionary<TKey, TValue>` / `IReadOnlyDictionary<TKey,
3
+ * TValue>` family of methods whose lowering can't be expressed as a simple inline JS
4
+ * expression. The compiler imports these via the declarative mappings under
5
+ * `Metano/Runtime/Dictionaries.cs`.
6
+ */
7
+ /**
8
+ * Returns the value stored under `key`, or `defaultValue` when the key is absent.
9
+ * Mirrors `CollectionExtensions.GetValueOrDefault(dictionary, key, defaultValue)`.
10
+ *
11
+ * Membership is tested with `has` rather than `get(key) ?? defaultValue`, so a key that
12
+ * is present with a stored `null` value returns that `null`, as it does in C#. The
13
+ * compiler passes `default(TValue)` (`0`, `false`, `null`, …) as `defaultValue` for the
14
+ * single-argument overload.
15
+ */
16
+ export declare function getValueOrDefault<K, V>(map: ReadonlyMap<K, V>, key: K, defaultValue: V): V;
17
+ /**
18
+ * Looks `key` up once and reports whether it was present, mirroring
19
+ * `IDictionary<TKey, TValue>.TryGetValue(key, out value)`. The compiler lowers the `out`
20
+ * parameter into the second tuple element and passes `default(TValue)` (`0`, `false`,
21
+ * `null`, …) as `missingValue`, which is what C# stores in `value` on a miss.
22
+ *
23
+ * Membership is tested with `has`, so a key stored with a `null` or `undefined` value is
24
+ * reported as found. Destructure the result with `const` so TypeScript narrows `value` on
25
+ * `found`.
26
+ */
27
+ export declare function tryGetValue<K, V, D>(map: ReadonlyMap<K, V>, key: K, missingValue: D): readonly [found: true, value: V] | readonly [found: false, value: D];
28
+ /**
29
+ * Adds `value` under `key`, mirroring `Dictionary<TKey, TValue>.Add(key, value)`: unlike
30
+ * `Map.set`, an existing entry is never overwritten. Collection initializers
31
+ * (`new Dictionary<K, V> { { k, v } }`) lower to this call too.
32
+ *
33
+ * The key is rendered with `String(key)`, which matches the .NET message for
34
+ * primitive keys and for keys whose class overrides `toString`.
35
+ *
36
+ * @throws Error when `key` is `null` or `undefined` (.NET throws
37
+ * `ArgumentNullException`) or is already present (.NET throws `ArgumentException`),
38
+ * with the message .NET reports.
39
+ */
40
+ export declare function addEntry<K, V>(map: Map<K, V>, key: K, value: V): void;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Runtime helpers for the C# `Dictionary<TKey, TValue>` / `IReadOnlyDictionary<TKey,
3
+ * TValue>` family of methods whose lowering can't be expressed as a simple inline JS
4
+ * expression. The compiler imports these via the declarative mappings under
5
+ * `Metano/Runtime/Dictionaries.cs`.
6
+ */
7
+ /**
8
+ * Returns the value stored under `key`, or `defaultValue` when the key is absent.
9
+ * Mirrors `CollectionExtensions.GetValueOrDefault(dictionary, key, defaultValue)`.
10
+ *
11
+ * Membership is tested with `has` rather than `get(key) ?? defaultValue`, so a key that
12
+ * is present with a stored `null` value returns that `null`, as it does in C#. The
13
+ * compiler passes `default(TValue)` (`0`, `false`, `null`, …) as `defaultValue` for the
14
+ * single-argument overload.
15
+ */
16
+ export function getValueOrDefault(map, key, defaultValue) {
17
+ return map.has(key) ? map.get(key) : defaultValue;
18
+ }
19
+ /**
20
+ * Looks `key` up once and reports whether it was present, mirroring
21
+ * `IDictionary<TKey, TValue>.TryGetValue(key, out value)`. The compiler lowers the `out`
22
+ * parameter into the second tuple element and passes `default(TValue)` (`0`, `false`,
23
+ * `null`, …) as `missingValue`, which is what C# stores in `value` on a miss.
24
+ *
25
+ * Membership is tested with `has`, so a key stored with a `null` or `undefined` value is
26
+ * reported as found. Destructure the result with `const` so TypeScript narrows `value` on
27
+ * `found`.
28
+ */
29
+ export function tryGetValue(map, key, missingValue) {
30
+ return map.has(key) ? [true, map.get(key)] : [false, missingValue];
31
+ }
32
+ /**
33
+ * Adds `value` under `key`, mirroring `Dictionary<TKey, TValue>.Add(key, value)`: unlike
34
+ * `Map.set`, an existing entry is never overwritten. Collection initializers
35
+ * (`new Dictionary<K, V> { { k, v } }`) lower to this call too.
36
+ *
37
+ * The key is rendered with `String(key)`, which matches the .NET message for
38
+ * primitive keys and for keys whose class overrides `toString`.
39
+ *
40
+ * @throws Error when `key` is `null` or `undefined` (.NET throws
41
+ * `ArgumentNullException`) or is already present (.NET throws `ArgumentException`),
42
+ * with the message .NET reports.
43
+ */
44
+ export function addEntry(map, key, value) {
45
+ if (key === null || key === undefined) {
46
+ throw new Error("Value cannot be null. (Parameter 'key')");
47
+ }
48
+ if (map.has(key)) {
49
+ throw new Error(`An item with the same key has already been added. Key: ${String(key)}`);
50
+ }
51
+ map.set(key, value);
52
+ }
@@ -1,3 +1,4 @@
1
+ export * from "./dictionary-helpers.ts";
1
2
  export * from "./hash-set.ts";
2
3
  export * from "./immutable-collection.ts";
3
4
  export * from "./list-helpers.ts";
@@ -1,3 +1,4 @@
1
+ export * from "./dictionary-helpers.js";
1
2
  export * from "./hash-set.js";
2
3
  export * from "./immutable-collection.js";
3
4
  export * from "./list-helpers.js";
@@ -44,3 +44,33 @@ export declare function hashCode(value: unknown): number;
44
44
  * recursive method-call ambiguity for human readers).
45
45
  */
46
46
  export declare const valueEquals: typeof equals;
47
+ /**
48
+ * C#'s static `object.Equals(a, b)`: true when both are null or `a.Equals(b)`, where
49
+ * `Equals` is what the value's type defines. Unlike {@link equals}, it never compares a
50
+ * class instance by structure, since a C# class that does not override `Equals`
51
+ * compares by reference:
52
+ *
53
+ * 1. Reference identity (`a === b`) wins immediately; `null` / `undefined` equal only
54
+ * themselves.
55
+ * 2. `NaN` equals `NaN`; other primitives use `===`.
56
+ * 3. Objects with an `equals(other)` method delegate to it (records, user overrides,
57
+ * `Decimal`, Temporal types).
58
+ * 4. Plain object literals (`[PlainObject]` records, anonymous types) compare by shape
59
+ * through {@link equals}, as their C# types compare by value.
60
+ * 5. Everything else (class instances, arrays, `Map`s, `Set`s) compares by reference,
61
+ * as C# arrays, lists, dictionaries and sets do.
62
+ */
63
+ export declare function objectEquals(a: unknown, b: unknown): boolean;
64
+ /**
65
+ * C#'s `ValueTuple.Equals(other)` over the positional arrays C# tuples lower to: same
66
+ * length, and each element pair equal under {@link objectEquals} (C# compares each
67
+ * element with `EqualityComparer<T>.Default`, so a class element compares by reference).
68
+ * A nested tuple element is an array too, so it compares by reference.
69
+ */
70
+ export declare function tupleEquals(tuple: readonly unknown[], other: unknown): boolean;
71
+ /**
72
+ * Alias the compiler emits for every C# `GetHashCode()` call. Same contract as
73
+ * {@link hashCode}; the distinct name keeps a call site from colliding with a
74
+ * local or a method the user named `hashCode` (records declare one).
75
+ */
76
+ export declare const valueHashCode: typeof hashCode;
@@ -7,7 +7,9 @@
7
7
  * `equals` methods whenever a constructor parameter has a non-primitive type that
8
8
  * exposes a value-equality contract (Decimal, Temporal types, nested records, …).
9
9
  * The previous lowering used `===` for every field which silently diverged from C#
10
- * semantics for value-wrapper types — see #202.
10
+ * semantics for value-wrapper types — see #202. It also lowers C# `==` / `!=` over
11
+ * records to {@link valueEquals}, and every C# `GetHashCode()` call to
12
+ * {@link valueHashCode} (#254).
11
13
  */
12
14
  import { HashCode } from "./hash-code.js";
13
15
  /**
@@ -184,3 +186,59 @@ export function hashCode(value) {
184
186
  * recursive method-call ambiguity for human readers).
185
187
  */
186
188
  export const valueEquals = equals;
189
+ /**
190
+ * C#'s static `object.Equals(a, b)`: true when both are null or `a.Equals(b)`, where
191
+ * `Equals` is what the value's type defines. Unlike {@link equals}, it never compares a
192
+ * class instance by structure, since a C# class that does not override `Equals`
193
+ * compares by reference:
194
+ *
195
+ * 1. Reference identity (`a === b`) wins immediately; `null` / `undefined` equal only
196
+ * themselves.
197
+ * 2. `NaN` equals `NaN`; other primitives use `===`.
198
+ * 3. Objects with an `equals(other)` method delegate to it (records, user overrides,
199
+ * `Decimal`, Temporal types).
200
+ * 4. Plain object literals (`[PlainObject]` records, anonymous types) compare by shape
201
+ * through {@link equals}, as their C# types compare by value.
202
+ * 5. Everything else (class instances, arrays, `Map`s, `Set`s) compares by reference,
203
+ * as C# arrays, lists, dictionaries and sets do.
204
+ */
205
+ export function objectEquals(a, b) {
206
+ if (a === b)
207
+ return true;
208
+ if (a == null || b == null)
209
+ return false;
210
+ if (typeof a === "number") {
211
+ return typeof b === "number" && Number.isNaN(a) && Number.isNaN(b);
212
+ }
213
+ if (typeof a !== "object")
214
+ return false;
215
+ if (hasEqualsMethod(a))
216
+ return a.equals(b);
217
+ return isPlainObject(a) && isPlainObject(b) && equals(a, b);
218
+ }
219
+ /**
220
+ * C#'s `ValueTuple.Equals(other)` over the positional arrays C# tuples lower to: same
221
+ * length, and each element pair equal under {@link objectEquals} (C# compares each
222
+ * element with `EqualityComparer<T>.Default`, so a class element compares by reference).
223
+ * A nested tuple element is an array too, so it compares by reference.
224
+ */
225
+ export function tupleEquals(tuple, other) {
226
+ if (!Array.isArray(other) || other.length !== tuple.length)
227
+ return false;
228
+ return tuple.every((element, index) => objectEquals(element, other[index]));
229
+ }
230
+ function hasEqualsMethod(value) {
231
+ return "equals" in value && typeof value.equals === "function";
232
+ }
233
+ function isPlainObject(value) {
234
+ if (typeof value !== "object" || value === null)
235
+ return false;
236
+ const prototype = Object.getPrototypeOf(value);
237
+ return prototype === Object.prototype || prototype === null;
238
+ }
239
+ /**
240
+ * Alias the compiler emits for every C# `GetHashCode()` call. Same contract as
241
+ * {@link hashCode}; the distinct name keeps a call site from colliding with a
242
+ * local or a method the user named `hashCode` (records declare one).
243
+ */
244
+ export const valueHashCode = hashCode;
@@ -1,5 +1,6 @@
1
1
  export * from "./hash-code.ts";
2
2
  export * from "./equality.ts";
3
+ export * from "./record-copy.ts";
3
4
  export * from "./temporal-helpers.ts";
4
5
  export * from "./collections/index.ts";
5
6
  export * from "./linq/index.ts";
@@ -7,3 +8,6 @@ export * from "./json/index.ts";
7
8
  export * from "./uuid.ts";
8
9
  export * from "./delegates.ts";
9
10
  export * from "./bind-receiver.ts";
11
+ export * from "./integer-division.ts";
12
+ export * from "./math.ts";
13
+ export * from "./number-parsing.ts";
@@ -1,5 +1,6 @@
1
1
  export * from "./hash-code.js";
2
2
  export * from "./equality.js";
3
+ export * from "./record-copy.js";
3
4
  export * from "./temporal-helpers.js";
4
5
  export * from "./collections/index.js";
5
6
  export * from "./linq/index.js";
@@ -7,3 +8,6 @@ export * from "./json/index.js";
7
8
  export * from "./uuid.js";
8
9
  export * from "./delegates.js";
9
10
  export * from "./bind-receiver.js";
11
+ export * from "./integer-division.js";
12
+ export * from "./math.js";
13
+ export * from "./number-parsing.js";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Runtime helper for C#'s integer division. The compiler lowers `/` and `/=` over
3
+ * integral operands (`int`, `long`, `uint`, `short`, `byte`, `char`, …) to
4
+ * {@link intDiv}, because JavaScript's `/` is always floating-point: `7 / 2` is `3.5`,
5
+ * where C# gives `3`.
6
+ */
7
+ /**
8
+ * Divides `dividend` by `divisor` and truncates the quotient toward zero, as C# does
9
+ * for integral operands (`-7 / 2` is `-3`). A `null` (or `undefined`) operand yields
10
+ * `null`, matching C#'s lifted `int?` division.
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
+ * @throws Error with .NET's `DivideByZeroException` message when `divisor` is zero,
17
+ * where a bare `Math.trunc(dividend / divisor)` would yield `Infinity` or `NaN`.
18
+ */
19
+ export declare function intDiv(dividend: number, divisor: number): number;
20
+ export declare function intDiv(dividend: number | null | undefined, divisor: number | null | undefined): number | null;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Runtime helper for C#'s integer division. The compiler lowers `/` and `/=` over
3
+ * integral operands (`int`, `long`, `uint`, `short`, `byte`, `char`, …) to
4
+ * {@link intDiv}, because JavaScript's `/` is always floating-point: `7 / 2` is `3.5`,
5
+ * where C# gives `3`.
6
+ */
7
+ /** The message .NET's `DivideByZeroException` carries by default. */
8
+ const DIVIDE_BY_ZERO_MESSAGE = "Attempted to divide by zero.";
9
+ export function intDiv(dividend, divisor) {
10
+ if (dividend == null || divisor == null) {
11
+ return null;
12
+ }
13
+ if (divisor === 0) {
14
+ throw new Error(DIVIDE_BY_ZERO_MESSAGE);
15
+ }
16
+ // C# integers have no negative zero: `+ 0` turns the `-0` of `-1 / 3` into `0`.
17
+ return Math.trunc(dividend / divisor) + 0;
18
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Runtime helpers for the C# `Math.Round` / `decimal.Round` family. The compiler
3
+ * imports them via the declarative mappings under `Metano/Runtime/Math.cs` and
4
+ * `Metano/Runtime/Decimal.cs`.
5
+ *
6
+ * JavaScript's `Math.round` rounds a midpoint toward +Infinity (`Math.round(-2.5)` is
7
+ * `-2`, `Math.round(2.5)` is `3`) and takes no digit count, while C# rounds a midpoint
8
+ * to the nearest even number by default (`Math.Round(2.5)` is `2`) and accepts both a
9
+ * digit count and a {@link MidpointRounding} mode.
10
+ */
11
+ /**
12
+ * Mirror of `System.MidpointRounding`. The numeric values match the .NET enum, so a
13
+ * value read from serialized C# data keeps its meaning.
14
+ */
15
+ export declare const MidpointRounding: {
16
+ readonly ToEven: 0;
17
+ readonly AwayFromZero: 1;
18
+ readonly ToZero: 2;
19
+ readonly ToNegativeInfinity: 3;
20
+ readonly ToPositiveInfinity: 4;
21
+ };
22
+ export type MidpointRounding = (typeof MidpointRounding)[keyof typeof MidpointRounding];
23
+ /** Structural view of a `decimal.js` `Decimal`, the only operation the helper uses. */
24
+ export interface DecimalRoundable<D> {
25
+ toDecimalPlaces(decimalPlaces: number, rounding: number): D;
26
+ }
27
+ /**
28
+ * Rounds `value` to `digits` fractional digits, resolving a midpoint with `mode`.
29
+ * Mirrors `System.Math.Round(double, int, MidpointRounding)` and its shorter overloads:
30
+ * the value is scaled by `10^digits`, rounded to an integer and scaled back, the
31
+ * algorithm .NET 10 uses. `2.675 * 100` rounds to the double `267.5`, so
32
+ * `roundNumber(2.675, 2)` is `2.68`, as `Math.Round(2.675, 2)` is on .NET 10. `NaN`, the
33
+ * infinities and magnitudes of `1e16` or more are returned unchanged, and the sign of a
34
+ * zero result is preserved.
35
+ *
36
+ * .NET 11 rounds the exact binary value instead (`Math.Round(2.675, 2)` is `2.67`
37
+ * there), so parity is pinned to the .NET 10 algorithm; revisit this helper when the
38
+ * supported target framework moves past .NET 10.
39
+ *
40
+ * @throws RangeError when `digits` is outside 0–15 or `mode` is not a
41
+ * {@link MidpointRounding} value, the cases where .NET throws
42
+ * `ArgumentOutOfRangeException` / `ArgumentException`.
43
+ */
44
+ export declare function roundNumber(value: number, digits?: number, mode?: MidpointRounding): number;
45
+ /**
46
+ * Rounds a `decimal.js` value to `digits` fractional digits, resolving a midpoint with
47
+ * `mode`. Mirrors `System.Math.Round(decimal, int, MidpointRounding)` and
48
+ * `decimal.Round`. `decimal.js` rounds the exact decimal value, so no binary
49
+ * representation error is involved.
50
+ *
51
+ * @throws RangeError when `digits` is outside 0–28 or `mode` is not a
52
+ * {@link MidpointRounding} value.
53
+ */
54
+ export declare function roundDecimal<D extends DecimalRoundable<D>>(value: D, digits?: number, mode?: MidpointRounding): D;
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Runtime helpers for the C# `Math.Round` / `decimal.Round` family. The compiler
3
+ * imports them via the declarative mappings under `Metano/Runtime/Math.cs` and
4
+ * `Metano/Runtime/Decimal.cs`.
5
+ *
6
+ * JavaScript's `Math.round` rounds a midpoint toward +Infinity (`Math.round(-2.5)` is
7
+ * `-2`, `Math.round(2.5)` is `3`) and takes no digit count, while C# rounds a midpoint
8
+ * to the nearest even number by default (`Math.Round(2.5)` is `2`) and accepts both a
9
+ * digit count and a {@link MidpointRounding} mode.
10
+ */
11
+ /**
12
+ * Mirror of `System.MidpointRounding`. The numeric values match the .NET enum, so a
13
+ * value read from serialized C# data keeps its meaning.
14
+ */
15
+ export const MidpointRounding = {
16
+ ToEven: 0,
17
+ AwayFromZero: 1,
18
+ ToZero: 2,
19
+ ToNegativeInfinity: 3,
20
+ ToPositiveInfinity: 4,
21
+ };
22
+ /** `Math.Round(double, int)` accepts 0 to 15 fractional digits. */
23
+ const MAX_DOUBLE_ROUNDING_DIGITS = 15;
24
+ /** `decimal.Round(decimal, int)` accepts 0 to 28 fractional digits. */
25
+ const MAX_DECIMAL_ROUNDING_DIGITS = 28;
26
+ /** Magnitude from which every double is already an integer at 15 digits of scale. */
27
+ const DOUBLE_ROUND_LIMIT = 1e16;
28
+ /** Exact powers of ten, the same table .NET scales by before rounding. */
29
+ const POWERS_OF_TEN = [
30
+ 1, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
31
+ ];
32
+ /**
33
+ * `decimal.js` rounding constants (`Decimal.ROUND_*`) indexed by
34
+ * {@link MidpointRounding}. The values are part of the `decimal.js` public API, so the
35
+ * runtime does not need to depend on the package to name them.
36
+ */
37
+ const DECIMAL_JS_ROUNDING = [
38
+ 6, // ToEven → ROUND_HALF_EVEN
39
+ 4, // AwayFromZero → ROUND_HALF_UP (a midpoint moves away from zero)
40
+ 1, // ToZero → ROUND_DOWN
41
+ 3, // ToNegativeInfinity → ROUND_FLOOR
42
+ 2, // ToPositiveInfinity → ROUND_CEIL
43
+ ];
44
+ /** Number of {@link MidpointRounding} modes; the values run from 0 upward. */
45
+ const MIDPOINT_ROUNDING_MODE_COUNT = Object.keys(MidpointRounding).length;
46
+ /**
47
+ * Rounds `value` to `digits` fractional digits, resolving a midpoint with `mode`.
48
+ * Mirrors `System.Math.Round(double, int, MidpointRounding)` and its shorter overloads:
49
+ * the value is scaled by `10^digits`, rounded to an integer and scaled back, the
50
+ * algorithm .NET 10 uses. `2.675 * 100` rounds to the double `267.5`, so
51
+ * `roundNumber(2.675, 2)` is `2.68`, as `Math.Round(2.675, 2)` is on .NET 10. `NaN`, the
52
+ * infinities and magnitudes of `1e16` or more are returned unchanged, and the sign of a
53
+ * zero result is preserved.
54
+ *
55
+ * .NET 11 rounds the exact binary value instead (`Math.Round(2.675, 2)` is `2.67`
56
+ * there), so parity is pinned to the .NET 10 algorithm; revisit this helper when the
57
+ * supported target framework moves past .NET 10.
58
+ *
59
+ * @throws RangeError when `digits` is outside 0–15 or `mode` is not a
60
+ * {@link MidpointRounding} value, the cases where .NET throws
61
+ * `ArgumentOutOfRangeException` / `ArgumentException`.
62
+ */
63
+ export function roundNumber(value, digits = 0, mode = MidpointRounding.ToEven) {
64
+ assertDigits(digits, MAX_DOUBLE_ROUNDING_DIGITS);
65
+ assertMode(mode);
66
+ if (!(Math.abs(value) < DOUBLE_ROUND_LIMIT))
67
+ return value;
68
+ const power = POWERS_OF_TEN[digits];
69
+ const rounded = roundToInteger(value * power, mode) / power;
70
+ return rounded === 0 ? copySignOfZero(value) : rounded;
71
+ }
72
+ /**
73
+ * Rounds a `decimal.js` value to `digits` fractional digits, resolving a midpoint with
74
+ * `mode`. Mirrors `System.Math.Round(decimal, int, MidpointRounding)` and
75
+ * `decimal.Round`. `decimal.js` rounds the exact decimal value, so no binary
76
+ * representation error is involved.
77
+ *
78
+ * @throws RangeError when `digits` is outside 0–28 or `mode` is not a
79
+ * {@link MidpointRounding} value.
80
+ */
81
+ export function roundDecimal(value, digits = 0, mode = MidpointRounding.ToEven) {
82
+ assertDigits(digits, MAX_DECIMAL_ROUNDING_DIGITS);
83
+ assertMode(mode);
84
+ return value.toDecimalPlaces(digits, DECIMAL_JS_ROUNDING[mode]);
85
+ }
86
+ function roundToInteger(value, mode) {
87
+ switch (mode) {
88
+ case MidpointRounding.ToEven:
89
+ return roundHalfToEven(value);
90
+ case MidpointRounding.AwayFromZero:
91
+ return roundHalfAwayFromZero(value);
92
+ case MidpointRounding.ToZero:
93
+ return Math.trunc(value);
94
+ case MidpointRounding.ToNegativeInfinity:
95
+ return Math.floor(value);
96
+ case MidpointRounding.ToPositiveInfinity:
97
+ return Math.ceil(value);
98
+ }
99
+ }
100
+ /**
101
+ * Banker's rounding. `value - floor(value)` is exact for every finite double, so the
102
+ * midpoint test never suffers a rounding error of its own.
103
+ */
104
+ function roundHalfToEven(value) {
105
+ const floor = Math.floor(value);
106
+ const fraction = value - floor;
107
+ if (fraction < 0.5)
108
+ return floor;
109
+ if (fraction > 0.5)
110
+ return floor + 1;
111
+ return floor % 2 === 0 ? floor : floor + 1;
112
+ }
113
+ function roundHalfAwayFromZero(value) {
114
+ const integer = Math.trunc(value);
115
+ const fraction = value - integer;
116
+ return Math.abs(fraction) >= 0.5 ? integer + Math.sign(fraction) : integer;
117
+ }
118
+ /** .NET keeps the sign of the input on a zero result (`Math.Round(-0.4)` is `-0`). */
119
+ function copySignOfZero(value) {
120
+ return value < 0 || Object.is(value, -0) ? -0 : 0;
121
+ }
122
+ function assertDigits(digits, max) {
123
+ if (!Number.isInteger(digits) || digits < 0 || digits > max)
124
+ throw new RangeError(`Rounding digits must be an integer between 0 and ${max}.`);
125
+ }
126
+ function assertMode(mode) {
127
+ if (!Number.isInteger(mode) || mode < 0 || mode >= MIDPOINT_ROUNDING_MODE_COUNT)
128
+ throw new RangeError(`The value '${mode}' is not a valid MidpointRounding mode.`);
129
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Runtime helpers for the C# `TryParse(string, out T)` family on the primitive types. The
3
+ * compiler lowers each `out` parameter into the second tuple element (see the declarative
4
+ * mappings under `Metano/Runtime/Parsing.cs`), so `int.TryParse(s, out var n)` becomes
5
+ * `const [ok, n] = tryParseInt32(s)`.
6
+ *
7
+ * Parsing follows the invariant culture: `.` is the decimal separator, `,` the thousands
8
+ * separator, and only the whitespace .NET accepts around a number (tab, line feed,
9
+ * vertical tab, form feed, carriage return and space) is ignored. On failure the value is
10
+ * C#'s `default` for the type (`0` or `false`).
11
+ */
12
+ /** The result of a `TryParse` call: whether it succeeded and the parsed value. */
13
+ export type ParseResult<T> = readonly [found: boolean, value: T];
14
+ /** Mirrors `int.TryParse(string, out int)`. */
15
+ export declare function tryParseInt32(text: string | null | undefined): ParseResult<number>;
16
+ /**
17
+ * Mirrors `long.TryParse(string, out long)`. The range check is exact; the value is a
18
+ * JavaScript `number`, so magnitudes above `Number.MAX_SAFE_INTEGER` lose precision, as
19
+ * every `long` does in the generated code.
20
+ */
21
+ export declare function tryParseInt64(text: string | null | undefined): ParseResult<number>;
22
+ /**
23
+ * Mirrors `double.TryParse(string, out double)` (and `float.TryParse`, whose values the
24
+ * generated code holds as `number` too). A value beyond the `double` range parses to
25
+ * an infinity, as it does since .NET Core 3.0.
26
+ */
27
+ export declare function tryParseFloat64(text: string | null | undefined): ParseResult<number>;
28
+ /**
29
+ * Mirrors `bool.TryParse(string, out bool)`: `true` / `false` in any letter case, around
30
+ * whitespace (JavaScript's `\s`, close to .NET's `char.IsWhiteSpace`) and `\0` characters.
31
+ */
32
+ export declare function tryParseBoolean(text: string | null | undefined): ParseResult<boolean>;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Runtime helpers for the C# `TryParse(string, out T)` family on the primitive types. The
3
+ * compiler lowers each `out` parameter into the second tuple element (see the declarative
4
+ * mappings under `Metano/Runtime/Parsing.cs`), so `int.TryParse(s, out var n)` becomes
5
+ * `const [ok, n] = tryParseInt32(s)`.
6
+ *
7
+ * Parsing follows the invariant culture: `.` is the decimal separator, `,` the thousands
8
+ * separator, and only the whitespace .NET accepts around a number (tab, line feed,
9
+ * vertical tab, form feed, carriage return and space) is ignored. On failure the value is
10
+ * C#'s `default` for the type (`0` or `false`).
11
+ */
12
+ const INT32_MIN = -2147483648;
13
+ const INT32_MAX = 2147483647;
14
+ const INT64_MIN = -9223372036854775808n;
15
+ const INT64_MAX = 9223372036854775807n;
16
+ /** `NumberStyles.Integer`: an optional sign followed by decimal digits. */
17
+ const INTEGER = /^[+-]?\d+$/;
18
+ /**
19
+ * `NumberStyles.Float | NumberStyles.AllowThousands`: an optional sign, digits with
20
+ * optional thousands separators, an optional fraction and an optional exponent.
21
+ */
22
+ const FLOAT = /^[+-]?(?:\d[\d,]*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
23
+ /** The symbols `double.Parse` accepts for the special values, compared case-insensitively. */
24
+ const SPECIAL_FLOATS = new Map([
25
+ ["nan", Number.NaN],
26
+ ["infinity", Number.POSITIVE_INFINITY],
27
+ ["+infinity", Number.POSITIVE_INFINITY],
28
+ ["-infinity", Number.NEGATIVE_INFINITY],
29
+ ["∞", Number.POSITIVE_INFINITY],
30
+ ["+∞", Number.POSITIVE_INFINITY],
31
+ ["-∞", Number.NEGATIVE_INFINITY],
32
+ ]);
33
+ /** Mirrors `int.TryParse(string, out int)`. */
34
+ export function tryParseInt32(text) {
35
+ const integer = parseInteger(text);
36
+ return integer !== null && integer >= INT32_MIN && integer <= INT32_MAX
37
+ ? [true, Number(integer)]
38
+ : [false, 0];
39
+ }
40
+ /**
41
+ * Mirrors `long.TryParse(string, out long)`. The range check is exact; the value is a
42
+ * JavaScript `number`, so magnitudes above `Number.MAX_SAFE_INTEGER` lose precision, as
43
+ * every `long` does in the generated code.
44
+ */
45
+ export function tryParseInt64(text) {
46
+ const integer = parseInteger(text);
47
+ return integer !== null && integer >= INT64_MIN && integer <= INT64_MAX
48
+ ? [true, Number(integer)]
49
+ : [false, 0];
50
+ }
51
+ /**
52
+ * Mirrors `double.TryParse(string, out double)` (and `float.TryParse`, whose values the
53
+ * generated code holds as `number` too). A value beyond the `double` range parses to
54
+ * an infinity, as it does since .NET Core 3.0.
55
+ */
56
+ export function tryParseFloat64(text) {
57
+ const trimmed = trimNumberWhitespace(text);
58
+ if (trimmed === null) {
59
+ return [false, 0];
60
+ }
61
+ const special = SPECIAL_FLOATS.get(trimmed.toLowerCase());
62
+ if (special !== undefined) {
63
+ return [true, special];
64
+ }
65
+ return FLOAT.test(trimmed) ? [true, Number(trimmed.replace(/,/g, ""))] : [false, 0];
66
+ }
67
+ /**
68
+ * Mirrors `bool.TryParse(string, out bool)`: `true` / `false` in any letter case, around
69
+ * whitespace (JavaScript's `\s`, close to .NET's `char.IsWhiteSpace`) and `\0` characters.
70
+ */
71
+ export function tryParseBoolean(text) {
72
+ const word = text?.replace(/^[\s\0]+|[\s\0]+$/g, "").toLowerCase();
73
+ if (word === "true") {
74
+ return [true, true];
75
+ }
76
+ return [word === "false", false];
77
+ }
78
+ /** The integer `text` spells, or `null` when it is not an integer. */
79
+ function parseInteger(text) {
80
+ const trimmed = trimNumberWhitespace(text);
81
+ return trimmed !== null && INTEGER.test(trimmed) ? BigInt(trimmed) : null;
82
+ }
83
+ /**
84
+ * `text` without the whitespace .NET allows around a number (and the trailing `\0`
85
+ * characters it tolerates), or `null` when nothing is left.
86
+ */
87
+ function trimNumberWhitespace(text) {
88
+ const trimmed = text?.replace(/^[\t\n\v\f\r ]+|[\t\n\v\f\r \0]+$/g, "") ?? "";
89
+ return trimmed.length > 0 ? trimmed : null;
90
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Non-destructive record update — the TypeScript side of C#'s
3
+ * `source with { X = value }`.
4
+ *
5
+ * C# compiles `with` to the record's copy constructor (a member-wise clone that
6
+ * does not run the primary constructor) followed by the `init` assignments.
7
+ * Mirroring that, the copy keeps the source's prototype and every own
8
+ * enumerable field — including members the primary constructor does not take —
9
+ * and then applies every own key of `overrides`: the generated call passes
10
+ * exactly the members the `with` assigns. A key that is absent keeps the copied
11
+ * value. A key that is present is an assignment even when its value is
12
+ * `undefined` — an absent optional field of a `[PlainObject]` value, read as
13
+ * C# `null` — so it sets the member to `null`, never back to the copied value.
14
+ * A generated `with` only assigns `null` where C# can, so a non-nullable member
15
+ * never receives one; a hand-written caller passing `undefined` for such a
16
+ * member gets `null` too.
17
+ *
18
+ * An override is assigned on the copy, so a member declared with an accessor
19
+ * pair runs its setter. An override naming a member the copy cannot be
20
+ * assigned — a getter without a setter, or a non-writable property — is
21
+ * skipped: C# rejects `with` on computed members, and a property whose custom
22
+ * `init` body is not transpiled has no setter (the compiler reports MS0001 for
23
+ * that `with`). JavaScript `#private` fields are not copied; generated records
24
+ * do not declare them.
25
+ */
26
+ export declare function copyRecordWith<T extends object>(source: T, overrides?: Partial<T>): T;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Non-destructive record update — the TypeScript side of C#'s
3
+ * `source with { X = value }`.
4
+ *
5
+ * C# compiles `with` to the record's copy constructor (a member-wise clone that
6
+ * does not run the primary constructor) followed by the `init` assignments.
7
+ * Mirroring that, the copy keeps the source's prototype and every own
8
+ * enumerable field — including members the primary constructor does not take —
9
+ * and then applies every own key of `overrides`: the generated call passes
10
+ * exactly the members the `with` assigns. A key that is absent keeps the copied
11
+ * value. A key that is present is an assignment even when its value is
12
+ * `undefined` — an absent optional field of a `[PlainObject]` value, read as
13
+ * C# `null` — so it sets the member to `null`, never back to the copied value.
14
+ * A generated `with` only assigns `null` where C# can, so a non-nullable member
15
+ * never receives one; a hand-written caller passing `undefined` for such a
16
+ * member gets `null` too.
17
+ *
18
+ * An override is assigned on the copy, so a member declared with an accessor
19
+ * pair runs its setter. An override naming a member the copy cannot be
20
+ * assigned — a getter without a setter, or a non-writable property — is
21
+ * skipped: C# rejects `with` on computed members, and a property whose custom
22
+ * `init` body is not transpiled has no setter (the compiler reports MS0001 for
23
+ * that `with`). JavaScript `#private` fields are not copied; generated records
24
+ * do not declare them.
25
+ */
26
+ export function copyRecordWith(source, overrides) {
27
+ const copy = Object.create(Object.getPrototypeOf(source));
28
+ Object.assign(copy, source);
29
+ if (overrides !== undefined) {
30
+ assignOverrides(copy, overrides);
31
+ }
32
+ return copy;
33
+ }
34
+ function assignOverrides(target, overrides) {
35
+ for (const key of Object.keys(overrides)) {
36
+ if (isAssignable(target, key)) {
37
+ const value = overrides[key] ?? null;
38
+ target[key] = value;
39
+ }
40
+ }
41
+ }
42
+ /** Whether assigning `key` on `target` would succeed rather than throw. */
43
+ function isAssignable(target, key) {
44
+ const descriptor = findPropertyDescriptor(target, key);
45
+ if (descriptor === undefined) {
46
+ return true;
47
+ }
48
+ if (descriptor.get !== undefined || descriptor.set !== undefined) {
49
+ return descriptor.set !== undefined;
50
+ }
51
+ return descriptor.writable === true;
52
+ }
53
+ function findPropertyDescriptor(target, key) {
54
+ for (let current = target; current !== null; current = Object.getPrototypeOf(current)) {
55
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
56
+ if (descriptor !== undefined) {
57
+ return descriptor;
58
+ }
59
+ }
60
+ return undefined;
61
+ }
@@ -41,4 +41,12 @@ export declare namespace UUID {
41
41
  * regular expression match, not full RFC 4122 version/variant validation.
42
42
  */
43
43
  function isUuid(value: unknown): value is UUID;
44
+ /**
45
+ * Parses a GUID string the way `Guid.TryParse(string, out Guid)` does: the `D`
46
+ * (`8-4-4-4-12`), `N` (32 digits), `B` (`{D}`) and `P` (`(D)`) formats, case-insensitive,
47
+ * with surrounding whitespace ignored. A match is normalized to the lowercase `D` form,
48
+ * the text C#'s `Guid.ToString()` produces; anything else yields `[false, UUID.empty]`.
49
+ * The `X` (hexadecimal braces) format is not supported.
50
+ */
51
+ function tryParse(text: string | null | undefined): readonly [found: boolean, value: UUID];
44
52
  }
@@ -46,4 +46,38 @@ export var UUID;
46
46
  return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$|^[0-9a-fA-F]{32}$/.test(value);
47
47
  }
48
48
  UUID.isUuid = isUuid;
49
+ /**
50
+ * Parses a GUID string the way `Guid.TryParse(string, out Guid)` does: the `D`
51
+ * (`8-4-4-4-12`), `N` (32 digits), `B` (`{D}`) and `P` (`(D)`) formats, case-insensitive,
52
+ * with surrounding whitespace ignored. A match is normalized to the lowercase `D` form,
53
+ * the text C#'s `Guid.ToString()` produces; anything else yields `[false, UUID.empty]`.
54
+ * The `X` (hexadecimal braces) format is not supported.
55
+ */
56
+ function tryParse(text) {
57
+ const digits = guidDigits(text?.trim() ?? "");
58
+ if (digits === null) {
59
+ return [false, UUID.empty];
60
+ }
61
+ const canonical = [
62
+ digits.slice(0, 8),
63
+ digits.slice(8, 12),
64
+ digits.slice(12, 16),
65
+ digits.slice(16, 20),
66
+ digits.slice(20),
67
+ ].join("-");
68
+ return [true, canonical.toLowerCase()];
69
+ }
70
+ UUID.tryParse = tryParse;
71
+ const HEX_DIGITS = /^[0-9a-fA-F]{32}$/;
72
+ const HYPHENATED = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
73
+ const ENCLOSURES = { "{": "}", "(": ")" };
74
+ /** The 32 hex digits of a `D`, `N`, `B` or `P` GUID string, or `null`. */
75
+ function guidDigits(text) {
76
+ if (HEX_DIGITS.test(text)) {
77
+ return text;
78
+ }
79
+ const closing = ENCLOSURES[text.charAt(0)];
80
+ const inner = closing !== undefined && text.endsWith(closing) ? text.slice(1, -1) : text;
81
+ return HYPHENATED.test(inner) ? inner.replace(/-/g, "") : null;
82
+ }
49
83
  })(UUID || (UUID = {}));
@@ -1 +1 @@
1
- export * from "./primitive-type-checks";
1
+ export * from "./primitive-type-checks.ts";
@@ -1 +1 @@
1
- export * from "./primitive-type-checks";
1
+ export * from "./primitive-type-checks.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metano-runtime",
3
- "version": "2.6.1",
3
+ "version": "2.7.1",
4
4
  "type": "module",
5
5
  "module": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -20,7 +20,9 @@
20
20
  ".": "./dist/index.js",
21
21
  "./system/json": "./dist/system/json/index.js",
22
22
  "./system/linq": "./dist/system/linq/index.js",
23
- "./*": "./dist/*"
23
+ "./package.json": "./package.json",
24
+ "./*.js": "./dist/*.js",
25
+ "./*": "./dist/*.js"
24
26
  },
25
27
  "imports": {
26
28
  "#/*": [
@@ -37,9 +39,6 @@
37
39
  "@typescript/native-preview": "^7.0.0-dev.20260225.1",
38
40
  "bun-types": "^1.3.11"
39
41
  },
40
- "peerDependencies": {
41
- "@typescript/native-preview": "^7"
42
- },
43
42
  "dependencies": {
44
43
  "@js-temporal/polyfill": "^0.5.1"
45
44
  }