@nerdalytics/beacon 1.0.0 โ†’ 1000.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Beacon
1
+ # Beacon <img align="right" src="https://raw.githubusercontent.com/nerdalytics/beacon/refs/heads/trunk/assets/beacon-logo.svg" width="128px" alt="A stylized lighthouse beacon with golden light against a dark blue background, representing the reactive state library"/>
2
2
 
3
- A lightweight reactive signal library for Node.js backends. Enables reactive state management with automatic dependency tracking and efficient updates for server-side applications.
3
+ A lightweight reactive state library for Node.js backends. Enables reactive state management with automatic dependency tracking and efficient updates for server-side applications.
4
4
 
5
5
  ## Table of Contents
6
6
 
@@ -8,10 +8,13 @@ A lightweight reactive signal library for Node.js backends. Enables reactive sta
8
8
  - [Installation](#installation)
9
9
  - [Usage](#usage)
10
10
  - [API](#api)
11
- - [state](#statetinitialvalue-t-signalt)
12
- - [derived](#derivedfn--t-signalt)
13
- - [effect](#effectfn--void--void)
14
- - [batch](#batchfn--t-t)
11
+ - [state](#statetinitialvalue-t-statet)
12
+ - [derive](#derivetfn---t-readonlystatet)
13
+ - [effect](#effectfn---void---void)
14
+ - [batch](#batchtfn---t-t)
15
+ - [select](#selectt-rsource-readonlystatet-selectorfn-state-t--r-equalityfn-a-r-b-r--boolean-readonlystater)
16
+ - [readonlyState](#readonlystatetstate-statet-readonlystatet)
17
+ - [protectedState](#protectedstatetinitialvalue-t-readonlystatet-writeablestatet)
15
18
  - [Development](#development)
16
19
  - [Node.js LTS Compatibility](#nodejs-lts-compatibility)
17
20
  - [Key Differences vs TC39 Proposal](#key-differences-between-my-library-and-the-tc39-proposal)
@@ -21,31 +24,33 @@ A lightweight reactive signal library for Node.js backends. Enables reactive sta
21
24
 
22
25
  ## Features
23
26
 
24
- - ๐Ÿ”„ **Reactive signals** - Create reactive values that automatically track dependencies
25
- - ๐Ÿงฎ **Computed values** - Derive values from other signals with automatic updates
26
- - ๐Ÿ” **Fine-grained reactivity** - Dependencies are tracked precisely at the signal level
27
+ - ๐Ÿ“ถ **Reactive state** - Create reactive values that automatically track dependencies
28
+ - ๐Ÿงฎ **Computed values** - Derive values from other states with automatic updates
29
+ - ๐Ÿ” **Fine-grained reactivity** - Dependencies are tracked precisely at the state level
27
30
  - ๐ŸŽ๏ธ **Efficient updates** - Only recompute values when dependencies change
28
31
  - ๐Ÿ“ฆ **Batched updates** - Group multiple updates for performance
32
+ - ๐ŸŽฏ **Targeted subscriptions** - Select and subscribe to specific parts of state objects
29
33
  - ๐Ÿงน **Automatic cleanup** - Effects and computations automatically clean up dependencies
30
- - ๐Ÿ” **Cycle handling** - Safely manages cyclic dependencies without crashing
34
+ - โ™ป๏ธ **Cycle handling** - Safely manages cyclic dependencies without crashing
35
+ - ๐Ÿšจ **Infinite loop detection** - Automatically detects and prevents infinite update loops
31
36
  - ๐Ÿ› ๏ธ **TypeScript-first** - Full TypeScript support with generics
32
37
  - ๐Ÿชถ **Lightweight** - Zero dependencies, < 200 LOC
33
38
  - โœ… **Node.js compatibility** - Works with Node.js LTS v20+ and v22+
34
39
 
35
40
  ## Installation
36
41
 
37
- ```bash
42
+ ```sh
38
43
  npm install @nerdalytics/beacon
39
44
  ```
40
45
 
41
46
  ## Usage
42
47
 
43
48
  ```typescript
44
- import { state, derived, effect, batch } from "@nerdalytics/beacon";
49
+ import { state, derive, effect, batch, select, readonlyState, protectedState } from "@nerdalytics/beacon";
45
50
 
46
51
  // Create reactive state
47
52
  const count = state(0);
48
- const doubled = derived(() => count() * 2);
53
+ const doubled = derive(() => count() * 2);
49
54
 
50
55
  // Read values
51
56
  console.log(count()); // => 0
@@ -73,20 +78,63 @@ batch(() => {
73
78
  });
74
79
  // => "Count is 20, doubled is 40" (only once)
75
80
 
81
+ // Using select to subscribe to specific parts of state
82
+ const user = state({ name: "Alice", age: 30, email: "alice@example.com" });
83
+ const nameSelector = select(user, u => u.name);
84
+
85
+ effect(() => {
86
+ console.log(`Name changed: ${nameSelector()}`);
87
+ });
88
+ // => "Name changed: Alice"
89
+
90
+ // Updates to the selected property will trigger the effect
91
+ user.update(u => ({ ...u, name: "Bob" }));
92
+ // => "Name changed: Bob"
93
+
94
+ // Updates to other properties won't trigger the effect
95
+ user.update(u => ({ ...u, age: 31 })); // No effect triggered
96
+
76
97
  // Unsubscribe the effect to stop it from running on future updates
77
98
  // and clean up all its internal subscriptions
78
99
  unsubscribe();
100
+
101
+ // Using readonlyState to create a read-only view
102
+ const counter = state(0);
103
+ const readonlyCounter = readonlyState(counter);
104
+ // readonlyCounter() works, but readonlyCounter.set() is not available
105
+
106
+ // Using protectedState to separate read and write capabilities
107
+ const [getUser, setUser] = protectedState({ name: 'Alice' });
108
+ // getUser() works to read the state
109
+ // setUser.set() and setUser.update() work to modify the state
110
+ // but getUser has no mutation methods
111
+
112
+ // Infinite loop detection example (would throw an error)
113
+ try {
114
+ effect(() => {
115
+ const value = counter();
116
+ // The following would throw an error because it attempts to
117
+ // update a state that the effect depends on:
118
+ // "Infinite loop detected: effect() cannot update a state() it depends on!"
119
+ // counter.set(value + 1);
120
+
121
+ // Instead, use a safe pattern with proper dependencies:
122
+ console.log(`Current counter value: ${value}`);
123
+ });
124
+ } catch (error) {
125
+ console.error('Prevented infinite loop:', error.message);
126
+ }
79
127
  ```
80
128
 
81
129
  ## API
82
130
 
83
- ### `state<T>(initialValue: T): Signal<T>`
131
+ ### `state<T>(initialValue: T): State<T>`
84
132
 
85
- Creates a new reactive signal with the given initial value.
133
+ Creates a new reactive state container with the provided initial value.
86
134
 
87
- ### `derived<T>(fn: () => T): Signal<T>`
135
+ ### `derive<T>(fn: () => T): ReadOnlyState<T>`
88
136
 
89
- Creates a derived signal that updates when its dependencies change.
137
+ Creates a read-only computed value that updates when its dependencies change.
90
138
 
91
139
  ### `effect(fn: () => void): () => void`
92
140
 
@@ -96,9 +144,21 @@ Creates an effect that runs the given function immediately and whenever its depe
96
144
 
97
145
  Batches multiple updates to only trigger effects once at the end.
98
146
 
147
+ ### `select<T, R>(source: ReadOnlyState<T>, selectorFn: (state: T) => R, equalityFn?: (a: R, b: R) => boolean): ReadOnlyState<R>`
148
+
149
+ Creates an efficient subscription to a subset of a state value. The selector will only notify its subscribers when the selected value actually changes according to the provided equality function (defaults to `Object.is`).
150
+
151
+ ### `readonlyState<T>(state: State<T>): ReadOnlyState<T>`
152
+
153
+ Creates a read-only view of a state, hiding mutation methods. Useful when you want to expose a state to other parts of your application without allowing direct mutations.
154
+
155
+ ### `protectedState<T>(initialValue: T): [ReadOnlyState<T>, WriteableState<T>]`
156
+
157
+ Creates a state with access control, returning a tuple of reader and writer. This pattern separates read and write capabilities, allowing you to expose only the reading capability to consuming code while keeping the writing capability private.
158
+
99
159
  ## Development
100
160
 
101
- ```bash
161
+ ```sh
102
162
  # Install dependencies
103
163
  npm install
104
164
 
@@ -111,19 +171,26 @@ npm run test:coverage
111
171
  # Run specific test suites
112
172
  # Core functionality
113
173
  npm run test:unit:state
114
- npm run test:unit:derived
115
174
  npm run test:unit:effect
175
+ npm run test:unit:derive
116
176
  npm run test:unit:batch
177
+ npm run test:unit:select
178
+ npm run test:unit:readonly
179
+ npm run test:unit:protected
117
180
 
118
181
  # Advanced patterns
119
- npm run test:unit:cleanup # Tests for effect cleanup behavior
120
- npm run test:unit:cyclic # Tests for cyclic dependency handling
182
+ npm run test:unit:cleanup # Tests for effect cleanup behavior
183
+ npm run test:unit:cyclic-dependency # Tests for cyclic dependency handling
184
+ npm run test:unit:deep-chain # Tests for deep chain handling
185
+ npm run test:unit:infinite-loop # Tests for infinite loop detection
186
+
187
+ # Benchmarking
188
+ npm run benchmark # Tests for infinite loop detection
121
189
 
122
190
  # Format code
123
191
  npm run format
124
-
125
- # Build for Node.js LTS compatibility (v20+)
126
- npm run build:lts
192
+ npm run lint
193
+ npm run check # Runs Bioms lint + format
127
194
  ```
128
195
 
129
196
  ### Node.js LTS Compatibility
@@ -134,7 +201,7 @@ Beacon supports the two most recent Node.js LTS versions (currently v20 and v22)
134
201
 
135
202
  | Aspect | @nerdalytics/beacon | TC39 Proposal |
136
203
  |--------|---------------------|---------------|
137
- | **API Style** | Functional approach (`state()`, `derived()`) | Class-based design (`Signal.State`, `Signal.Computed`) |
204
+ | **API Style** | Functional approach (`state()`, `derive()`) | Class-based design (`Signal.State`, `Signal.Computed`) |
138
205
  | **Reading/Writing Pattern** | Function call for reading (`count()`), methods for writing (`count.set(5)`) | Method-based access (`get()`/`set()`) |
139
206
  | **Framework Support** | High-level abstractions like `effect()` and `batch()` | Lower-level primitives (`Signal.subtle.Watcher`) that frameworks build upon |
140
207
  | **Advanced Features** | Focused on core reactivity | Includes introspection capabilities, watched/unwatched callbacks, and Signal.subtle namespace |
@@ -146,42 +213,51 @@ Beacon is designed with a focus on simplicity, performance, and robust handling
146
213
 
147
214
  ### Key Implementation Concepts
148
215
 
149
- - **Fine-grained reactivity**: Dependencies are tracked automatically at the signal level
216
+ - **Fine-grained reactivity**: Dependencies are tracked automatically at the state level
150
217
  - **Efficient updates**: Changes only propagate to affected parts of the dependency graph
151
218
  - **Cyclical dependency handling**: Robust handling of circular references without crashing
219
+ - **Infinite loop detection**: Safeguards against direct self-mutation within effects
152
220
  - **Memory management**: Automatic cleanup of subscriptions when effects are disposed
153
-
154
- For an in-depth explanation of Beacon's internal architecture, advanced features, and best practices for handling complex scenarios like cyclical dependencies, see the [TECHNICAL_DETAILS.md][2] document.
221
+ - **Optimized batching**: Smart scheduling of updates to minimize redundant computations
155
222
 
156
223
  ## FAQ
157
224
 
158
225
  <details>
159
226
 
160
227
  <summary>Why "Beacon" Instead of "Signal"?</summary>
161
- I chose "Beacon" because it clearly represents how the library broadcasts notifications when state changesโ€”just like a lighthouse guides ships. While my library draws inspiration from Preact Signals, Angular Signals, and aspects of Svelte, I wanted to create something lighter and specifically designed for Node.js backends. Using "Beacon" instead of "Signal" helps avoid confusion with the TC39 proposal and similar libraries while still accurately describing the core functionality.
228
+ I chose "Beacon" because it clearly represents how the library broadcasts notifications when state changesโ€”just like a lighthouse guides ships. While my library draws inspiration from Preact Signals, Angular Signals, and aspects of Svelte, I wanted to create something lighter and specifically designed for Node.js backends. Using "Beacon" instead of the term "Signal" helps avoid confusion with the TC39 proposal and similar libraries while still accurately describing the core functionality.
162
229
 
163
230
  </details>
164
231
 
165
232
  <details>
166
233
 
167
234
  <summary>How does Beacon handle infinite update cycles?</summary>
168
- Beacon uses a queue-based update system that won't crash even with cyclical dependencies. If signals form a cycle where values constantly change (A updates B updates A...), the system will continue processing these updates without stack overflows. However, this could potentially affect performance if updates never stabilize. See the [TECHNICAL_DETAILS.md][4] document for best practices on handling cyclical dependencies.
235
+ Beacon employs two complementary strategies for handling cyclical updates:
236
+
237
+ 1. **Infinite Loop Detection**: Beacon actively detects direct infinite loops in effects by tracking which states an effect reads and writes to. If an effect attempts to update a state it depends on (directly modifying its own dependency), Beacon throws an error with a clear message: "Infinite loop detected: effect() cannot update a state() it depends on!"
238
+
239
+ 2. **Safe Cyclic Dependencies**: For indirect cycles and safe update patterns, Beacon uses a queue-based update system that won't crash even with cyclical dependencies. When states form a cycle where values eventually stabilize, the system handles these updates efficiently without stack overflows.
240
+
241
+ This dual approach prevents accidental infinite loops while still supporting legitimate cyclic update patterns that eventually stabilize.
169
242
 
170
243
  </details>
171
244
 
172
245
  <details>
173
246
 
174
247
  <summary>How performant is Beacon?</summary>
175
- Beacon is designed with performance in mind for server-side Node.js environments. It achieves millions of operations per second for core operations like reading and writing signals.
248
+ Beacon is designed with performance in mind for server-side Node.js environments. It achieves millions of operations per second for core operations like reading and writing states.
176
249
 
177
250
  </details>
178
251
 
179
252
  ## License
180
253
 
181
- This project is licensed under the MIT License. See the [LICENSE][3] file for details.
254
+ This project is licensed under the MIT License. See the [LICENSE][2] file for details.
255
+
256
+ <div align="center">
257
+ <img src="https://raw.githubusercontent.com/nerdalytics/nerdalytics/refs/heads/main/nerdalytics-logo-gray-transparent.svg" width="128px">
258
+ </div>
182
259
 
183
260
  <!-- Links collection -->
184
261
 
185
262
  [1]: https://github.com/tc39/proposal-signals
186
- [2]: ./TECHNICAL_DETAILS.md
187
- [3]: ./LICENSE
263
+ [2]: ./LICENSE
package/package.json CHANGED
@@ -1,58 +1,79 @@
1
1
  {
2
2
  "name": "@nerdalytics/beacon",
3
- "version": "1.0.0",
4
- "description": "A lightweight reactive signal library for Node.js backends. Enables reactive state management with automatic dependency tracking and efficient updates for server-side applications.",
3
+ "version": "1000.0.0",
4
+ "description": "A lightweight reactive state library for Node.js backends. Enables reactive state management with automatic dependency tracking and efficient updates for server-side applications.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
8
  "files": [
9
- "dist/",
9
+ "dist/index.js",
10
+ "dist/index.d.ts",
10
11
  "src/",
11
12
  "LICENSE"
12
13
  ],
14
+ "repository": {
15
+ "url": "github:nerdalytics/beacon",
16
+ "type": "git"
17
+ },
13
18
  "scripts": {
14
- "test": "node --test --experimental-config-file=node.config.json \"test/**/*.test.ts\"",
15
- "test:coverage": "node --test --experimental-config-file=node.config.json --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info \"test/**/*.test.ts\"",
16
- "test:unit": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^(State|Derived|Effect|Batch|Cleanup|Cyclic Dependencies)$/\"",
17
- "test:unit:state": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^State$/\"",
18
- "test:unit:derived": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^Derived$/\"",
19
- "test:unit:effect": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^Effect$/\"",
20
- "test:unit:batch": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^Batch$/\"",
21
- "test:unit:cleanup": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^Cleanup$/\"",
22
- "test:unit:cyclic": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^Cyclic Dependencies$/\"",
23
- "test:integration": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^Deep Dependency Chains$/\"",
24
- "test:perf": "node --test --experimental-config-file=node.config.json --test-name-pattern=\"/^Performance$/\"",
25
- "test:perf:update-docs": "node scripts/update-performance-docs.ts",
26
- "format": "biome format --write .",
27
- "prebuild": "rm -rf dist/",
19
+ "lint": "npx @biomejs/biome lint --config-path=./biome.json",
20
+ "lint:fix": "npx @biomejs/biome lint --fix --config-path=./biome.json",
21
+ "lint:fix:unsafe": "npx @biomejs/biome lint --fix --unsafe --config-path=./biome.json",
22
+ "format": "npx @biomejs/biome format src --write --config-path=./biome.json",
23
+ "check": "npx @biomejs/biome check src --config-path=./biome.json",
24
+ "check:fix": "npx @biomejs/biome format src --fix --config-path=./biome.json",
25
+
26
+ "test": "node --test --test-skip-pattern=\"COMPONENT NAME\" tests/**/*.ts",
27
+ "test:coverage": "node --test --experimental-config-file=node.config.json --test-skip-pattern=\"[COMPONENT NAME]\" --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info tests/**/*.ts",
28
+ "test:unit:state": "node --test tests/state.test.ts",
29
+ "test:unit:effect": "node --test tests/effect.test.ts",
30
+ "test:unit:batch": "node --test tests/batch.test.ts",
31
+ "test:unit:derive": "node --test tests/derive.test.ts",
32
+ "test:unit:select": "node --test tests/select.test.ts",
33
+ "test:unit:cleanup": "node --test tests/cleanup.test.ts",
34
+ "test:unit:cyclic-dependency": "node --test tests/cyclic-dependency.test.ts",
35
+ "test:unit:deep-chain": "node --test tests/deep-chain.test.ts",
36
+ "test:unit:infinite-loop": "node --test tests/infinite-loop.test.ts",
37
+
38
+ "benchmark": "node scripts/benchmark.ts",
39
+
28
40
  "build": "npm run build:lts",
29
- "build:lts": "tsc -p tsconfig.build.json",
30
- "prepublishOnly": "npm run build"
41
+ "prebuild:lts": "rm -rf dist/",
42
+ "build:lts": "tsc -p tsconfig.lts.json",
43
+ "prepublishOnly": "npm run build:lts",
44
+
45
+ "pretest:lts": "npm run build:lts",
46
+ "test:lts": "node scripts/run-lts-tests.js",
47
+
48
+ "update-performance-docs": "node --experimental-config-file=node.config.json scripts/update-performance-docs.ts"
31
49
  },
32
50
  "keywords": [
33
- "reactive",
34
- "signals",
35
51
  "state-management",
36
- "nodejs",
37
- "typescript",
38
- "reactive-programming",
52
+ "effects",
53
+ "fine-grained",
54
+ "computed-values",
55
+ "batching",
56
+ "signals",
57
+ "reactive",
58
+ "lightweight",
59
+ "performance",
39
60
  "dependency-tracking",
40
- "esm",
41
- "observable",
42
- "backend",
61
+ "memoization",
62
+ "memory-management",
63
+ "nodejs",
43
64
  "server-side",
44
- "computed-values",
45
- "effects",
46
- "batching"
65
+ "backend",
66
+ "typescript"
47
67
  ],
48
- "author": "Denny Trebbin",
68
+ "author": "Denny Trebbin (nerdalytics)",
49
69
  "license": "MIT",
50
70
  "devDependencies": {
51
71
  "@biomejs/biome": "1.9.4",
52
- "@types/node": "22.13.16",
53
- "typescript": "5.8.2"
72
+ "@types/node": "22.14.0",
73
+ "typescript": "5.8.3"
54
74
  },
55
75
  "engines": {
56
76
  "node": ">=20.0.0"
57
- }
77
+ },
78
+ "packageManager": "npm@11.2.0"
58
79
  }
package/src/index.ts CHANGED
@@ -1,175 +1,427 @@
1
- // Types
1
+ // Core types for reactive primitives
2
2
  type Subscriber = () => void
3
-
4
3
  type Unsubscribe = () => void
5
-
6
- export interface Signal<T> {
7
- (): T // get value
8
- set(value: T): void // set value directly
9
- update(fn: (currentValue: T) => T): void // update value with a function
4
+ export type ReadOnlyState<T> = () => T
5
+ export interface WriteableState<T> {
6
+ set(value: T): void
7
+ update(fn: (value: T) => T): void
10
8
  }
11
9
 
12
- // Global state for tracking
13
- let currentEffect: Subscriber | null = null
10
+ // Special symbol used for internal tracking
11
+ const STATE_ID = Symbol()
14
12
 
15
- let batchDepth = 0
13
+ export type State<T> = ReadOnlyState<T> &
14
+ WriteableState<T> & {
15
+ [STATE_ID]?: symbol
16
+ }
16
17
 
17
- const pendingEffects = new Set<Subscriber>()
18
+ /**
19
+ * Creates a reactive state container with the provided initial value.
20
+ */
21
+ export const state = <T>(initialValue: T): State<T> => StateImpl.createState(initialValue)
18
22
 
19
- const subscriberDependencies = new WeakMap<Subscriber, Set<Set<Subscriber>>>()
23
+ /**
24
+ * Registers a function to run whenever its reactive dependencies change.
25
+ */
26
+ export const effect = (fn: () => void): Unsubscribe => StateImpl.createEffect(fn)
20
27
 
21
- // Use a flag to prevent multiple updates from running the effects
22
- let updateInProgress = false
28
+ /**
29
+ * Groups multiple state updates to trigger effects only once at the end.
30
+ */
31
+ export const batch = <T>(fn: () => T): T => StateImpl.executeBatch(fn)
23
32
 
24
33
  /**
25
- * Creates a new reactive state with the provided initial value
34
+ * Creates a read-only computed value that updates when its dependencies change.
26
35
  */
27
- export const state = <T>(initialValue: T): Signal<T> => {
28
- let value = initialValue
36
+ export const derive = <T>(computeFn: () => T): ReadOnlyState<T> => StateImpl.createDerive(computeFn)
29
37
 
30
- const subscribers = new Set<Subscriber>()
38
+ /**
39
+ * Creates an efficient subscription to a subset of a state value.
40
+ */
41
+ export const select = <T, R>(
42
+ source: ReadOnlyState<T>,
43
+ selectorFn: (state: T) => R,
44
+ equalityFn: (a: R, b: R) => boolean = Object.is
45
+ ): ReadOnlyState<R> => StateImpl.createSelect(source, selectorFn, equalityFn)
31
46
 
32
- const read = (): T => {
33
- if (currentEffect) {
34
- subscribers.add(currentEffect)
47
+ /**
48
+ * Creates a read-only view of a state, hiding mutation methods.
49
+ */
50
+ export const readonlyState =
51
+ <T>(state: State<T>): ReadOnlyState<T> =>
52
+ (): T =>
53
+ state()
54
+
55
+ /**
56
+ * Creates a state with access control, returning a tuple of reader and writer.
57
+ */
58
+ export const protectedState = <T>(initialValue: T): [ReadOnlyState<T>, WriteableState<T>] => {
59
+ const fullState = state(initialValue)
60
+ return [
61
+ (): T => readonlyState(fullState)(),
62
+ {
63
+ set: (value: T): void => fullState.set(value),
64
+ update: (fn: (value: T) => T): void => fullState.update(fn),
65
+ },
66
+ ]
67
+ }
35
68
 
36
- let dependencies = subscriberDependencies.get(currentEffect)
69
+ class StateImpl<T> {
70
+ // Static fields track global reactivity state - this centralized approach allows
71
+ // for coordinated updates while maintaining individual state isolation
72
+ private static currentSubscriber: Subscriber | null = null
73
+ private static pendingSubscribers = new Set<Subscriber>()
74
+ private static isNotifying = false
75
+ private static batchDepth = 0
76
+ private static deferredEffectCreations: Subscriber[] = []
77
+ private static activeSubscribers = new Set<Subscriber>()
78
+
79
+ // WeakMaps enable automatic garbage collection when subscribers are no
80
+ // longer referenced, preventing memory leaks in long-running applications
81
+ private static stateTracking = new WeakMap<Subscriber, Set<symbol>>()
82
+ private static subscriberDependencies = new WeakMap<Subscriber, Set<Set<Subscriber>>>()
83
+ private static parentSubscriber = new WeakMap<Subscriber, Subscriber>()
84
+ private static childSubscribers = new WeakMap<Subscriber, Set<Subscriber>>()
85
+
86
+ // Instance state - each state has unique subscribers and ID
87
+ private value: T
88
+ private subscribers = new Set<Subscriber>()
89
+ private stateId = Symbol()
90
+
91
+ constructor(initialValue: T) {
92
+ this.value = initialValue
93
+ }
94
+
95
+ // Creates a callable function that both reads and writes state -
96
+ // this design maintains JavaScript idioms while adding reactivity
97
+ static createState = <T>(initialValue: T): State<T> => {
98
+ const instance = new StateImpl<T>(initialValue)
99
+ const get = (): T => instance.get()
100
+ get.set = (value: T): void => instance.set(value)
101
+ get.update = (fn: (currentValue: T) => T): void => instance.update(fn)
102
+ get[STATE_ID] = instance.stateId
103
+ return get as State<T>
104
+ }
37
105
 
106
+ // Auto-tracks dependencies when called within effects, creating a fine-grained
107
+ // reactivity graph that only updates affected components
108
+ get = (): T => {
109
+ const currentEffect = StateImpl.currentSubscriber
110
+ if (currentEffect) {
111
+ // Add this effect to subscribers for future notification
112
+ this.subscribers.add(currentEffect)
113
+
114
+ // Maintain bidirectional dependency tracking to enable precise cleanup
115
+ // when effects are unsubscribed, preventing memory leaks
116
+ let dependencies = StateImpl.subscriberDependencies.get(currentEffect)
38
117
  if (!dependencies) {
39
118
  dependencies = new Set()
40
-
41
- subscriberDependencies.set(currentEffect, dependencies)
119
+ StateImpl.subscriberDependencies.set(currentEffect, dependencies)
42
120
  }
43
-
44
- dependencies.add(subscribers)
121
+ dependencies.add(this.subscribers)
122
+
123
+ // Track read states to detect direct cyclical dependencies that
124
+ // could cause infinite loops
125
+ let readStates = StateImpl.stateTracking.get(currentEffect)
126
+ if (!readStates) {
127
+ readStates = new Set()
128
+ StateImpl.stateTracking.set(currentEffect, readStates)
129
+ }
130
+ readStates.add(this.stateId)
45
131
  }
46
-
47
- return value
132
+ return this.value
48
133
  }
49
134
 
50
- const write = (newValue: T): void => {
51
- if (Object.is(value, newValue)) {
52
- return // No change
135
+ // Handles value updates with built-in optimizations and safeguards
136
+ set = (newValue: T): void => {
137
+ // Skip updates for unchanged values to prevent redundant effect executions
138
+ if (Object.is(this.value, newValue)) {
139
+ return
140
+ }
141
+
142
+ // Infinite loop detection prevents direct self-mutation within effects,
143
+ // while allowing nested effect patterns that would otherwise appear cyclical
144
+ const effect = StateImpl.currentSubscriber
145
+ if (effect) {
146
+ const states = StateImpl.stateTracking.get(effect)
147
+ if (states?.has(this.stateId) && !StateImpl.parentSubscriber.get(effect)) {
148
+ throw new Error('Infinite loop detected: effect() cannot update a state() it depends on!')
149
+ }
53
150
  }
54
- value = newValue
55
151
 
56
- if (subscribers.size === 0) {
152
+ this.value = newValue
153
+
154
+ // Skip updates when there are no subscribers, avoiding unnecessary processing
155
+ if (this.subscribers.size === 0) {
57
156
  return
58
157
  }
59
158
 
60
- // Add subscribers to pendingEffects - always use loop for better performance
61
- for (const sub of subscribers) {
62
- pendingEffects.add(sub)
159
+ // Queue notifications instead of executing immediately to support batch operations
160
+ // and prevent redundant effect runs
161
+ for (const sub of this.subscribers) {
162
+ StateImpl.pendingSubscribers.add(sub)
63
163
  }
64
164
 
65
- if (batchDepth === 0 && !updateInProgress) {
66
- processEffects()
165
+ // Immediate execution outside of batches, deferred execution inside batches
166
+ if (StateImpl.batchDepth === 0 && !StateImpl.isNotifying) {
167
+ StateImpl.notifySubscribers()
67
168
  }
68
169
  }
69
170
 
70
- const update = (fn: (currentValue: T) => T): void => {
71
- write(fn(value))
171
+ update = (fn: (currentValue: T) => T): void => {
172
+ this.set(fn(this.value))
72
173
  }
73
174
 
74
- return Object.assign(read, { set: write, update })
75
- }
175
+ // Creates an effect that automatically tracks and responds to state changes
176
+ static createEffect = (fn: () => void): Unsubscribe => {
177
+ const runEffect = (): void => {
178
+ // Prevent re-entrance to avoid cascade updates during effect execution
179
+ if (StateImpl.activeSubscribers.has(runEffect)) {
180
+ return
181
+ }
76
182
 
77
- /**
78
- * Process all pending effects, ensuring full propagation through the dependency chain
79
- */
80
- const processEffects = (): void => {
81
- if (pendingEffects.size === 0 || updateInProgress) {
82
- return
83
- }
183
+ StateImpl.activeSubscribers.add(runEffect)
184
+ const parentEffect = StateImpl.currentSubscriber
185
+
186
+ try {
187
+ // Clean existing subscriptions before running to ensure only
188
+ // currently accessed states are tracked as dependencies
189
+ StateImpl.cleanupEffect(runEffect)
190
+
191
+ // Set current context for automatic dependency tracking
192
+ StateImpl.currentSubscriber = runEffect
193
+ StateImpl.stateTracking.set(runEffect, new Set())
194
+
195
+ // Track parent-child relationships to handle nested effects correctly
196
+ // and enable hierarchical cleanup later
197
+ if (parentEffect) {
198
+ StateImpl.parentSubscriber.set(runEffect, parentEffect)
199
+ let children = StateImpl.childSubscribers.get(parentEffect)
200
+ if (!children) {
201
+ children = new Set()
202
+ StateImpl.childSubscribers.set(parentEffect, children)
203
+ }
204
+ children.add(runEffect)
205
+ }
206
+
207
+ // Execute the effect function, which will auto-track dependencies
208
+ fn()
209
+ } finally {
210
+ // Restore previous context when done
211
+ StateImpl.currentSubscriber = parentEffect
212
+ StateImpl.activeSubscribers.delete(runEffect)
213
+ }
214
+ }
84
215
 
85
- updateInProgress = true
216
+ // Run immediately unless we're in a batch operation
217
+ if (StateImpl.batchDepth === 0) {
218
+ runEffect()
219
+ } else {
220
+ // Still track parent-child relationship even when deferred,
221
+ // ensuring proper hierarchical cleanup later
222
+ if (StateImpl.currentSubscriber) {
223
+ const parent = StateImpl.currentSubscriber
224
+ StateImpl.parentSubscriber.set(runEffect, parent)
225
+ let children = StateImpl.childSubscribers.get(parent)
226
+ if (!children) {
227
+ children = new Set()
228
+ StateImpl.childSubscribers.set(parent, children)
229
+ }
230
+ children.add(runEffect)
231
+ }
86
232
 
87
- while (pendingEffects.size > 0) {
88
- const currentEffects = [...pendingEffects]
89
- pendingEffects.clear()
233
+ // Queue for execution when batch completes
234
+ StateImpl.deferredEffectCreations.push(runEffect)
235
+ }
90
236
 
91
- for (const effect of currentEffects) {
92
- effect()
237
+ // Return cleanup function to properly disconnect from reactivity graph
238
+ return (): void => {
239
+ // Remove from dependency tracking to stop future notifications
240
+ StateImpl.cleanupEffect(runEffect)
241
+ StateImpl.pendingSubscribers.delete(runEffect)
242
+ StateImpl.activeSubscribers.delete(runEffect)
243
+ StateImpl.stateTracking.delete(runEffect)
244
+
245
+ // Clean up parent-child relationship bidirectionally
246
+ const parent = StateImpl.parentSubscriber.get(runEffect)
247
+ if (parent) {
248
+ const siblings = StateImpl.childSubscribers.get(parent)
249
+ if (siblings) {
250
+ siblings.delete(runEffect)
251
+ }
252
+ }
253
+ StateImpl.parentSubscriber.delete(runEffect)
254
+
255
+ // Recursively clean up child effects to prevent memory leaks in
256
+ // nested effect scenarios
257
+ const children = StateImpl.childSubscribers.get(runEffect)
258
+ if (children) {
259
+ for (const child of children) {
260
+ StateImpl.cleanupEffect(child)
261
+ }
262
+ children.clear()
263
+ StateImpl.childSubscribers.delete(runEffect)
264
+ }
93
265
  }
94
266
  }
95
267
 
96
- updateInProgress = false
97
- }
98
-
99
- /**
100
- * Helper to clean up effect subscriptions
101
- */
102
- const cleanupEffect = (effect: Subscriber): void => {
103
- const deps = subscriberDependencies.get(effect)
104
-
105
- if (deps) {
106
- for (const subscribers of deps) {
107
- subscribers.delete(effect)
268
+ // Batches state updates to improve performance by reducing redundant effect runs
269
+ static executeBatch = <T>(fn: () => T): T => {
270
+ // Increment depth counter to handle nested batches correctly
271
+ StateImpl.batchDepth++
272
+ try {
273
+ return fn()
274
+ } catch (error: unknown) {
275
+ // Clean up on error to prevent stale subscribers from executing
276
+ // and potentially causing cascading errors
277
+ if (StateImpl.batchDepth === 1) {
278
+ StateImpl.pendingSubscribers.clear()
279
+ StateImpl.deferredEffectCreations.length = 0
280
+ }
281
+ throw error
282
+ } finally {
283
+ StateImpl.batchDepth--
284
+
285
+ // Only process effects when exiting the outermost batch,
286
+ // maintaining proper execution order while avoiding redundant runs
287
+ if (StateImpl.batchDepth === 0) {
288
+ // Process effects created during the batch
289
+ if (StateImpl.deferredEffectCreations.length > 0) {
290
+ const effectsToRun = [...StateImpl.deferredEffectCreations]
291
+ StateImpl.deferredEffectCreations.length = 0
292
+ for (const effect of effectsToRun) {
293
+ effect()
294
+ }
295
+ }
296
+
297
+ // Process state updates that occurred during the batch
298
+ if (StateImpl.pendingSubscribers.size > 0 && !StateImpl.isNotifying) {
299
+ StateImpl.notifySubscribers()
300
+ }
301
+ }
108
302
  }
109
-
110
- deps.clear()
111
303
  }
112
- }
113
-
114
- /**
115
- * Creates an effect that runs when its dependencies change
116
- */
117
- export const effect = (fn: () => void): Unsubscribe => {
118
- const runEffect = (): void => {
119
- cleanupEffect(runEffect)
120
304
 
121
- const prevEffect = currentEffect
305
+ // Creates a derived state that memoizes computations and updates only when dependencies change
306
+ static createDerive = <T>(computeFn: () => T): ReadOnlyState<T> => {
307
+ const valueState = StateImpl.createState<T | undefined>(undefined)
308
+ let initialized = false
309
+ let cachedValue: T
310
+
311
+ // Internal effect automatically tracks dependencies and updates the derived value
312
+ StateImpl.createEffect((): void => {
313
+ const newValue = computeFn()
314
+
315
+ // Only update if the value actually changed to preserve referential equality
316
+ // and prevent unnecessary downstream updates
317
+ if (!(initialized && Object.is(cachedValue, newValue))) {
318
+ cachedValue = newValue
319
+ valueState.set(newValue)
320
+ }
122
321
 
123
- currentEffect = runEffect
322
+ initialized = true
323
+ })
124
324
 
125
- try {
126
- fn()
127
- } finally {
128
- currentEffect = prevEffect
325
+ // Return function with lazy initialization - ensures value is available
326
+ // even when accessed before its dependencies have had a chance to update
327
+ return (): T => {
328
+ if (!initialized) {
329
+ cachedValue = computeFn()
330
+ initialized = true
331
+ valueState.set(cachedValue)
332
+ }
333
+ return valueState() as T
129
334
  }
130
335
  }
131
336
 
132
- runEffect()
337
+ // Creates a selector that monitors a slice of state with performance optimizations
338
+ static createSelect = <T, R>(
339
+ source: ReadOnlyState<T>,
340
+ selectorFn: (state: T) => R,
341
+ equalityFn: (a: R, b: R) => boolean = Object.is
342
+ ): ReadOnlyState<R> => {
343
+ let lastSourceValue: T | undefined
344
+ let lastSelectedValue: R | undefined
345
+ let initialized = false
346
+ const valueState = StateImpl.createState<R | undefined>(undefined)
347
+
348
+ // Internal effect to track the source and update only when needed
349
+ StateImpl.createEffect((): void => {
350
+ const sourceValue = source()
351
+
352
+ // Skip computation if source reference hasn't changed
353
+ if (initialized && Object.is(lastSourceValue, sourceValue)) {
354
+ return
355
+ }
133
356
 
134
- return (): void => {
135
- cleanupEffect(runEffect)
136
- }
137
- }
357
+ lastSourceValue = sourceValue
358
+ const newSelectedValue = selectorFn(sourceValue)
138
359
 
139
- /**
140
- * Creates a derived signal that computes its value from other signals
141
- */
142
- export const derived = <T>(fn: () => T): Signal<T> => {
143
- // Initialize signal with the computed value
144
- const signal = state<T>(fn())
360
+ // Use custom equality function to determine if value semantically changed,
361
+ // allowing for deep equality comparisons with complex objects
362
+ if (initialized && lastSelectedValue !== undefined && equalityFn(lastSelectedValue, newSelectedValue)) {
363
+ return
364
+ }
145
365
 
146
- // Only run fn() again when dependencies change
147
- effect((): void => {
148
- signal.set(fn())
149
- })
366
+ // Update cache and notify subscribers due the value has changed
367
+ lastSelectedValue = newSelectedValue
368
+ valueState.set(newSelectedValue)
369
+ initialized = true
370
+ })
371
+
372
+ // Return function with eager initialization capability
373
+ return (): R => {
374
+ if (!initialized) {
375
+ lastSourceValue = source()
376
+ lastSelectedValue = selectorFn(lastSourceValue)
377
+ valueState.set(lastSelectedValue)
378
+ initialized = true
379
+ }
380
+ return valueState() as R
381
+ }
382
+ }
150
383
 
151
- return signal
152
- }
384
+ // Processes queued subscriber notifications in a controlled, non-reentrant way
385
+ private static notifySubscribers = (): void => {
386
+ // Prevent reentrance to avoid cascading notification loops when
387
+ // effects trigger further state changes
388
+ if (StateImpl.isNotifying) {
389
+ return
390
+ }
153
391
 
154
- /**
155
- * Batches multiple updates to run effects only once at the end
156
- */
157
- export const batch = <T>(fn: () => T): T => {
158
- batchDepth++
159
-
160
- try {
161
- return fn()
162
- } catch (error) {
163
- if (batchDepth === 1) {
164
- pendingEffects.clear()
392
+ StateImpl.isNotifying = true
393
+
394
+ try {
395
+ // Process all pending effects in batches for better perf,
396
+ // ensuring topological execution order is maintained
397
+ while (StateImpl.pendingSubscribers.size > 0) {
398
+ // Process in snapshot batches to prevent infinite loops
399
+ // when effects trigger further state changes
400
+ const subscribers = Array.from(StateImpl.pendingSubscribers)
401
+ StateImpl.pendingSubscribers.clear()
402
+
403
+ for (const effect of subscribers) {
404
+ effect()
405
+ }
406
+ }
407
+ } finally {
408
+ StateImpl.isNotifying = false
165
409
  }
410
+ }
166
411
 
167
- throw error
168
- } finally {
169
- batchDepth--
412
+ // Removes effect from dependency tracking to prevent memory leaks
413
+ private static cleanupEffect = (effect: Subscriber): void => {
414
+ // Remove from execution queue to prevent stale updates
415
+ StateImpl.pendingSubscribers.delete(effect)
170
416
 
171
- if (batchDepth === 0 && pendingEffects.size > 0) {
172
- processEffects()
417
+ // Remove bidirectional dependency references to prevent memory leaks
418
+ const deps = StateImpl.subscriberDependencies.get(effect)
419
+ if (deps) {
420
+ for (const subscribers of deps) {
421
+ subscribers.delete(effect)
422
+ }
423
+ deps.clear()
424
+ StateImpl.subscriberDependencies.delete(effect)
173
425
  }
174
426
  }
175
427
  }
package/dist/index.d.ts DELETED
@@ -1,23 +0,0 @@
1
- type Unsubscribe = () => void;
2
- export interface Signal<T> {
3
- (): T;
4
- set(value: T): void;
5
- update(fn: (currentValue: T) => T): void;
6
- }
7
- /**
8
- * Creates a new reactive state with the provided initial value
9
- */
10
- export declare const state: <T>(initialValue: T) => Signal<T>;
11
- /**
12
- * Creates an effect that runs when its dependencies change
13
- */
14
- export declare const effect: (fn: () => void) => Unsubscribe;
15
- /**
16
- * Creates a derived signal that computes its value from other signals
17
- */
18
- export declare const derived: <T>(fn: () => T) => Signal<T>;
19
- /**
20
- * Batches multiple updates to run effects only once at the end
21
- */
22
- export declare const batch: <T>(fn: () => T) => T;
23
- export {};
package/dist/index.js DELETED
@@ -1,129 +0,0 @@
1
- // Global state for tracking
2
- let currentEffect = null;
3
- let batchDepth = 0;
4
- const pendingEffects = new Set();
5
- const subscriberDependencies = new WeakMap();
6
- // Use a flag to prevent multiple updates from running the effects
7
- let updateInProgress = false;
8
- /**
9
- * Creates a new reactive state with the provided initial value
10
- */
11
- export const state = (initialValue) => {
12
- let value = initialValue;
13
- const subscribers = new Set();
14
- const read = () => {
15
- if (currentEffect) {
16
- subscribers.add(currentEffect);
17
- let dependencies = subscriberDependencies.get(currentEffect);
18
- if (!dependencies) {
19
- dependencies = new Set();
20
- subscriberDependencies.set(currentEffect, dependencies);
21
- }
22
- dependencies.add(subscribers);
23
- }
24
- return value;
25
- };
26
- const write = (newValue) => {
27
- if (Object.is(value, newValue)) {
28
- return; // No change
29
- }
30
- value = newValue;
31
- if (subscribers.size === 0) {
32
- return;
33
- }
34
- // Add subscribers to pendingEffects - always use loop for better performance
35
- for (const sub of subscribers) {
36
- pendingEffects.add(sub);
37
- }
38
- if (batchDepth === 0 && !updateInProgress) {
39
- processEffects();
40
- }
41
- };
42
- const update = (fn) => {
43
- write(fn(value));
44
- };
45
- return Object.assign(read, { set: write, update });
46
- };
47
- /**
48
- * Process all pending effects, ensuring full propagation through the dependency chain
49
- */
50
- const processEffects = () => {
51
- if (pendingEffects.size === 0 || updateInProgress) {
52
- return;
53
- }
54
- updateInProgress = true;
55
- while (pendingEffects.size > 0) {
56
- const currentEffects = [...pendingEffects];
57
- pendingEffects.clear();
58
- for (const effect of currentEffects) {
59
- effect();
60
- }
61
- }
62
- updateInProgress = false;
63
- };
64
- /**
65
- * Helper to clean up effect subscriptions
66
- */
67
- const cleanupEffect = (effect) => {
68
- const deps = subscriberDependencies.get(effect);
69
- if (deps) {
70
- for (const subscribers of deps) {
71
- subscribers.delete(effect);
72
- }
73
- deps.clear();
74
- }
75
- };
76
- /**
77
- * Creates an effect that runs when its dependencies change
78
- */
79
- export const effect = (fn) => {
80
- const runEffect = () => {
81
- cleanupEffect(runEffect);
82
- const prevEffect = currentEffect;
83
- currentEffect = runEffect;
84
- try {
85
- fn();
86
- }
87
- finally {
88
- currentEffect = prevEffect;
89
- }
90
- };
91
- runEffect();
92
- return () => {
93
- cleanupEffect(runEffect);
94
- };
95
- };
96
- /**
97
- * Creates a derived signal that computes its value from other signals
98
- */
99
- export const derived = (fn) => {
100
- // Initialize signal with the computed value
101
- const signal = state(fn());
102
- // Only run fn() again when dependencies change
103
- effect(() => {
104
- signal.set(fn());
105
- });
106
- return signal;
107
- };
108
- /**
109
- * Batches multiple updates to run effects only once at the end
110
- */
111
- export const batch = (fn) => {
112
- batchDepth++;
113
- try {
114
- return fn();
115
- }
116
- catch (error) {
117
- if (batchDepth === 1) {
118
- pendingEffects.clear();
119
- }
120
- throw error;
121
- }
122
- finally {
123
- batchDepth--;
124
- if (batchDepth === 0 && pendingEffects.size > 0) {
125
- processEffects();
126
- }
127
- }
128
- };
129
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAWA,4BAA4B;AAC5B,IAAI,aAAa,GAAsB,IAAI,CAAA;AAE3C,IAAI,UAAU,GAAG,CAAC,CAAA;AA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