metano-runtime 0.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 (85) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +2 -0
  3. package/dist/system/collections/hash-set.d.ts +29 -0
  4. package/dist/system/collections/hash-set.js +138 -0
  5. package/dist/system/collections/immutable-collection.d.ts +31 -0
  6. package/dist/system/collections/immutable-collection.js +58 -0
  7. package/dist/system/collections/index.d.ts +3 -0
  8. package/dist/system/collections/index.js +3 -0
  9. package/dist/system/collections/list-helpers.d.ts +43 -0
  10. package/dist/system/collections/list-helpers.js +58 -0
  11. package/dist/system/equality.d.ts +38 -0
  12. package/dist/system/equality.js +178 -0
  13. package/dist/system/hash-code.d.ts +35 -0
  14. package/dist/system/hash-code.js +177 -0
  15. package/dist/system/index.d.ts +6 -0
  16. package/dist/system/index.js +6 -0
  17. package/dist/system/json/converters.d.ts +22 -0
  18. package/dist/system/json/converters.js +261 -0
  19. package/dist/system/json/index.d.ts +5 -0
  20. package/dist/system/json/index.js +4 -0
  21. package/dist/system/json/json-serializer.d.ts +39 -0
  22. package/dist/system/json/json-serializer.js +57 -0
  23. package/dist/system/json/property-naming-policy.d.ts +14 -0
  24. package/dist/system/json/property-naming-policy.js +116 -0
  25. package/dist/system/json/serializer-context.d.ts +30 -0
  26. package/dist/system/json/serializer-context.js +38 -0
  27. package/dist/system/json/types.d.ts +85 -0
  28. package/dist/system/json/types.js +1 -0
  29. package/dist/system/linq/append-enumerable.d.ts +8 -0
  30. package/dist/system/linq/append-enumerable.js +15 -0
  31. package/dist/system/linq/compare-keys.d.ts +7 -0
  32. package/dist/system/linq/compare-keys.js +31 -0
  33. package/dist/system/linq/concat-enumerable.d.ts +8 -0
  34. package/dist/system/linq/concat-enumerable.js +15 -0
  35. package/dist/system/linq/distinct-by-enumerable.d.ts +8 -0
  36. package/dist/system/linq/distinct-by-enumerable.js +21 -0
  37. package/dist/system/linq/distinct-enumerable.d.ts +7 -0
  38. package/dist/system/linq/distinct-enumerable.js +19 -0
  39. package/dist/system/linq/enumerable-base.d.ts +98 -0
  40. package/dist/system/linq/enumerable-base.js +306 -0
  41. package/dist/system/linq/enumerable.d.ts +16 -0
  42. package/dist/system/linq/enumerable.js +33 -0
  43. package/dist/system/linq/except-enumerable.d.ts +8 -0
  44. package/dist/system/linq/except-enumerable.js +22 -0
  45. package/dist/system/linq/group-by-enumerable.d.ts +8 -0
  46. package/dist/system/linq/group-by-enumerable.js +31 -0
  47. package/dist/system/linq/index.d.ts +23 -0
  48. package/dist/system/linq/index.js +70 -0
  49. package/dist/system/linq/intersect-enumerable.d.ts +8 -0
  50. package/dist/system/linq/intersect-enumerable.js +22 -0
  51. package/dist/system/linq/order-by-enumerable.d.ts +9 -0
  52. package/dist/system/linq/order-by-enumerable.js +22 -0
  53. package/dist/system/linq/prepend-enumerable.d.ts +8 -0
  54. package/dist/system/linq/prepend-enumerable.js +15 -0
  55. package/dist/system/linq/reverse-enumerable.d.ts +7 -0
  56. package/dist/system/linq/reverse-enumerable.js +15 -0
  57. package/dist/system/linq/select-enumerable.d.ts +8 -0
  58. package/dist/system/linq/select-enumerable.js +17 -0
  59. package/dist/system/linq/select-many-enumerable.d.ts +8 -0
  60. package/dist/system/linq/select-many-enumerable.js +17 -0
  61. package/dist/system/linq/skip-enumerable.d.ts +8 -0
  62. package/dist/system/linq/skip-enumerable.js +21 -0
  63. package/dist/system/linq/skip-while-enumerable.d.ts +8 -0
  64. package/dist/system/linq/skip-while-enumerable.js +21 -0
  65. package/dist/system/linq/source-enumerable.d.ts +7 -0
  66. package/dist/system/linq/source-enumerable.js +12 -0
  67. package/dist/system/linq/take-enumerable.d.ts +8 -0
  68. package/dist/system/linq/take-enumerable.js +20 -0
  69. package/dist/system/linq/take-while-enumerable.d.ts +8 -0
  70. package/dist/system/linq/take-while-enumerable.js +19 -0
  71. package/dist/system/linq/then-by-enumerable.d.ts +9 -0
  72. package/dist/system/linq/then-by-enumerable.js +61 -0
  73. package/dist/system/linq/union-enumerable.d.ts +8 -0
  74. package/dist/system/linq/union-enumerable.js +27 -0
  75. package/dist/system/linq/where-enumerable.d.ts +8 -0
  76. package/dist/system/linq/where-enumerable.js +18 -0
  77. package/dist/system/linq/zip-enumerable.d.ts +9 -0
  78. package/dist/system/linq/zip-enumerable.js +24 -0
  79. package/dist/system/temporal-helpers.d.ts +10 -0
  80. package/dist/system/temporal-helpers.js +12 -0
  81. package/dist/type-checking/index.d.ts +1 -0
  82. package/dist/type-checking/index.js +1 -0
  83. package/dist/type-checking/primitive-type-checks.d.ts +33 -0
  84. package/dist/type-checking/primitive-type-checks.js +74 -0
  85. package/package.json +44 -0
@@ -0,0 +1,2 @@
1
+ export * from "./system";
2
+ export * from "./type-checking";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./system";
2
+ export * from "./type-checking";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * A HashSet implementation that uses equals()/hashCode() for value-based
3
+ * equality when available, falling back to === for primitives.
4
+ *
5
+ * Inspired by Kotlin/JS and Fable's approach to bridging .NET equality
6
+ * semantics to JavaScript.
7
+ */
8
+ export declare class HashSet<T> implements Iterable<T> {
9
+ private _buckets;
10
+ private _size;
11
+ constructor(items?: Iterable<T>);
12
+ get size(): number;
13
+ add(item: T): this;
14
+ has(item: T): boolean;
15
+ delete(item: T): boolean;
16
+ clear(): void;
17
+ forEach(callback: (item: T) => void): void;
18
+ values(): IterableIterator<T>;
19
+ [Symbol.iterator](): Iterator<T>;
20
+ toArray(): T[];
21
+ private _primitiveSet?;
22
+ private _isPrimitive;
23
+ private _getPrimitiveSet;
24
+ private _addPrimitive;
25
+ private _hasPrimitive;
26
+ private _deletePrimitive;
27
+ private _getHash;
28
+ private _areEqual;
29
+ }
@@ -0,0 +1,138 @@
1
+ import { HashCode } from "../hash-code.js";
2
+ /**
3
+ * A HashSet implementation that uses equals()/hashCode() for value-based
4
+ * equality when available, falling back to === for primitives.
5
+ *
6
+ * Inspired by Kotlin/JS and Fable's approach to bridging .NET equality
7
+ * semantics to JavaScript.
8
+ */
9
+ export class HashSet {
10
+ _buckets = new Map();
11
+ _size = 0;
12
+ constructor(items) {
13
+ if (items) {
14
+ for (const item of items) {
15
+ this.add(item);
16
+ }
17
+ }
18
+ }
19
+ get size() {
20
+ return this._size;
21
+ }
22
+ add(item) {
23
+ if (this._isPrimitive(item)) {
24
+ return this._addPrimitive(item);
25
+ }
26
+ const hash = this._getHash(item);
27
+ const bucket = this._buckets.get(hash);
28
+ if (!bucket) {
29
+ this._buckets.set(hash, [item]);
30
+ this._size++;
31
+ return this;
32
+ }
33
+ if (!bucket.some((existing) => this._areEqual(existing, item))) {
34
+ bucket.push(item);
35
+ this._size++;
36
+ }
37
+ return this;
38
+ }
39
+ has(item) {
40
+ if (this._isPrimitive(item)) {
41
+ return this._hasPrimitive(item);
42
+ }
43
+ const hash = this._getHash(item);
44
+ const bucket = this._buckets.get(hash);
45
+ return bucket?.some((existing) => this._areEqual(existing, item)) ?? false;
46
+ }
47
+ delete(item) {
48
+ if (this._isPrimitive(item)) {
49
+ return this._deletePrimitive(item);
50
+ }
51
+ const hash = this._getHash(item);
52
+ const bucket = this._buckets.get(hash);
53
+ if (!bucket)
54
+ return false;
55
+ const index = bucket.findIndex((existing) => this._areEqual(existing, item));
56
+ if (index === -1)
57
+ return false;
58
+ bucket.splice(index, 1);
59
+ if (bucket.length === 0)
60
+ this._buckets.delete(hash);
61
+ this._size--;
62
+ return true;
63
+ }
64
+ clear() {
65
+ this._buckets.clear();
66
+ this._size = 0;
67
+ }
68
+ forEach(callback) {
69
+ for (const item of this) {
70
+ callback(item);
71
+ }
72
+ }
73
+ *values() {
74
+ if (this._primitiveSet) {
75
+ yield* this._primitiveSet;
76
+ }
77
+ for (const bucket of this._buckets.values()) {
78
+ yield* bucket;
79
+ }
80
+ }
81
+ *[Symbol.iterator]() {
82
+ yield* this.values();
83
+ }
84
+ toArray() {
85
+ return [...this];
86
+ }
87
+ // ─── Primitive fast path ─────────────────────────────────
88
+ // Primitives use a dedicated bucket (hash = NaN) with a native Set
89
+ // for O(1) lookup via ===.
90
+ _primitiveSet;
91
+ _isPrimitive(item) {
92
+ const t = typeof item;
93
+ return (t === "string" || t === "number" || t === "boolean" || item === null || item === undefined);
94
+ }
95
+ _getPrimitiveSet() {
96
+ return (this._primitiveSet ??= new Set());
97
+ }
98
+ _addPrimitive(item) {
99
+ const set = this._getPrimitiveSet();
100
+ const before = set.size;
101
+ set.add(item);
102
+ if (set.size > before)
103
+ this._size++;
104
+ return this;
105
+ }
106
+ _hasPrimitive(item) {
107
+ return this._primitiveSet?.has(item) ?? false;
108
+ }
109
+ _deletePrimitive(item) {
110
+ if (!this._primitiveSet)
111
+ return false;
112
+ const deleted = this._primitiveSet.delete(item);
113
+ if (deleted)
114
+ this._size--;
115
+ return deleted;
116
+ }
117
+ // ─── Equality helpers ────────────────────────────────────
118
+ _getHash(item) {
119
+ if (typeof item === "object" &&
120
+ item !== null &&
121
+ "hashCode" in item &&
122
+ typeof item.hashCode === "function") {
123
+ return item.hashCode();
124
+ }
125
+ return HashCode.combine(item);
126
+ }
127
+ _areEqual(a, b) {
128
+ if (a === b)
129
+ return true;
130
+ if (typeof a === "object" &&
131
+ a !== null &&
132
+ "equals" in a &&
133
+ typeof a.equals === "function") {
134
+ return a.equals(b);
135
+ }
136
+ return false;
137
+ }
138
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Pure helper functions for immutable array operations. Each function takes a
3
+ * source array and returns a NEW array — the original is never mutated. This
4
+ * mirrors the contract of C#'s `ImmutableList<T>` / `ImmutableArray<T>`.
5
+ *
6
+ * The compiler's declarative mappings in `Metano/Runtime/ImmutableCollections.cs`
7
+ * lower C# calls like `list.Add(item)` to `ImmutableCollection.add(list, item)`.
8
+ * Using a namespace keeps the generated code readable and the helpers debuggable
9
+ * (named functions in stack traces), while the underlying representation stays as
10
+ * a plain JS array — no wrapper, no serialization friction.
11
+ */
12
+ export declare namespace ImmutableCollection {
13
+ /** Returns a new array with `item` appended at the end. */
14
+ function add<T>(array: readonly T[], item: T): T[];
15
+ /** Returns a new array with all items from `other` appended. */
16
+ function addRange<T>(array: readonly T[], other: readonly T[]): T[];
17
+ /** Returns a new array with `item` inserted at `index`. */
18
+ function insert<T>(array: readonly T[], index: number, item: T): T[];
19
+ /** Returns a new array with the element at `index` removed. */
20
+ function removeAt<T>(array: readonly T[], index: number): T[];
21
+ /**
22
+ * Returns a new array with the first occurrence of `item` removed, or the
23
+ * original array unchanged when the item is not found. Uses reference
24
+ * equality (indexOf) — same as the C# default equality for reference types.
25
+ */
26
+ function remove<T>(array: readonly T[], item: T): readonly T[];
27
+ /** Returns an empty array. Equivalent to `ImmutableList<T>.Clear()`. */
28
+ function clear<T>(): T[];
29
+ /** Returns a new array with the element at `index` replaced by `item`. */
30
+ function set<T>(array: readonly T[], index: number, item: T): T[];
31
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Pure helper functions for immutable array operations. Each function takes a
3
+ * source array and returns a NEW array — the original is never mutated. This
4
+ * mirrors the contract of C#'s `ImmutableList<T>` / `ImmutableArray<T>`.
5
+ *
6
+ * The compiler's declarative mappings in `Metano/Runtime/ImmutableCollections.cs`
7
+ * lower C# calls like `list.Add(item)` to `ImmutableCollection.add(list, item)`.
8
+ * Using a namespace keeps the generated code readable and the helpers debuggable
9
+ * (named functions in stack traces), while the underlying representation stays as
10
+ * a plain JS array — no wrapper, no serialization friction.
11
+ */
12
+ export var ImmutableCollection;
13
+ (function (ImmutableCollection) {
14
+ /** Returns a new array with `item` appended at the end. */
15
+ function add(array, item) {
16
+ return [...array, item];
17
+ }
18
+ ImmutableCollection.add = add;
19
+ /** Returns a new array with all items from `other` appended. */
20
+ function addRange(array, other) {
21
+ return [...array, ...other];
22
+ }
23
+ ImmutableCollection.addRange = addRange;
24
+ /** Returns a new array with `item` inserted at `index`. */
25
+ function insert(array, index, item) {
26
+ return [...array.slice(0, index), item, ...array.slice(index)];
27
+ }
28
+ ImmutableCollection.insert = insert;
29
+ /** Returns a new array with the element at `index` removed. */
30
+ function removeAt(array, index) {
31
+ return [...array.slice(0, index), ...array.slice(index + 1)];
32
+ }
33
+ ImmutableCollection.removeAt = removeAt;
34
+ /**
35
+ * Returns a new array with the first occurrence of `item` removed, or the
36
+ * original array unchanged when the item is not found. Uses reference
37
+ * equality (indexOf) — same as the C# default equality for reference types.
38
+ */
39
+ function remove(array, item) {
40
+ const i = array.indexOf(item);
41
+ if (i < 0)
42
+ return array;
43
+ return [...array.slice(0, i), ...array.slice(i + 1)];
44
+ }
45
+ ImmutableCollection.remove = remove;
46
+ /** Returns an empty array. Equivalent to `ImmutableList<T>.Clear()`. */
47
+ function clear() {
48
+ return [];
49
+ }
50
+ ImmutableCollection.clear = clear;
51
+ /** Returns a new array with the element at `index` replaced by `item`. */
52
+ function set(array, index, item) {
53
+ const copy = [...array];
54
+ copy[index] = item;
55
+ return copy;
56
+ }
57
+ ImmutableCollection.set = set;
58
+ })(ImmutableCollection || (ImmutableCollection = {}));
@@ -0,0 +1,3 @@
1
+ export * from "./hash-set.ts";
2
+ export * from "./immutable-collection.ts";
3
+ export * from "./list-helpers.ts";
@@ -0,0 +1,3 @@
1
+ export * from "./hash-set.js";
2
+ export * from "./immutable-collection.js";
3
+ export * from "./list-helpers.js";
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Runtime helpers for the C# List<T> / IList<T> / ICollection<T> family of methods
3
+ * whose lowering can't be expressed as a simple inline JS expression. The compiler
4
+ * imports these via the [MapMethod(..., RuntimeImports = "...")] declarative mappings
5
+ * under Metano/Runtime/Lists.cs and ImmutableCollections.cs.
6
+ *
7
+ * The two flavors are kept in the same file because they share an underlying
8
+ * representation (plain JS arrays); only the contract differs:
9
+ *
10
+ * - The mutable helpers (`listRemove`, future siblings) operate in place and return a
11
+ * status value, mirroring the C# `bool` return of `List<T>.Remove`.
12
+ * - The immutable helpers (`immutableInsert`, `immutableRemoveAt`, `immutableRemove`)
13
+ * never mutate the input — they return a fresh array, mirroring the
14
+ * `ImmutableList<T>` / `ImmutableArray<T>` contract.
15
+ */
16
+ /**
17
+ * Mutating remove for arrays used as `List<T>` / `IList<T>` / `ICollection<T>`. Finds
18
+ * the first occurrence of `item` (via `Array.indexOf`, so reference equality for
19
+ * objects), splices it out in place, and returns true if anything was removed.
20
+ * Returns false when the item isn't present, leaving `arr` untouched.
21
+ *
22
+ * Mirrors `System.Collections.Generic.List<T>.Remove(T item)` semantics.
23
+ */
24
+ export declare function listRemove<T>(arr: T[], item: T): boolean;
25
+ /**
26
+ * Returns a new array with `item` inserted at `index`. The original array is left
27
+ * untouched. Mirrors `ImmutableList<T>.Insert(int index, T item)` and
28
+ * `ImmutableArray<T>.Insert(int index, T item)`.
29
+ */
30
+ export declare function immutableInsert<T>(arr: readonly T[], index: number, item: T): T[];
31
+ /**
32
+ * Returns a new array with the element at `index` removed. The original array is left
33
+ * untouched. Mirrors `ImmutableList<T>.RemoveAt(int index)` and
34
+ * `ImmutableArray<T>.RemoveAt(int index)`.
35
+ */
36
+ export declare function immutableRemoveAt<T>(arr: readonly T[], index: number): T[];
37
+ /**
38
+ * Returns a new array with the first occurrence of `item` removed, or the original
39
+ * array unchanged when the item is not present. Mirrors `ImmutableList<T>.Remove(T)`
40
+ * and `ImmutableArray<T>.Remove(T)`, both of which return the receiver when the
41
+ * lookup misses (since immutable instances can be safely shared).
42
+ */
43
+ export declare function immutableRemove<T>(arr: readonly T[], item: T): readonly T[];
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Runtime helpers for the C# List<T> / IList<T> / ICollection<T> family of methods
3
+ * whose lowering can't be expressed as a simple inline JS expression. The compiler
4
+ * imports these via the [MapMethod(..., RuntimeImports = "...")] declarative mappings
5
+ * under Metano/Runtime/Lists.cs and ImmutableCollections.cs.
6
+ *
7
+ * The two flavors are kept in the same file because they share an underlying
8
+ * representation (plain JS arrays); only the contract differs:
9
+ *
10
+ * - The mutable helpers (`listRemove`, future siblings) operate in place and return a
11
+ * status value, mirroring the C# `bool` return of `List<T>.Remove`.
12
+ * - The immutable helpers (`immutableInsert`, `immutableRemoveAt`, `immutableRemove`)
13
+ * never mutate the input — they return a fresh array, mirroring the
14
+ * `ImmutableList<T>` / `ImmutableArray<T>` contract.
15
+ */
16
+ /**
17
+ * Mutating remove for arrays used as `List<T>` / `IList<T>` / `ICollection<T>`. Finds
18
+ * the first occurrence of `item` (via `Array.indexOf`, so reference equality for
19
+ * objects), splices it out in place, and returns true if anything was removed.
20
+ * Returns false when the item isn't present, leaving `arr` untouched.
21
+ *
22
+ * Mirrors `System.Collections.Generic.List<T>.Remove(T item)` semantics.
23
+ */
24
+ export function listRemove(arr, item) {
25
+ const i = arr.indexOf(item);
26
+ if (i < 0)
27
+ return false;
28
+ arr.splice(i, 1);
29
+ return true;
30
+ }
31
+ /**
32
+ * Returns a new array with `item` inserted at `index`. The original array is left
33
+ * untouched. Mirrors `ImmutableList<T>.Insert(int index, T item)` and
34
+ * `ImmutableArray<T>.Insert(int index, T item)`.
35
+ */
36
+ export function immutableInsert(arr, index, item) {
37
+ return [...arr.slice(0, index), item, ...arr.slice(index)];
38
+ }
39
+ /**
40
+ * Returns a new array with the element at `index` removed. The original array is left
41
+ * untouched. Mirrors `ImmutableList<T>.RemoveAt(int index)` and
42
+ * `ImmutableArray<T>.RemoveAt(int index)`.
43
+ */
44
+ export function immutableRemoveAt(arr, index) {
45
+ return [...arr.slice(0, index), ...arr.slice(index + 1)];
46
+ }
47
+ /**
48
+ * Returns a new array with the first occurrence of `item` removed, or the original
49
+ * array unchanged when the item is not present. Mirrors `ImmutableList<T>.Remove(T)`
50
+ * and `ImmutableArray<T>.Remove(T)`, both of which return the receiver when the
51
+ * lookup misses (since immutable instances can be safely shared).
52
+ */
53
+ export function immutableRemove(arr, item) {
54
+ const i = arr.indexOf(item);
55
+ if (i < 0)
56
+ return arr;
57
+ return [...arr.slice(0, i), ...arr.slice(i + 1)];
58
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Returns true when `a` and `b` are deeply equal. Comparison rules, in order:
3
+ *
4
+ * 1. Reference identity (`a === b`) wins immediately.
5
+ * 2. `null` and `undefined` are equal to themselves but not to anything else.
6
+ * 3. Different `typeof` → not equal.
7
+ * 4. `NaN` equals `NaN` (unlike the `===` operator).
8
+ * 5. Other primitives use `===`.
9
+ * 6. Objects with a custom `equals(other)` method delegate to it (record classes).
10
+ * 7. `Array`s compare element-wise in order.
11
+ * 8. `Map`s compare by size, then by key→value pairs (order-independent on the keys).
12
+ * 9. `Set`s compare by size, then by membership (order-independent).
13
+ * 10. `Date`s compare by `getTime()`.
14
+ * 11. Plain objects compare structurally on their own enumerable string keys.
15
+ *
16
+ * Cycles in the input graph are NOT detected — pass cyclic structures at your own risk
17
+ * (the same caveat as `JSON.stringify`). For real-world record/value-object data this
18
+ * has not been a problem.
19
+ */
20
+ export declare function equals(a: unknown, b: unknown): boolean;
21
+ /**
22
+ * Computes a deep hash code for an arbitrary value. The result is consistent with
23
+ * `equals(a, b)` — values that compare equal under `equals` produce the same hash.
24
+ *
25
+ * Rules:
26
+ * 1. `null` / `undefined` → 0.
27
+ * 2. Objects with a custom `hashCode()` method delegate to it.
28
+ * 3. Primitives go through `HashCode.combine`.
29
+ * 4. Arrays hash size + each element in order.
30
+ * 5. `Map` and `Set` hash with an order-independent XOR fold so two Maps/Sets with the
31
+ * same content but different insertion order get the same hash.
32
+ * 6. `Date`s hash their epoch milliseconds.
33
+ * 7. Plain objects hash their enumerable string keys + values, with the keys sorted so
34
+ * insertion order doesn't affect the result.
35
+ *
36
+ * Cycle handling matches `equals` — undefined behavior on cyclic graphs.
37
+ */
38
+ export declare function hashCode(value: unknown): number;
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Deep value-equality and standalone hashing helpers for arbitrary JavaScript values.
3
+ * Mirror the C# .NET semantics: structural equality for compounds, NaN-equals-NaN for
4
+ * floats, custom `equals(other)` / `hashCode()` methods on user types take precedence.
5
+ *
6
+ * These are utility helpers for user code — the compiler does NOT call them. Generated
7
+ * record classes have their own inline `equals(other)` / `hashCode()` methods that
8
+ * compare each captured constructor parameter directly. Use these when you have an
9
+ * arbitrary value of unknown shape and need a structural compare or a content-based
10
+ * hash key (e.g., to feed into a `HashSet<T>` over plain object literals).
11
+ */
12
+ import { HashCode } from "./hash-code.js";
13
+ /**
14
+ * Returns true when `a` and `b` are deeply equal. Comparison rules, in order:
15
+ *
16
+ * 1. Reference identity (`a === b`) wins immediately.
17
+ * 2. `null` and `undefined` are equal to themselves but not to anything else.
18
+ * 3. Different `typeof` → not equal.
19
+ * 4. `NaN` equals `NaN` (unlike the `===` operator).
20
+ * 5. Other primitives use `===`.
21
+ * 6. Objects with a custom `equals(other)` method delegate to it (record classes).
22
+ * 7. `Array`s compare element-wise in order.
23
+ * 8. `Map`s compare by size, then by key→value pairs (order-independent on the keys).
24
+ * 9. `Set`s compare by size, then by membership (order-independent).
25
+ * 10. `Date`s compare by `getTime()`.
26
+ * 11. Plain objects compare structurally on their own enumerable string keys.
27
+ *
28
+ * Cycles in the input graph are NOT detected — pass cyclic structures at your own risk
29
+ * (the same caveat as `JSON.stringify`). For real-world record/value-object data this
30
+ * has not been a problem.
31
+ */
32
+ export function equals(a, b) {
33
+ if (a === b)
34
+ return true;
35
+ if (a == null || b == null)
36
+ return false;
37
+ if (typeof a !== typeof b)
38
+ return false;
39
+ // NaN equals NaN — needed because NaN === NaN is false in JS but the C# equivalent
40
+ // (double.NaN.Equals(double.NaN)) returns true.
41
+ if (typeof a === "number") {
42
+ return Number.isNaN(a) && Number.isNaN(b);
43
+ }
44
+ // Other primitives are settled by the `===` check above; we only get here for objects.
45
+ if (typeof a !== "object")
46
+ return false;
47
+ // Custom equals contract from record/value classes.
48
+ if ("equals" in a && typeof a.equals === "function") {
49
+ return a.equals(b);
50
+ }
51
+ if (Array.isArray(a)) {
52
+ if (!Array.isArray(b))
53
+ return false;
54
+ if (a.length !== b.length)
55
+ return false;
56
+ for (let i = 0; i < a.length; i++) {
57
+ if (!equals(a[i], b[i]))
58
+ return false;
59
+ }
60
+ return true;
61
+ }
62
+ if (Array.isArray(b))
63
+ return false;
64
+ if (a instanceof Map) {
65
+ if (!(b instanceof Map))
66
+ return false;
67
+ if (a.size !== b.size)
68
+ return false;
69
+ for (const [key, value] of a) {
70
+ if (!b.has(key))
71
+ return false;
72
+ if (!equals(value, b.get(key)))
73
+ return false;
74
+ }
75
+ return true;
76
+ }
77
+ if (b instanceof Map)
78
+ return false;
79
+ if (a instanceof Set) {
80
+ if (!(b instanceof Set))
81
+ return false;
82
+ if (a.size !== b.size)
83
+ return false;
84
+ for (const value of a) {
85
+ if (!b.has(value))
86
+ return false;
87
+ }
88
+ return true;
89
+ }
90
+ if (b instanceof Set)
91
+ return false;
92
+ if (a instanceof Date) {
93
+ if (!(b instanceof Date))
94
+ return false;
95
+ return a.getTime() === b.getTime();
96
+ }
97
+ if (b instanceof Date)
98
+ return false;
99
+ // Structural compare on enumerable string keys. Symbol-keyed properties are ignored,
100
+ // matching JSON.stringify and the typical "value object" model.
101
+ const aObj = a;
102
+ const bObj = b;
103
+ const aKeys = Object.keys(aObj);
104
+ const bKeys = Object.keys(bObj);
105
+ if (aKeys.length !== bKeys.length)
106
+ return false;
107
+ for (const key of aKeys) {
108
+ if (!Object.hasOwn(bObj, key))
109
+ return false;
110
+ if (!equals(aObj[key], bObj[key]))
111
+ return false;
112
+ }
113
+ return true;
114
+ }
115
+ /**
116
+ * Computes a deep hash code for an arbitrary value. The result is consistent with
117
+ * `equals(a, b)` — values that compare equal under `equals` produce the same hash.
118
+ *
119
+ * Rules:
120
+ * 1. `null` / `undefined` → 0.
121
+ * 2. Objects with a custom `hashCode()` method delegate to it.
122
+ * 3. Primitives go through `HashCode.combine`.
123
+ * 4. Arrays hash size + each element in order.
124
+ * 5. `Map` and `Set` hash with an order-independent XOR fold so two Maps/Sets with the
125
+ * same content but different insertion order get the same hash.
126
+ * 6. `Date`s hash their epoch milliseconds.
127
+ * 7. Plain objects hash their enumerable string keys + values, with the keys sorted so
128
+ * insertion order doesn't affect the result.
129
+ *
130
+ * Cycle handling matches `equals` — undefined behavior on cyclic graphs.
131
+ */
132
+ export function hashCode(value) {
133
+ if (value == null)
134
+ return 0;
135
+ if (typeof value === "object") {
136
+ // Custom hashCode contract from record/value classes.
137
+ if ("hashCode" in value && typeof value.hashCode === "function") {
138
+ return value.hashCode();
139
+ }
140
+ if (Array.isArray(value)) {
141
+ const hc = new HashCode();
142
+ hc.add(value.length);
143
+ for (const item of value)
144
+ hc.add(hashCode(item));
145
+ return hc.toHashCode();
146
+ }
147
+ if (value instanceof Map) {
148
+ // Order-independent: XOR each (key, value) pair hash. XOR is commutative so the
149
+ // result doesn't depend on insertion order, matching how Map equality works.
150
+ let acc = 0;
151
+ for (const [k, v] of value) {
152
+ acc ^= HashCode.combine2(hashCode(k), hashCode(v));
153
+ }
154
+ return acc;
155
+ }
156
+ if (value instanceof Set) {
157
+ let acc = 0;
158
+ for (const item of value) {
159
+ acc ^= hashCode(item);
160
+ }
161
+ return acc;
162
+ }
163
+ if (value instanceof Date) {
164
+ return hashCode(value.getTime());
165
+ }
166
+ // Plain object: hash sorted keys + values for stable insertion-order independence.
167
+ const obj = value;
168
+ const keys = Object.keys(obj).sort();
169
+ const hc = new HashCode();
170
+ for (const key of keys) {
171
+ hc.add(key);
172
+ hc.add(hashCode(obj[key]));
173
+ }
174
+ return hc.toHashCode();
175
+ }
176
+ // Primitives.
177
+ return HashCode.combine(value);
178
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Port of System.HashCode from .NET (xxHash32-based).
3
+ * Used by Metano-generated record classes for value-based equality.
4
+ *
5
+ * Reference: https://github.com/dotnet/corert/blob/master/src/System.Private.CoreLib/shared/System/HashCode.cs
6
+ * Algorithm: xxHash32 by Yann Collet (BSD 2-Clause)
7
+ */
8
+ /**
9
+ * Accumulator for computing hash codes, modeled after System.HashCode.
10
+ *
11
+ * Usage:
12
+ * ```ts
13
+ * const hc = new HashCode();
14
+ * hc.add(this.x);
15
+ * hc.add(this.y);
16
+ * return hc.toHashCode();
17
+ * ```
18
+ */
19
+ export declare class HashCode {
20
+ private _v1;
21
+ private _v2;
22
+ private _v3;
23
+ private _v4;
24
+ private _queue1;
25
+ private _queue2;
26
+ private _queue3;
27
+ private _length;
28
+ constructor();
29
+ add(value: unknown): void;
30
+ toHashCode(): number;
31
+ static combine(v1: unknown): number;
32
+ static combine2(v1: unknown, v2: unknown): number;
33
+ static combine3(v1: unknown, v2: unknown, v3: unknown): number;
34
+ static combine4(v1: unknown, v2: unknown, v3: unknown, v4: unknown): number;
35
+ }