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
@@ -0,0 +1,126 @@
1
+ import { IValueContainer } from "../../_common/value-container.interface.js"
2
+ import { $Value } from "../../value/$value.class.js"
3
+ import { $Set } from "../$set.class.js"
4
+ import { $SetFromAny } from "./$set-from-any.class.js"
5
+ import { ICombinationOptions } from "../_combination/$combination.class.js"
6
+ import { MaybePromise } from "#typescript/maybe-promise.type.js"
7
+ import { difference } from "#set/index.js"
8
+
9
+ /**
10
+ * Configuration options for `$ComplementViaVal<TItem, TRelation>`.
11
+ *
12
+ * Creates a reactive complement set by excluding values from a `superset`
13
+ * based on a single dynamic **relation key** stored in a reactive `$Value`.
14
+ *
15
+ * The `resolver()` function defines how this key maps to items in the `superset`
16
+ * that should be excluded from the result.
17
+ */
18
+ export interface IComplementViaValOptions<TItem, TRelation> extends ICombinationOptions {
19
+ /** The source set from which the complement is computed. */
20
+ superset: $Set<TItem>
21
+
22
+ /**
23
+ * Reactive value representing a relation key.
24
+ *
25
+ * The current value is used to project which items in the `superset`
26
+ * should be excluded from the result.
27
+ */
28
+ relation: $Value<TRelation>
29
+
30
+ /**
31
+ * Resolves the current relation key into the set of items to exclude.
32
+ *
33
+ * This function defines a projective exclusion:
34
+ * the key may correspond to zero, one, or many values in the superset.
35
+ *
36
+ * @example
37
+ * - a selected tag → items with that tag
38
+ * - a current user role → restricted features
39
+ * - a selected category → hidden content
40
+ *
41
+ * @param superset The current contents of the superset.
42
+ * @param relation A reactive wrapper around the current relation key.
43
+ * @returns The set of values to exclude from the final result.
44
+ */
45
+ resolver: (superset: Set<NoInfer<TItem>>, relation: IValueContainer<NoInfer<TRelation>>) => MaybePromise<Iterable<NoInfer<TItem>>>
46
+ }
47
+
48
+ /**
49
+ * Reactive complement of a superset based on a dynamic projection key.
50
+ *
51
+ * `$ComplementViaVal<TItem, TRelation>` creates a readonly derived set
52
+ * by projecting a single reactive `relation` value into items to **exclude**
53
+ * from the `superset` using a custom `resolver()` function.
54
+ *
55
+ * The result is a reactive complement:
56
+ * it includes all values from the superset that are **not** part of the projection.
57
+ *
58
+ * This is the inverse of `$SubsetViaVal`, and is useful for building
59
+ * exclusion lists, inverse selections, or permission denials.
60
+ *
61
+ * Reacts to:
62
+ * - changes in the `superset`;
63
+ * - updates to the `relation` key.
64
+ *
65
+ * @template TItem The type of values in the superset and result.
66
+ * @template TRelation The type of the relation key used for exclusion.
67
+ *
68
+ * @remarks
69
+ * This set is `readonly`: any attempt to modify it directly will throw.
70
+ *
71
+ * @example Exclude items by even/odd projection:
72
+ * ```ts
73
+ * const $nums = $set({ values: [1, 2, 3, 4, 5, 6] })
74
+ * const $mode = $value<'even' | 'odd'>({ value: 'even' })
75
+ *
76
+ * const $excluded = new $ComplementViaVal({
77
+ * superset: $nums,
78
+ * relation: $mode,
79
+ * resolver: (nums, mode) =>
80
+ * [...nums].filter(n => (mode.value === 'even' ? n % 2 === 0 : n % 2 !== 0)),
81
+ * })
82
+ *
83
+ * console.log([...$excluded]) // → [1, 3, 5]
84
+ * $mode.value = 'odd'
85
+ * console.log([...$excluded]) // → [2, 4, 6]
86
+ * ```
87
+ */
88
+ export class $ComplementViaVal<TItem, TRelation> extends $SetFromAny<TItem, { superset: $Set<TItem>; relation: $Value<TRelation> }> {
89
+ constructor(options: IComplementViaValOptions<TItem, TRelation>) {
90
+ const { label, enabled = true, superset, relation, resolver } = options
91
+
92
+ super({
93
+ label,
94
+ enabled,
95
+ dependencies: {
96
+ superset,
97
+ relation,
98
+ },
99
+ resolvers: {
100
+ superset: async ({ relation: currentRelation }, { increment: addedToSuperset, decrement: removedFromSuperset }) => {
101
+ if (!currentRelation) return { increment: undefined, decrement: undefined }
102
+
103
+ let addedToComplement: Set<TItem> | undefined
104
+
105
+ if (addedToSuperset?.size) {
106
+ const matched = new Set(await resolver(addedToSuperset, currentRelation))
107
+ addedToComplement = difference(addedToSuperset, matched)
108
+ }
109
+
110
+ return {
111
+ increment: addedToComplement,
112
+ decrement: removedFromSuperset,
113
+ }
114
+ },
115
+ relation: async ({ superset: currentSuperset }, { increment: nextRelation }) => {
116
+ if (!currentSuperset?.size || !nextRelation) return { increment: undefined, decrement: undefined }
117
+
118
+ const matched = new Set(await resolver(currentSuperset, nextRelation))
119
+ const newComplement = difference(currentSuperset, matched)
120
+
121
+ return { overwrite: newComplement }
122
+ },
123
+ },
124
+ })
125
+ }
126
+ }
@@ -0,0 +1,382 @@
1
+ import { $Combination, ICombinationOptions } from "../_combination/$combination.class.js"
2
+ import type { TDependencySetResolver } from "./types/dependency-set-resolver.type.js"
3
+ import type { TDependencyValueResolver } from "./types/dependency-value-resolver.type.js"
4
+ import { $Value } from "../../value/$value.class.js"
5
+ import { $Set } from "../$set.class.js"
6
+ import { DeltaBufferForSet } from "./feature.reactive-delta-buffer/delta-buffer-for-set.class.js"
7
+ import { DeltaBufferForValue } from "./feature.reactive-delta-buffer/delta-buffer-for-value.class.js"
8
+ import type { IValueContainer } from "../../_common/value-container.interface.js"
9
+
10
+ /** Maps string keys to reactive dependencies — either `$Set<T>` or `$Value<T>`. */
11
+ export type TDependenciesMap = Record<string, $Set<unknown> | $Value<unknown>>
12
+
13
+ /**
14
+ * Resolves a single reactive dependency to its runtime value representation:
15
+ *
16
+ * - `$Set<T>` becomes `Set<T> | null`
17
+ * - `$Value<T>` becomes `IValueContainer<T> | null`
18
+ *
19
+ * Used as a building block for `TResolvedContext`.
20
+ */
21
+ export type TResolved<T extends $Set<unknown> | $Value<unknown>> =
22
+ T extends $Set<infer U> ? Set<U> | null
23
+ : T extends $Value<infer V> ? IValueContainer<V> | null
24
+ : never
25
+
26
+ /**
27
+ * Maps dependency names to their resolved values:
28
+ * - `$Set<T>` becomes `Set<T> | null`
29
+ * - `$Value<T>` becomes `IValueContainer<T> | null`
30
+ */
31
+ export type TResolvedContext<TDependencies extends TDependenciesMap> = {
32
+ [name in keyof TDependencies]: TResolved<TDependencies[name]>
33
+ }
34
+
35
+ /**
36
+ * Maps dependency names to resolver functions.
37
+ *
38
+ * For each declared dependency, a corresponding resolver must be provided.
39
+ * This resolver defines how changes in that dependency affect the derived result set.
40
+ *
41
+ * - `$Set<T>` dependencies receive an `ISetChanges<T>` and return a set-level delta.
42
+ * - `$Value<T>` dependencies receive an `IValueChange<T>` and return a set-level delta.
43
+ *
44
+ * @template TDeps The declared dependency map (`$Set` / `$Value`).
45
+ * @template TResult The type of values in the resulting reactive set.
46
+ *
47
+ * @remarks
48
+ * In the case of `$Set` dependencies, values in the source set are often treated as **projection keys** —
49
+ * not direct members of the result set. The resolver may expand these keys into actual result values.
50
+ *
51
+ * For example:
52
+ * - A tag ID in a filter set might expand into many entities to exclude.
53
+ * - A parent ID might map to all child nodes in a tree structure.
54
+ */
55
+ export type TDependencyResolversMap<TDeps extends TDependenciesMap, TResult> = {
56
+ [key in keyof TDeps]: TDeps[key] extends $Set<infer TSourceValue> ? TDependencySetResolver<TResolvedContext<TDeps>, TSourceValue, TResult>
57
+ : TDeps[key] extends $Value<infer TSourceValue> ? TDependencyValueResolver<TResolvedContext<TDeps>, TSourceValue, TResult>
58
+ : never
59
+ }
60
+
61
+ /**
62
+ * Configuration for `$SetFromAny<TResult, TDependencies>`.
63
+ *
64
+ * Describes the reactive input sources and how each of them should affect the resulting set.
65
+ * Every entry in `dependencies` is paired with a corresponding function in `resolvers`
66
+ * that determines how changes from that source propagate.
67
+ *
68
+ * @template TResult The type of values in the resulting reactive set.
69
+ * @template TDependencies A record of named `$Set<T>` or `$Value<T>` inputs.
70
+ */
71
+ export interface ISetFromAnyOptions<TResult, TDependencies extends TDependenciesMap> extends ICombinationOptions {
72
+ /**
73
+ * Named reactive dependencies: either `$Set<T>` or `$Value<T>`.
74
+ *
75
+ * Each key defines a named input, and the name will be used as:
76
+ * - the key in the reactive context passed to all resolver functions;
77
+ * - the identifier for matching the corresponding resolver in `resolvers`;
78
+ * - a semantic reference in debugging or tracing.
79
+ *
80
+ * 💡 Use clear, meaningful names such as `source`, `filter`, `mode`, `superset`, `relation`.
81
+ */
82
+ dependencies: TDependencies
83
+
84
+ /**
85
+ * Resolver functions for handling incoming changes from each dependency.
86
+ *
87
+ * Each key must exactly match the corresponding name in `dependencies`.
88
+ * The result of each resolver will be applied to the target set.
89
+ *
90
+ * - For `$Set<T>` sources, use `TDependencySetResolver`
91
+ * - For `$Value<T>` sources, use `TDependencyValueResolver`
92
+ *
93
+ * @remarks
94
+ * In the case of `$Set` dependencies, each item may be treated as a **projection key**,
95
+ * not a literal result value. The resolver can expand each key into zero or more
96
+ * elements that affect the derived set.
97
+ *
98
+ * This allows powerful correlation logic such as:
99
+ * - mapping tag IDs to excluded objects;
100
+ * - resolving user roles into granted features;
101
+ * - expanding relation keys into a graph of affected entities.
102
+ */
103
+ resolvers: TDependencyResolversMap<TDependencies, TResult>
104
+ }
105
+
106
+ /**
107
+ * Reactive combination that derives a set from one or more `$Set` or `$Value` sources.
108
+ *
109
+ * `$SetFromAny` generalizes reactive set computation by allowing
110
+ * arbitrary dependencies (sets or values) and assigning each a resolver function.
111
+ *
112
+ * Whenever any dependency changes, the appropriate resolver runs,
113
+ * producing incremental or overwrite-level changes to the result.
114
+ *
115
+ * This class powers all advanced constructs like:
116
+ * - `$SubsetViaVal`, `$SubsetViaSet`
117
+ * - `$ComplementViaVal`, `$ComplementViaSet`
118
+ * - `$SetFromSet`
119
+ *
120
+ * @template TResult The type of values in the resulting set.
121
+ * @template TDependencies A record of dependency names → $Set / $Value
122
+ *
123
+ * @remarks
124
+ * This set is readonly. To influence its result, mutate the sources it depends on.
125
+ */
126
+ export class $SetFromAny<TResult, TDependencies extends TDependenciesMap> extends $Combination<TResult> {
127
+ /**
128
+ * Internal buffer objects that accumulate and commit changes
129
+ * from each reactive dependency.
130
+ */
131
+ protected readonly buffers = new Set<DeltaBufferForSet | DeltaBufferForValue>()
132
+
133
+ constructor(options: ISetFromAnyOptions<TResult, TDependencies>) {
134
+ super(options)
135
+
136
+ for (const name in options.dependencies) {
137
+ const source = options.dependencies[name]
138
+
139
+ if (source instanceof $Set) {
140
+ /// @ts-expect-error: type erasure due to structural resolution
141
+ const resolver: TDependencySetResolver = options.resolvers[name]
142
+
143
+ this.buffers.add(new DeltaBufferForSet(name, source, resolver, false))
144
+ } else if (source instanceof $Value) {
145
+ /// @ts-expect-error: type erasure due to structural resolution
146
+ const resolver: TDependencyValueResolver = options.resolvers[name]
147
+
148
+ this.buffers.add(new DeltaBufferForValue(name, source, resolver, false))
149
+ } else throw new TypeError(`Unexpected dependency type for "${name}".`)
150
+ }
151
+
152
+ if (this.enabled) this.attachBuffers()
153
+ }
154
+
155
+ // ################# CASCADED REACTIVITY ####################
156
+
157
+ /** Returns the list of parent sources that are reactive combinations and currently disabled. */
158
+ protected get inactiveParents() {
159
+ return [...this.buffers].map((buffer) => buffer.source).filter((source) => source instanceof $Combination && !source.enabled)
160
+ }
161
+
162
+ /**
163
+ * Returns true if all parent combinations are currently active.
164
+ * If any parent is disabled, this node is considered blocked.
165
+ */
166
+ protected get allParentsAreActive() {
167
+ return this.inactiveParents.length === 0
168
+ }
169
+
170
+ /**
171
+ * Whether this combination is currently reactive and eligible for updates.
172
+ *
173
+ * A node is considered enabled only if:
174
+ * - it is locally enabled;
175
+ * - all its parent combinations are enabled (transitive cascade).
176
+ */
177
+ public get enabled() {
178
+ return this.isLocallyEnabled && this.allParentsAreActive
179
+ }
180
+
181
+ /**
182
+ * Enables the current node locally.
183
+ * Will trigger full activation only if all parent combinations are active.
184
+ */
185
+ protected activate() {
186
+ this.isLocallyEnabled = true
187
+ if (this.allParentsAreActive) this.onActivated()
188
+ }
189
+
190
+ /**
191
+ * Disables the current node locally.
192
+ * Will trigger full deactivation only if all parent combinations are still active.
193
+ */
194
+ protected deactivate() {
195
+ this.isLocallyEnabled = false
196
+ if (this.allParentsAreActive) this.onDeactivated()
197
+ }
198
+
199
+ // ################# LIFECYCLE AND SUBSCRIPTION #################
200
+
201
+ /**
202
+ * Internal controller used to cancel the currently running `synchronize()` operation.
203
+ * Ensures that overlapping sync passes do not interfere with each other.
204
+ */
205
+ #syncController?: AbortController
206
+
207
+ /**
208
+ * Stores per-buffer subscription controllers.
209
+ * Used to unsubscribe cleanly during deactivation.
210
+ */
211
+ protected readonly changeSubscriptions = new Map<DeltaBufferForSet | DeltaBufferForValue, AbortController>()
212
+
213
+ /**
214
+ * Called when this node becomes fully active (locally and via parent cascade).
215
+ * Enables all buffers, subscribes to their `.onChange`, and starts syncing.
216
+ */
217
+ protected onActivated(): void {
218
+ super.onActivated()
219
+ this.attachBuffers()
220
+ }
221
+
222
+ /**
223
+ * Called when this node is deactivated.
224
+ * Unsubscribes from all buffer change signals and cancels pending sync work.
225
+ */
226
+ protected onDeactivated(): void {
227
+ super.onDeactivated()
228
+ this.detachBuffers()
229
+ this.#syncController?.abort()
230
+ }
231
+
232
+ /**
233
+ * Enables all delta buffers and subscribes to their `.onChange` signals.
234
+ * Triggers an initial `synchronize()` pass to resolve buffered state.
235
+ */
236
+ protected attachBuffers() {
237
+ for (const buffer of this.buffers) buffer.enable()
238
+ for (const buffer of this.buffers) this.listenToBuffer(buffer)
239
+ this.synchronize()
240
+ }
241
+
242
+ /**
243
+ * Unsubscribes from all buffer signals and disables tracking.
244
+ * Called during full deactivation of this node.
245
+ */
246
+ protected detachBuffers() {
247
+ for (const buffer of this.buffers) {
248
+ this.changeSubscriptions.get(buffer)?.abort()
249
+ buffer.disable()
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Subscribes to `.onChange` signals from a delta buffer.
255
+ *
256
+ * Signals are treated as notifications that a new delta *may* exist.
257
+ * After receiving a signal, we check for real uncommitted changes via `getBufferedChange()`.
258
+ * If changes are present, a `synchronize()` pass is started.
259
+ *
260
+ * @param buffer A delta buffer tracking either a `$Set` or `$Value` source.
261
+ */
262
+ protected listenToBuffer(buffer: DeltaBufferForSet | DeltaBufferForValue): void {
263
+ const controller = new AbortController()
264
+
265
+ this.changeSubscriptions.set(buffer, controller)
266
+
267
+ if (buffer instanceof DeltaBufferForSet)
268
+ buffer.onChange.subscribe(() => buffer.getBufferedChanges() && this.synchronize(), { signal: controller.signal })
269
+
270
+ if (buffer instanceof DeltaBufferForValue)
271
+ buffer.onChange.subscribe(() => buffer.getBufferedChange() && this.synchronize(), { signal: controller.signal })
272
+ }
273
+
274
+ /** Whether a sync worker is currently running. */
275
+ #isWorkerRunned = false
276
+
277
+ /**
278
+ * Prevents overlapping sync operations by running only one worker at a time.
279
+ * If a sync is already running, this call is skipped.
280
+ *
281
+ * @param doWork A function that receives an `AbortSignal` and performs the sync logic.
282
+ */
283
+ protected async runWorker(doWork: (signal: AbortSignal) => Promise<void>) {
284
+ if (this.#isWorkerRunned) return
285
+
286
+ this.#isWorkerRunned = true
287
+ const controller = (this.#syncController = new AbortController())
288
+
289
+ try {
290
+ await doWork(controller.signal)
291
+ } catch (error) {
292
+ console.error(error)
293
+
294
+ this.disable()
295
+ console.warn("The derived set was disabled because an error occurred while resolving its dependencies.")
296
+ }
297
+
298
+ this.#isWorkerRunned = false
299
+ this.#syncController = undefined
300
+ }
301
+
302
+ /**
303
+ * Synchronizes buffered changes by resolving and applying deltas
304
+ * from one dependency buffer at a time.
305
+ *
306
+ * Because resolution is asynchronous, other buffers might change
307
+ * while we await — so we must re-evaluate all buffers after each resolution.
308
+ *
309
+ * This loop continues until no buffered deltas remain.
310
+ */
311
+ protected async synchronize() {
312
+ this.runWorker(async (signal: AbortSignal) => {
313
+ let desyncDetected = false
314
+
315
+ do {
316
+ desyncDetected = false
317
+
318
+ for (const buffer of this.buffers) {
319
+ if (buffer instanceof DeltaBufferForSet) {
320
+ // Try to consume buffered delta from this buffer
321
+ const bufferedDelta = buffer.getBufferedChanges()
322
+ if (!bufferedDelta) continue
323
+
324
+ // Mark this buffer as committed before awaiting resolver
325
+ buffer.commitChanges()
326
+
327
+ // Compute the downstream effect of this delta
328
+ const resolvedDelta = await buffer.resolver(this.contextSnapshot(), bufferedDelta)
329
+ // A delta was consumed — we must re-check all buffers from the start
330
+ desyncDetected = true
331
+
332
+ // If this sync pass was aborted (e.g., due to disable), stop immediately
333
+ if (signal.aborted) return
334
+
335
+ // Apply changes to the target set
336
+ this.applyChanges(resolvedDelta)
337
+
338
+ break
339
+ } else if (buffer instanceof DeltaBufferForValue) {
340
+ // Try to consume buffered delta from this buffer
341
+ const bufferedDelta = buffer.getBufferedChange()
342
+ if (!bufferedDelta) continue
343
+
344
+ // Mark this buffer as committed before awaiting resolver
345
+ buffer.commitState()
346
+
347
+ // Compute the downstream effect of this delta
348
+ const resolvedDelta = await buffer.resolver(this.contextSnapshot(), bufferedDelta)
349
+ // A delta was consumed — we must re-check all buffers from the start
350
+ desyncDetected = true
351
+
352
+ // If this sync pass was aborted (e.g., due to disable), stop immediately
353
+ if (signal.aborted) return
354
+
355
+ // Apply changes to the target set
356
+ this.applyChanges(resolvedDelta)
357
+
358
+ break
359
+ }
360
+ }
361
+ } while (desyncDetected)
362
+ })
363
+ }
364
+
365
+ /**
366
+ * Returns a snapshot of the last committed state of all dependencies.
367
+ *
368
+ * This snapshot is passed as the `context` argument to resolver functions.
369
+ * It contains:
370
+ * - for each `$Set` dependency: a `Set<T> | null` representing committed values;
371
+ * - for each `$Value` dependency: an `IValueContainer<T> | null` representing the last known value;
372
+ *
373
+ * @returns A record mapping dependency names to their last committed state.
374
+ */
375
+ protected contextSnapshot(): Record<string, Set<any> | IValueContainer<any> | null> {
376
+ const committedStates: Record<string, Set<any> | IValueContainer<any> | null> = {}
377
+
378
+ for (const buffer of this.buffers) committedStates[buffer.name] = buffer.getCommittedState()
379
+
380
+ return committedStates
381
+ }
382
+ }
@@ -0,0 +1,90 @@
1
+ import { $Set } from "../$set.class.js"
2
+ import { ISetChanges } from "../../_common/set-changes.interface.js"
3
+ import { $SetFromAny } from "./$set-from-any.class.js"
4
+ import { ICombinationOptions } from "../_combination/$combination.class.js"
5
+ import { MaybePromise } from "#typescript/maybe-promise.type.js"
6
+
7
+ /**
8
+ * Configuration options for creating a `$SetFromSet<TTarget, TSource>` instance.
9
+ *
10
+ * This derived set reacts to changes in a source `$Set<TSource>` and computes
11
+ * a corresponding set of changes to apply to the target set.
12
+ *
13
+ * Each update is handled via a `resolver` function that receives a delta
14
+ * and returns a projected delta in the target domain.
15
+ *
16
+ * This enables many-to-many reactive projections, not just 1:1 mappings.
17
+ */
18
+ export interface ISetFromSetOptions<TTarget, TSource> extends ICombinationOptions {
19
+ /** Reactive source set to observe. */
20
+ source: $Set<TSource>
21
+
22
+ /**
23
+ * Resolves a source delta (`ISetChanges<TSource>`) into a change
24
+ * that should be applied to the target set.
25
+ *
26
+ * This function can implement any projection logic, such as:
27
+ * - transforming raw data → enriched data;
28
+ * - resolving foreign keys → related models;
29
+ * - grouping, expanding, or filtering incoming changes.
30
+ *
31
+ * @remarks
32
+ * Each value in the source set may project to:
33
+ * - zero target values (filtered);
34
+ * - one value (mapped);
35
+ * - multiple values (expanded).
36
+ *
37
+ * The resolver is called for each incremental change (`increment` / `decrement`)
38
+ * and must return a valid `ISetChanges<TTarget>` object.
39
+ */
40
+ resolver: (changes: ISetChanges<TSource>) => MaybePromise<ISetChanges<TTarget>>
41
+ }
42
+
43
+ /**
44
+ * Low-level reactive adapter between two sets with custom change mapping.
45
+ *
46
+ * `$SetFromSet<TTarget, TSource>` builds a derived `$Set<TTarget>` by listening
47
+ * to a source `$Set<TSource>` and applying a transformation via a user-provided `associate()` function.
48
+ *
49
+ * This is the most flexible form of reactive projection — useful when:
50
+ * - mapping one domain to another;
51
+ * - synchronizing a subset or superset view;
52
+ * - building observables from foreign representations.
53
+ *
54
+ * @template TTarget The type of values in the derived set.
55
+ * @template TSource The type of values in the source set.
56
+ *
57
+ * @remarks
58
+ * This set is readonly — you must mutate the source set to affect the output.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * const $ids = $set({ values: [1, 2, 3] })
63
+ * const $labels = new $SetFromSet({
64
+ * source: $ids,
65
+ * associate: ({ increment, decrement }) => ({
66
+ * increment: increment && new Set([...increment].map(id => `#${id}`)),
67
+ * decrement: decrement && new Set([...decrement].map(id => `#${id}`)),
68
+ * }),
69
+ * })
70
+ *
71
+ * $ids.add(4)
72
+ * // $labels → Set { '#1', '#2', '#3', '#4' }
73
+ * ```
74
+ */
75
+ export class $SetFromSet<TTarget, TSource> extends $SetFromAny<TTarget, { source: $Set<TSource> }> {
76
+ constructor(options: ISetFromSetOptions<TTarget, TSource>) {
77
+ const { source, resolver, enabled = true, label } = options
78
+
79
+ super({
80
+ dependencies: {
81
+ source,
82
+ },
83
+ resolvers: {
84
+ source: (_, changes) => resolver(changes),
85
+ },
86
+ enabled,
87
+ label,
88
+ })
89
+ }
90
+ }