heavy-reactive 1.0.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 (55) hide show
  1. package/.commitlintrc +2 -0
  2. package/.editorconfig +17 -0
  3. package/.gitattributes +2 -0
  4. package/.github/workflows/check-code.yml +48 -0
  5. package/.github/workflows/lint-commit.yml +15 -0
  6. package/.github/workflows/lint-request.yml +19 -0
  7. package/.github/workflows/release-job.yml +62 -0
  8. package/.husky/commit-msg +18 -0
  9. package/.husky/pre-commit +18 -0
  10. package/.prettierignore +2 -0
  11. package/.prettierrc +9 -0
  12. package/.vscode/extensions.json +3 -0
  13. package/.vscode/settings.json +27 -0
  14. package/.vscode/tasks.json +25 -0
  15. package/CHANGELOG.md +1 -0
  16. package/CONTRIBUTING.md +116 -0
  17. package/GLOSSARY.md +144 -0
  18. package/LICENSE +21 -0
  19. package/README.md +198 -0
  20. package/feature.reactivity/_common/changes.interface.ts +44 -0
  21. package/feature.reactivity/_common/dictionary-changes.interface.ts +54 -0
  22. package/feature.reactivity/_common/observable.interface.ts +22 -0
  23. package/feature.reactivity/_common/set-changes.interface.ts +50 -0
  24. package/feature.reactivity/_common/value-change.interface.ts +54 -0
  25. package/feature.reactivity/_common/value-container.interface.ts +12 -0
  26. package/feature.reactivity/dictionary/reactive-array.class.ts +0 -0
  27. package/feature.reactivity/dictionary/reactive-map.class.ts +0 -0
  28. package/feature.reactivity/dictionary/reactive-object.class.ts +0 -0
  29. package/feature.reactivity/reactivity-disabled.error.ts +11 -0
  30. package/feature.reactivity/reactivity.module.ts +458 -0
  31. package/feature.reactivity/readonly-access.error.ts +13 -0
  32. package/feature.reactivity/set/$difference.class.ts +272 -0
  33. package/feature.reactivity/set/$intersection.class.ts +137 -0
  34. package/feature.reactivity/set/$set.class.ts +1022 -0
  35. package/feature.reactivity/set/$union.class.ts +74 -0
  36. package/feature.reactivity/set/_combination/$combination.class.ts +179 -0
  37. package/feature.reactivity/set/_combination/$variadic-combination.class.ts +235 -0
  38. package/feature.reactivity/set/feature.projection-sets/$complement-via-set.class.ts +159 -0
  39. package/feature.reactivity/set/feature.projection-sets/$complement-via-val.class.ts +126 -0
  40. package/feature.reactivity/set/feature.projection-sets/$set-from-any.class.ts +382 -0
  41. package/feature.reactivity/set/feature.projection-sets/$set-from-set.class.ts +90 -0
  42. package/feature.reactivity/set/feature.projection-sets/$subset-via-set.class.ts +123 -0
  43. package/feature.reactivity/set/feature.projection-sets/$subset-via-val.class.ts +114 -0
  44. package/feature.reactivity/set/feature.projection-sets/feature.reactive-delta-buffer/delta-buffer-for-set.class.ts +235 -0
  45. package/feature.reactivity/set/feature.projection-sets/feature.reactive-delta-buffer/delta-buffer-for-value.class.ts +193 -0
  46. package/feature.reactivity/set/feature.projection-sets/types/dependency-set-resolver.type.ts +19 -0
  47. package/feature.reactivity/set/feature.projection-sets/types/dependency-value-resolver.type.ts +20 -0
  48. package/feature.reactivity/value/$value.class.ts +237 -0
  49. package/feature.set/index.ts +3 -0
  50. package/feature.set/set.prototype.difference.polyfill.ts +7 -0
  51. package/feature.set/set.prototype.intersection.polyfill.ts +6 -0
  52. package/feature.set/set.prototype.union.polyfill.ts +11 -0
  53. package/feature.typescript/maybe-promise.type.ts +1 -0
  54. package/package.json +51 -0
  55. package/tsconfig.json +116 -0
package/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # Heavy Reactive
2
+
3
+ Lightweight TypeScript primitives for reactive programming with heavy computations, optimized to handle hundreds of thousands of objects in real-time streams. The library provides explicit control over complex data flows through subscription-based patterns while avoiding magic and overhead. It supports cancellation, lazy evaluation, and efficient set operations at scale without garbage collection pressure. Designed for seamless integration in any architecture, it works without global state or framework dependencies.
4
+
5
+ The core maintains constant-time operations even with massive datasets, processing only what changes through granular differential updates. You get precise memory control and zero-implicit reactivity waterfalls while working with plain JavaScript objects.
6
+
7
+ ## 🚀 Getting Started
8
+
9
+ Install the library:
10
+
11
+ ```bash
12
+ npm install @your-scope/reactive-state
13
+ ```
14
+
15
+ Import the reactive primitives:
16
+
17
+ ```ts
18
+ import { $value, $set, $intersectionSets, $unionSets, $differenceSets } from "@your-scope/reactive-state"
19
+ ```
20
+
21
+ ## ✨ Core Concepts
22
+
23
+ ### `$value()` – Reactive Value
24
+
25
+ Wraps a single value in a reactive container:
26
+
27
+ ```ts
28
+ const count = $value({ value: 0 })
29
+ count.onChange.subscribe(({ increment }) => {
30
+ console.log("New value:", increment?.value)
31
+ })
32
+ count.value = 1
33
+ ```
34
+
35
+ ### `$set()` – Reactive Set
36
+
37
+ Reactive equivalent of `Set<T>`:
38
+
39
+ ```ts
40
+ const $tags = $set({ values: ["a", "b"] })
41
+ $tags.add("c")
42
+ $tags.delete("a")
43
+ ```
44
+
45
+ Supports:
46
+
47
+ - `.onChange` with `{ increment?, decrement? }`
48
+ - `batchAdd`, `batchDelete`, `applyChanges`
49
+ - Transactions via `openTransaction` / `closeTransaction`
50
+
51
+ ### Combinations
52
+
53
+ Use derived sets to represent computed relationships:
54
+
55
+ ```ts
56
+ const $admin = $set({ values: ["alice", "bob"] })
57
+ const $online = $set({ values: ["bob", "carol"] })
58
+
59
+ const $onlineAdmins = $intersectionSets({ subsets: [$admin, $online] })
60
+ ```
61
+
62
+ Available combinators:
63
+
64
+ - `$intersectionSets()` — only values present in all
65
+ - `$unionSets()` — all values from any
66
+ - `$differenceSets()` — values in one but not others
67
+
68
+ All combination sets:
69
+
70
+ - Are strictly readonly — you cannot call `add()` or `delete()` on them.
71
+ - Automatically update when their source sets change.
72
+ - Can be toggled on/off via the `enabled` flag to reduce reactivity and resource usage.
73
+
74
+ ### 🏗 Factory Functions
75
+
76
+ Factory functions provide named creation helpers for all key reactive types.
77
+
78
+ #### Base factories
79
+
80
+ - `$value(...)` – Create a reactive value container
81
+ - `$set(...)` – Create a reactive set container
82
+
83
+ #### Projection-based set factories
84
+
85
+ - `$subsetViaVal(...)` – Build a projected subset using a relation stored in a `$Value`
86
+ - `$subsetViaSet(...)` – Build a projected subset using a set of relation keys in a `$Set`
87
+ - `$complementViaVal(...)` – Build a complement set by excluding a projection from a single relation value
88
+ - `$complementViaSet(...)` – Build a complement set by excluding projected values from multiple relation keys
89
+ - `$setFromSet(...)` – Build a projected set that maps source deltas into custom results
90
+
91
+ Each factory returns a `$Combination<T>` instance.
92
+
93
+ Projection factories enable expressive modeling such as:
94
+
95
+ ```ts
96
+ const $roles = $value({ value: "admin" })
97
+ const $allPermissions = $set({ values: ["read", "write", "delete"] })
98
+
99
+ const $granted = $subsetViaVal({
100
+ superset: $allPermissions,
101
+ relation: $roles,
102
+ resolver: (all, role) => (role.value === "admin" ? all : [...all].filter((p) => p !== "delete")),
103
+ })
104
+ ```
105
+
106
+ For internal mechanics, see [CONTRIBUTING.md](./CONTRIBUTING.md#-projection-based-derived-sets).
107
+
108
+ ## 🧠 Use Cases
109
+
110
+ ### Cascade Filtering and Aggregation
111
+
112
+ ```ts
113
+ const $allItems = $set({ values: ["a", "b", "c", "d"] })
114
+ const $archived = $set({ values: ["b"] })
115
+ const $selected = $set({ values: ["a", "b", "d"] })
116
+
117
+ const $visible = $differenceSets({ superset: $allItems, subsets: [$archived] })
118
+ const $visibleSelected = $intersectionSets({ subsets: [$selected, $visible] })
119
+
120
+ // → $visibleSelected contains ['a', 'd']
121
+
122
+ $archived.add("d")
123
+ // → $visible now excludes 'd'
124
+ // → $visibleSelected now becomes ['a']
125
+ ```
126
+
127
+ This showcases how combinations compose:
128
+
129
+ - `$differenceSets` subtracts exclusions;
130
+ - `$intersectionSets` refines the view.
131
+
132
+ ### ⚠️ Readonly Behavior of Combinations
133
+
134
+ All combination sets are readonly and cannot be modified directly.
135
+ Attempting to call mutating methods such as `.add()` or `.delete()` will throw a runtime error:
136
+
137
+ ```ts
138
+ const $onlineAdmins = $intersectionSets({ subsets: [$admin, $online] })
139
+
140
+ $onlineAdmins.add("carol")
141
+ // ❌ RuntimeError: $Intersection is readonly and cannot be modified.
142
+ ```
143
+
144
+ To update the contents, always mutate the source sets directly:
145
+
146
+ ```ts
147
+ $online.add("carol")
148
+ // ✅ Triggers recomputation of $onlineAdmins
149
+ ```
150
+
151
+ ### Reactive Tag System
152
+
153
+ ```ts
154
+ const $tagsA = $set({ values: ["x", "y"] })
155
+ const $tagsB = $set({ values: ["y", "z"] })
156
+ const $commonTags = $intersectionSets({ subsets: [$tagsA, $tagsB] })
157
+
158
+ $tagsA.delete("y")
159
+ // $commonTags → Set { } (now empty)
160
+ ```
161
+
162
+ ### Reducing Reactivity to Save Resources
163
+
164
+ All reactive combinations can be temporarily disabled:
165
+
166
+ ```ts
167
+ $commonTags.disable() // stops responding to changes
168
+ $commonTags.enable() // resumes tracking intersection
169
+ ```
170
+
171
+ This is useful for optimizing performance:
172
+
173
+ - Pause unused derived state during inactive UI screens.
174
+ - Avoid unnecessary recomputations when state is backgrounded.
175
+
176
+ ## 🔁 Subscriptions and Signals
177
+
178
+ All reactive entities expose signals like `.onChange` or `.onSwitch`
179
+ hese signals emit typed payloads and support cancellation:
180
+
181
+ ```ts
182
+ const ctrl = new AbortController()
183
+ $tags.onChange.subscribe(
184
+ ({ increment, decrement }) => {
185
+ console.log("Updated:", increment, decrement)
186
+ },
187
+ { signal: ctrl.signal },
188
+ )
189
+ ```
190
+
191
+ ## 📚 Learn More
192
+
193
+ - See [GLOSSARY.md](./REACTIVE-GLOSSARY.md) for terminology
194
+ - See [CONTRIBUTING.md](./CONTRIBUTING.md) for internal architecture and projection mechanics
195
+
196
+ ## 🛠 License
197
+
198
+ MIT
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Describes a differential change to a reactive value or collection.
3
+ *
4
+ * This form is used when applying partial updates (e.g. adding/removing items)
5
+ * rather than fully replacing the state.
6
+ *
7
+ * @template T The type of the internal content (e.g. `Set<TValue>`, `IValueContainer<TValue>`)
8
+ */
9
+ export interface IIncrementalChanges<T = unknown> {
10
+ /**
11
+ * The part that was added or introduced.
12
+ * - In a set, this would be a `Set<T>` of added items.
13
+ * - In a value, this would be the new `IValueContainer<T>`.
14
+ */
15
+ increment: T | undefined
16
+
17
+ /**
18
+ * The part that was removed or replaced.
19
+ * - In a set, this would be a `Set<T>` of removed items.
20
+ * - In a value, this would be the old `IValueContainer<T>`.
21
+ */
22
+ decrement: T | undefined
23
+ }
24
+
25
+ /**
26
+ * Describes a full overwrite operation in a reactive context.
27
+ *
28
+ * Used when completely replacing a value or structure.
29
+ *
30
+ * @template T The type of the internal content (e.g. `Set<TValue>`, `IValueContainer<TValue>`)
31
+ */
32
+ export interface IOverwriteChange<T = unknown> {
33
+ /** The new value or structure that fully replaces the previous one. */
34
+ overwrite: T
35
+ }
36
+
37
+ /**
38
+ * Union type for reactive change payloads — either differential or full-replacement.
39
+ *
40
+ * This is used as input to functions like `.applyChanges()` which accept both styles.
41
+ *
42
+ * @template T The type of the internal content (e.g. `Set<TValue>`, `IValueContainer<TValue>`)
43
+ */
44
+ export type TInputChanges<T = unknown> = IIncrementalChanges<T> | IOverwriteChange<T>
@@ -0,0 +1,54 @@
1
+ import { IIncrementalChanges, IOverwriteChange } from "./changes.interface.js"
2
+
3
+ /**
4
+ * Describes a differential change in a reactive dictionary-like structure.
5
+ *
6
+ * - Keys in `increment` represent entries that were added or updated.
7
+ * - Keys in `decrement` represent entries that were removed.
8
+ *
9
+ * All keys and values are plain objects (`Record`) — no `Map` or `Set` is used.
10
+ *
11
+ * @template TKey Key type (typically `string`, `number`, or `symbol`)
12
+ * @template TValue Value type
13
+ */
14
+ export interface IDictionaryChanges<TKey extends string | number | symbol = string, TValue = unknown> extends IIncrementalChanges<Record<TKey, TValue>> {
15
+ /**
16
+ * Dictionary entries that were added or updated.
17
+ * If undefined, no insertions occurred.
18
+ */
19
+ increment: Record<TKey, TValue> | undefined
20
+
21
+ /**
22
+ * Dictionary entries that were removed.
23
+ * Keys are included with their last known values.
24
+ * If undefined, no deletions occurred.
25
+ */
26
+ decrement: Record<TKey, TValue> | undefined
27
+ }
28
+
29
+ /**
30
+ * Describes a full replacement of a reactive dictionary’s contents.
31
+ *
32
+ * When applied, this replaces the entire internal state with a new object.
33
+ *
34
+ * @template TKey Key type (typically `string`, `number`, or `symbol`)
35
+ * @template TValue Value type
36
+ */
37
+ export interface IOverwritingDictionaryChanges<TKey extends string | number | symbol = string, TValue = unknown>
38
+ extends IOverwriteChange<Record<TKey, TValue>> {
39
+ /** The new dictionary object that fully replaces the current contents. */
40
+ overwrite: Record<TKey, TValue>
41
+ }
42
+
43
+ /**
44
+ * Union type representing a dictionary change input.
45
+ *
46
+ * Accepts either:
47
+ * - a differential change (`increment` / `decrement`), via `IDictionaryChanges`;
48
+ * - or a full overwrite, via `IOverwritingDictionaryChanges`.
49
+ *
50
+ * Used in `.applyChanges(...)` methods of dictionary-like reactive structures.
51
+ */
52
+ export type TInputDictionaryChanges<TKey extends string | number | symbol = string, TValue = unknown> =
53
+ | IDictionaryChanges<TKey, TValue>
54
+ | IOverwritingDictionaryChanges<TKey, TValue>
@@ -0,0 +1,22 @@
1
+ import { Signal } from "class-signals"
2
+ import { IIncrementalChanges } from "./changes.interface.js"
3
+
4
+ /**
5
+ * Contract for reactive data sources that can emit change notifications.
6
+ *
7
+ * Any object implementing this interface exposes an `onChange` signal,
8
+ * which allows listeners to subscribe to structural or value changes.
9
+ *
10
+ * @template TChanges The shape of the emitted change payload.
11
+ */
12
+ export interface IObservable<TChanges = IIncrementalChanges> {
13
+ /**
14
+ * Reactive signal that emits changes.
15
+ *
16
+ * The emitted value must conform to the generic type `TChanges`,
17
+ * and is typically an object describing the difference (e.g. increment/decrement).
18
+ *
19
+ * Use `.subscribe(...)` to subscribe.
20
+ */
21
+ onChange: Signal<TChanges>
22
+ }
@@ -0,0 +1,50 @@
1
+ import { IIncrementalChanges, IOverwriteChange } from "./changes.interface.js"
2
+
3
+ /**
4
+ * Describes a differential change in a reactive Set.
5
+ *
6
+ * This type is used when individual items are added or removed,
7
+ * without replacing the entire set.
8
+ *
9
+ * - Emitted by signals such as `$set.onChange`.
10
+ * - Passed into methods like `applyChanges({ increment, decrement })`.
11
+ *
12
+ * @template TValue The type of values in the set.
13
+ */
14
+ export interface ISetChanges<TValue> extends IIncrementalChanges<Set<TValue>> {
15
+ /**
16
+ * Items that were added to the set.
17
+ * If undefined, no additions occurred.
18
+ */
19
+ increment: Set<TValue> | undefined
20
+
21
+ /**
22
+ * Items that were removed from the set.
23
+ * If undefined, no deletions occurred.
24
+ */
25
+ decrement: Set<TValue> | undefined
26
+ }
27
+
28
+ /**
29
+ * Describes a full replacement of a reactive Set's contents.
30
+ *
31
+ * This type is used when replacing the entire set with a new one.
32
+ * All previous items are considered removed, and all new items are considered added.
33
+ *
34
+ * @template TValue The type of values in the set.
35
+ */
36
+ export interface IOverwritingSetChanges<TValue> extends IOverwriteChange<Set<TValue>> {
37
+ /** The new set that completely replaces the previous contents. */
38
+ overwrite: Set<TValue>
39
+ }
40
+
41
+ /**
42
+ * Union type describing either:
43
+ * - a differential change (`increment` / `decrement`),
44
+ * - or a full overwrite (`overwrite`).
45
+ *
46
+ * Used as input to APIs like `$set.applyChanges(...)`.
47
+ *
48
+ * @template TValue The type of values in the set.
49
+ */
50
+ export type TInputSetChanges<TValue> = ISetChanges<TValue> | IOverwritingSetChanges<TValue>
@@ -0,0 +1,54 @@
1
+ import { IIncrementalChanges, IOverwriteChange } from "./changes.interface.js"
2
+ import { IValueContainer } from "./value-container.interface.js"
3
+
4
+ /**
5
+ * Describes a differential change in a reactive `$Value<T>`.
6
+ *
7
+ * This structure is emitted by `.onChange` of a `$Value`, representing a value update
8
+ * where both the old and new values are tracked via `IValueContainer<T>`.
9
+ *
10
+ * It extends the `IIncrementalChanges` interface with a concrete type for containers.
11
+ *
12
+ * @template TValue The inner value type stored in the container.
13
+ */
14
+ export interface IValueChange<TValue> extends IIncrementalChanges<IValueContainer<TValue>> {
15
+ /**
16
+ * The new value container (after assignment).
17
+ * `undefined` means no addition occurred.
18
+ */
19
+ increment: IValueContainer<TValue> | undefined
20
+
21
+ /**
22
+ * The previous value container (before update).
23
+ * `undefined` means no removal occurred.
24
+ */
25
+ decrement: IValueContainer<TValue> | undefined
26
+ }
27
+
28
+ /**
29
+ * Describes a full replacement of a `$Value<T>`’s content.
30
+ *
31
+ * This structure is used when the value is not updated incrementally,
32
+ * but completely overwritten with a new container.
33
+ *
34
+ * Used in methods like `overwrite()` or `applyChanges({ overwrite })`.
35
+ *
36
+ * @template TValue The inner value type stored in the container.
37
+ */
38
+ export interface IOverwritingValueChange<TValue> extends IOverwriteChange<IValueContainer<TValue>> {
39
+ /** The new value container to fully replace the old one. */
40
+ overwrite: IValueContainer<TValue>
41
+ }
42
+
43
+ /**
44
+ * Union type representing a reactive value change input.
45
+ *
46
+ * Accepts either:
47
+ * - a differential change (`increment` / `decrement`), via `IValueChange<TValue>`;
48
+ * - or a full overwrite (`overwrite`), via `IOverwritingValueChange<TValue>`.
49
+ *
50
+ * Used in APIs like `$value.applyChanges(...)`, where both styles are supported.
51
+ *
52
+ * @template TValue The inner value type managed by the container.
53
+ */
54
+ export type TInputValueChange<TValue> = IValueChange<TValue> | IOverwritingValueChange<TValue>
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Container that holds a single value in a reactive context.
3
+ *
4
+ * Used to represent values that may appear in incremental or overwrite change payloads.
5
+ * Helps distinguish between “value containers” and raw values, especially when tracking changes.
6
+ *
7
+ * @template TValue The type of the contained value.
8
+ */
9
+ export interface IValueContainer<TValue> {
10
+ /** Contained value. */
11
+ value: TValue
12
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Thrown when a reactive entity is marked as `immutable` or
3
+ * its reactivity has been disabled, making all operations invalid
4
+ * until re-enabled.
5
+ */
6
+ export class ReactivityDisabledError extends Error {
7
+ constructor(message = "Reactivity is disabled for this value or collection.") {
8
+ super(message)
9
+ this.name = "ReactivityDisabledError"
10
+ }
11
+ }