@alwatr/signal 6.0.0 → 6.0.2
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/CHANGELOG.md +20 -0
- package/README.md +13 -13
- package/dist/core/computed-signal.d.ts.map +1 -1
- package/dist/core/effect-signal.d.ts.map +1 -1
- package/dist/core/event-signal.d.ts.map +1 -1
- package/dist/core/signal-base.d.ts.map +1 -1
- package/dist/core/state-signal.d.ts.map +1 -1
- package/dist/main.cjs +2 -1
- package/dist/main.cjs.map +2 -2
- package/dist/main.mjs +2 -1
- package/dist/main.mjs.map +2 -2
- package/package.json +10 -9
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,26 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [6.0.2](https://github.com/Alwatr/flux/compare/v6.0.1...v6.0.2) (2025-09-21)
|
|
7
|
+
|
|
8
|
+
### 🔗 Dependencies update
|
|
9
|
+
|
|
10
|
+
* update dependencies for @alwatr/nano-build, @alwatr/logger, @alwatr/debounce, and @alwatr/delay ([e7cfed5](https://github.com/Alwatr/flux/commit/e7cfed56bd6a7e7cd402e6f38c415de5737f5b24))
|
|
11
|
+
|
|
12
|
+
## [6.0.1](https://github.com/Alwatr/flux/compare/v6.0.0...v6.0.1) (2025-09-20)
|
|
13
|
+
|
|
14
|
+
### 🐛 Bug Fixes
|
|
15
|
+
|
|
16
|
+
* add sideEffects property to package.json for fsm and signal packages ([37d175c](https://github.com/Alwatr/flux/commit/37d175c2cd16144449dfa72e7504a4d179f1cb01))
|
|
17
|
+
|
|
18
|
+
### 🔨 Code Refactoring
|
|
19
|
+
|
|
20
|
+
* remove public access modifier from constructors in signal classes ([afb42da](https://github.com/Alwatr/flux/commit/afb42da7fd812cd09555c43ac9489ef15efce96a))
|
|
21
|
+
|
|
22
|
+
### 🔗 Dependencies update
|
|
23
|
+
|
|
24
|
+
* update alwatr dependencies ([19bd8a5](https://github.com/Alwatr/flux/commit/19bd8a597a4e74b620e04a497eff7247a03bf8b8))
|
|
25
|
+
|
|
6
26
|
## [6.0.0](https://github.com/Alwatr/flux/compare/v5.2.2...v6.0.0) (2025-09-19)
|
|
7
27
|
|
|
8
28
|
### ✨ Features
|
package/README.md
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
# Alwatr Signal
|
|
2
2
|
|
|
3
|
+
[](https://www.google.com/search?q=alwatr+flux)
|
|
4
|
+
[](https://www.google.com/search?q=alwatr+signal)
|
|
5
|
+
[](https://www.google.com/search?q=alwatr)
|
|
6
|
+
[](https://www.npmjs.com/package/%40alwatr/flux)
|
|
7
|
+
[](https://www.npmjs.com/package/%40alwatr/signal)
|
|
8
|
+
|
|
3
9
|
Alwatr Signal is a powerful, lightweight, and modern reactive programming library. It is inspired by the best concepts from major reactive libraries but engineered to be faster and more efficient than all of them. It provides a robust and elegant way to manage application state through a system of signals, offering fine-grained reactivity, predictability, and excellent performance.
|
|
4
10
|
|
|
5
11
|
It's designed to be simple to learn, yet capable of handling complex state management scenarios.
|
|
6
12
|
|
|
7
|
-
[](https://www.google.com/search?q=https://www.npmjs.com/package/%40alwatr/signal)
|
|
8
|
-
[](https://www.google.com/search?q=https://www.npmjs.com/package/%40alwatr/flux)
|
|
9
|
-
[](https://www.google.com/search?q=alwatr+signal)
|
|
10
|
-
[](https://www.google.com/search?q=alwatr+flux)
|
|
11
|
-
[](https://www.google.com/search?q=alwatr)
|
|
12
|
-
|
|
13
13
|
## Features
|
|
14
14
|
|
|
15
15
|
- **Type-Safe**: Fully implemented in TypeScript for robust, type-safe code.
|
|
@@ -221,16 +221,16 @@ Contributions are welcome! Please read our [contribution guidelines](https://git
|
|
|
221
221
|
|
|
222
222
|
# Alwatr Signal (راهنمای فارسی)
|
|
223
223
|
|
|
224
|
+
[](https://www.google.com/search?q=alwatr+flux)
|
|
225
|
+
[](https://www.google.com/search?q=alwatr+signal)
|
|
226
|
+
[](https://www.google.com/search?q=alwatr)
|
|
227
|
+
[](https://www.npmjs.com/package/%40alwatr/flux)
|
|
228
|
+
[](https://www.npmjs.com/package/%40alwatr/signal)
|
|
229
|
+
|
|
224
230
|
کتابخانه Alwatr Signal یک ابزار قدرتمند، سبک و مدرن برای برنامهنویسی واکنشی (Reactive Programming) است. این کتابخانه با الگوبرداری از بهترین مفاهیم بزرگترین کتابخانههای واکنشی طراحی شده، اما مهندسی آن به گونهای است که از تمام آنها سریعتر و کارآمدتر باشد. این کتابخانه روشی استوار و زیبا برای مدیریت وضعیت برنامه از طریق سیگنالها ارائه میدهد و واکنشپذیری دقیق (fine-grained reactivity)، پیشبینیپذیری و عملکرد عالی را به ارمغان میآورد.
|
|
225
231
|
|
|
226
232
|
طراحی آن به گونهای است که یادگیری آن ساده باشد، اما در عین حال قادر به مدیریت سناریوهای پیچیده مدیریت وضعیت نیز باشد.
|
|
227
233
|
|
|
228
|
-
[](https://www.google.com/search?q=https://www.npmjs.com/package/%40alwatr/signal)
|
|
229
|
-
[](https://www.google.com/search?q=https://www.npmjs.com/package/%40alwatr/flux)
|
|
230
|
-
[](https://www.google.com/search?q=alwatr+signal)
|
|
231
|
-
[](https://www.google.com/search?q=alwatr+flux)
|
|
232
|
-
[](https://www.google.com/search?q=alwatr)
|
|
233
|
-
|
|
234
234
|
## ویژگیها
|
|
235
235
|
|
|
236
236
|
- **ایمنی نوع (Type-Safe)**: به طور کامل با TypeScript پیادهسازی شده تا کدی قوی و ایمن از نظر نوع داشته باشید.
|
|
@@ -370,7 +370,7 @@ const isEven = new ComputedSignal({
|
|
|
370
370
|
isEven.destroy();
|
|
371
371
|
```
|
|
372
372
|
|
|
373
|
-
فراخوانی `destroy()` اشتراک سیگنال را از تمام وابستگیهایش لغو میکند و به
|
|
373
|
+
فراخوانی `destroy()` اشتراک سیگنال را از تمام وابستگیهایش لغو میکند و به جمعآورنده زباله (garbage collector) اجازه میدهد آن را با خیال راحت پاک کند.
|
|
374
374
|
|
|
375
375
|
### نوتیفیکیشنهای ناهمزمان (Asynchronous)
|
|
376
376
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"computed-signal.d.ts","sourceRoot":"","sources":["../../src/core/computed-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,WAAW,EAAC,MAAM,mBAAmB,CAAC;AAE9C,OAAO,KAAK,EAAC,oBAAoB,EAAE,eAAe,EAAE,eAAe,EAAE,gBAAgB,EAAC,MAAM,YAAY,CAAC;AAEzG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,qBAAa,cAAc,CAAC,CAAC,CAAE,YAAW,eAAe,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"computed-signal.d.ts","sourceRoot":"","sources":["../../src/core/computed-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,WAAW,EAAC,MAAM,mBAAmB,CAAC;AAE9C,OAAO,KAAK,EAAC,oBAAoB,EAAE,eAAe,EAAE,eAAe,EAAE,gBAAgB,EAAC,MAAM,YAAY,CAAC;AAEzG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,qBAAa,cAAc,CAAC,CAAC,CAAE,YAAW,eAAe,CAAC,CAAC,CAAC;IAmC9C,SAAS,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC,CAAC;IAlCtD;;OAEG;IACH,SAAgB,IAAI,SAAqB;IAEzC;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,OAAO,wCAAgD;IAE1E;;;;OAIG;IACH,SAAS,CAAC,QAAQ,CAAC,eAAe,iBAG/B;IAEH;;;OAGG;IAEH,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAAyB;IAEnE;;;OAGG;IACH,OAAO,CAAC,iBAAiB,CAAS;gBAEZ,OAAO,EAAE,oBAAoB,CAAC,CAAC,CAAC;IAWtD;;;;;;OAMG;IACI,GAAG,IAAI,CAAC;IAIf;;;;OAIG;IACH,IAAW,WAAW,IAAI,OAAO,CAEhC;IAED;;;;;;;OAOG;IACI,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,eAAe;IAI3F;;;;OAIG;IACI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC;IAI9B;;;;;;;;OAQG;IACI,OAAO,IAAI,IAAI;IAqBtB;;;;;;;OAOG;cACa,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CAwC9C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effect-signal.d.ts","sourceRoot":"","sources":["../../src/core/effect-signal.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,kBAAkB,EAAE,aAAa,EAAkB,MAAM,YAAY,CAAC;AAEnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,qBAAa,YAAa,YAAW,aAAa;
|
|
1
|
+
{"version":3,"file":"effect-signal.d.ts","sourceRoot":"","sources":["../../src/core/effect-signal.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,kBAAkB,EAAE,aAAa,EAAkB,MAAM,YAAY,CAAC;AAEnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,qBAAa,YAAa,YAAW,aAAa;IAwCpC,SAAS,CAAC,OAAO,EAAE,kBAAkB;IAvCjD;;OAEG;IACH,SAAgB,IAAI,SAAmF;IAEvG;;;OAGG;IACH,SAAS,CAAC,QAAQ,CAAC,OAAO,wCAA8C;IAExE;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAAyB;IAEnE;;;OAGG;IACH,OAAO,CAAC,WAAW,CAAS;IAE5B;;;OAGG;IACH,OAAO,CAAC,aAAa,CAAS;IAE9B;;;;;OAKG;IACH,IAAW,WAAW,IAAI,OAAO,CAEhC;gBAEqB,OAAO,EAAE,kBAAkB;IAmBjD;;;;;;;OAOG;cACa,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC;IAmCnD;;;;;;OAMG;IACI,OAAO,IAAI,IAAI;CAmBvB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-signal.d.ts","sourceRoot":"","sources":["../../src/core/event-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,YAAY,CAAC;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,WAAW,CAAC,CAAC,GAAG,IAAI,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAC;IACtD;;;OAGG;IACH,SAAS,CAAC,OAAO,wCAA6C;
|
|
1
|
+
{"version":3,"file":"event-signal.d.ts","sourceRoot":"","sources":["../../src/core/event-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,YAAY,CAAC;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,WAAW,CAAC,CAAC,GAAG,IAAI,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAC;IACtD;;;OAGG;IACH,SAAS,CAAC,OAAO,wCAA6C;gBAElD,MAAM,EAAE,YAAY;IAKhC;;;;;;OAMG;IACI,QAAQ,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI;CAMlC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signal-base.d.ts","sourceRoot":"","sources":["../../src/core/signal-base.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,gBAAgB,EAAE,YAAY,EAAC,MAAM,YAAY,CAAC;AAC7G,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,gBA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-
{"version":3,"file":"state-signal.d.ts","sourceRoot":"","sources":["../../src/core/state-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAC,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAC,MAAM,YAAY,CAAC;AAExH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,WAAW,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAE,YAAW,eAAe,CAAC,CAAC,CAAC;IAC7E;;;OAGG;IACH,OAAO,CAAC,OAAO,CAAI;IAEnB;;;OAGG;IACH,SAAS,CAAC,OAAO,wCAA6C;
|
|
1
|
+
{"version":3,"file":"state-signal.d.ts","sourceRoot":"","sources":["../../src/core/state-signal.ts"],"names":[],"mappings":"AAGA,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAC,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAC,MAAM,YAAY,CAAC;AAExH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,WAAW,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAE,YAAW,eAAe,CAAC,CAAC,CAAC;IAC7E;;;OAGG;IACH,OAAO,CAAC,OAAO,CAAI;IAEnB;;;OAGG;IACH,SAAS,CAAC,OAAO,wCAA6C;gBAElD,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;IAMxC;;;;;;;OAOG;IACI,GAAG,IAAI,CAAC;IAKf;;;;;;;;;;;;;;OAcG;IACI,GAAG,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI;IAe7B;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,OAAO,EAAE,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI;IAOrD;;;;;;;;;OASG;IACa,SAAS,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAAE,OAAO,GAAE,gBAAqB,GAAG,eAAe;IA2BzG;;;OAGG;IACa,OAAO,IAAI,IAAI;IAKxB,UAAU,IAAI,eAAe,CAAC,CAAC,CAAC;CAGxC"}
|
package/dist/main.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
/** 📦 @alwatr/signal v6.0.2 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/signal v6.0.2");
|
|
2
3
|
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var main_exports={};__export(main_exports,{ComputedSignal:()=>ComputedSignal,EffectSignal:()=>EffectSignal,EventSignal:()=>EventSignal,SignalBase:()=>SignalBase,StateSignal:()=>StateSignal,createComputedSignal:()=>createComputedSignal,createDebouncedSignal:()=>createDebouncedSignal,createEffect:()=>createEffect,createEventSignal:()=>createEventSignal,createStateSignal:()=>createStateSignal});module.exports=__toCommonJS(main_exports);var SignalBase=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.observers_=[];this.isDestroyed__=false}get isDestroyed(){return this.isDestroyed__}removeObserver_(observer){this.logger_.logMethod?.("removeObserver_");if(this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}const index=this.observers_.indexOf(observer);if(index!==-1){this.observers_.splice(index,1)}}subscribe(callback,options){this.logger_.logMethodArgs?.("subscribe.base",options);this.checkDestroyed_();const observer={callback,options};if(options?.priority){this.observers_.unshift(observer)}else{this.observers_.push(observer)}return{unsubscribe:()=>this.removeObserver_(observer)}}notify_(value){this.logger_.logMethodArgs?.("notify_",value);if(this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}const currentObservers=[...this.observers_];for(const observer of currentObservers){if(observer.options?.once){this.removeObserver_(observer)}try{const result=observer.callback(value);if(result instanceof Promise){result.catch(err=>this.logger_.error("notify_","async_callback_failed",err,{observer}))}}catch(err){this.logger_.error("notify_","sync_callback_failed",err)}}}untilNext(){this.logger_.logMethod?.("untilNext");this.checkDestroyed_();return new Promise(resolve=>{this.subscribe(resolve,{once:true,priority:true,receivePrevious:false})})}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=true;this.observers_.length=0;this.config_.onDestroy?.();this.config_=null}checkDestroyed_(){if(this.isDestroyed__){this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal");throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}};var import_delay=require("@alwatr/delay");var import_logger=require("@alwatr/logger");var EventSignal=class extends SignalBase{constructor(config){super(config);this.logger_=(0,import_logger.createLogger)(`event-signal:${this.name}`);this.logger_.logMethod?.("constructor")}dispatch(payload){this.logger_.logMethodArgs?.("dispatch",{payload});this.checkDestroyed_();import_delay.delay.nextMicrotask().then(()=>this.notify_(payload))}};var import_delay2=require("@alwatr/delay");var import_logger2=require("@alwatr/logger");var StateSignal=class extends SignalBase{constructor(config){super(config);this.logger_=(0,import_logger2.createLogger)(`state-signal:${this.name}`);this.value__=config.initialValue;this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){this.checkDestroyed_();return this.value__}set(newValue){this.logger_.logMethodArgs?.("set",{newValue});this.checkDestroyed_();if(Object.is(this.value__,newValue)&&(typeof newValue!=="object"||newValue===null)){return}this.value__=newValue;import_delay2.delay.nextMicrotask().then(()=>this.notify_(newValue))}update(updater){this.checkDestroyed_();const newValue=updater(this.value__);this.logger_.logMethodFull?.("update",this.value__,newValue);this.set(newValue)}subscribe(callback,options={}){this.logger_.logMethodArgs?.("subscribe",options);this.checkDestroyed_();if(options.receivePrevious!==false){import_delay2.delay.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback");callback(this.value__)}).catch(err=>this.logger_.error("subscribe","immediate_callback_failed",err));if(options.once){return{unsubscribe:()=>{}}}}return super.subscribe(callback,options)}destroy(){this.value__=null;super.destroy()}asReadonly(){return this}};var import_delay3=require("@alwatr/delay");var import_logger3=require("@alwatr/logger");var ComputedSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.logger_=(0,import_logger3.createLogger)(`computed-signal:${this.name}`);this.internalSignal_=new StateSignal({name:`compute-${this.name}_`,initialValue:this.config_.get()});this.dependencySubscriptions__=[];this.isRecalculating__=false;this.logger_.logMethod?.("constructor");this.recalculate_=this.recalculate_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_,{receivePrevious:false}))}}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(callback,options){return this.internalSignal_.subscribe(callback,options)}untilNext(){return this.internalSignal_.untilNext()}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.internalSignal_.destroy();this.config_.onDestroy?.();this.config_=null}async recalculate_(){this.logger_.logMethod?.("recalculate_");if(this.internalSignal_.isDestroyed){this.logger_.incident?.("recalculate_","recalculate_on_destroyed_signal");return}if(this.isRecalculating__){this.logger_.logStep?.("recalculate_","skipping_recalculation_already_scheduled");return}this.isRecalculating__=true;try{await import_delay3.delay.nextMacrotask();if(this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay");this.isRecalculating__=false;return}this.logger_.logStep?.("recalculate_","recalculating_value");this.internalSignal_.set(this.config_.get())}catch(err){this.logger_.error("recalculate_","recalculation_failed",err)}this.isRecalculating__=false}};var import_delay4=require("@alwatr/delay");var import_logger4=require("@alwatr/logger");var EffectSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name??`[${this.config_.deps.map(dep=>dep.name).join(", ")}]`;this.logger_=(0,import_logger4.createLogger)(`effect-signal:${this.name}`);this.dependencySubscriptions__=[];this.isRunning__=false;this.isDestroyed__=false;this.logger_.logMethod?.("constructor");this.scheduleExecution_=this.scheduleExecution_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_,{receivePrevious:false}))}if(config_.runImmediately===true){this.logger_.logStep?.("constructor","scheduling_initial_execution");void this.scheduleExecution_()}}get isDestroyed(){return this.isDestroyed__}async scheduleExecution_(){this.logger_.logMethod?.("scheduleExecution_");if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","schedule_execution_on_destroyed_signal");return}if(this.isRunning__){this.logger_.logStep?.("scheduleExecution_","skipped_because_already_running");return}this.isRunning__=true;try{await import_delay4.delay.nextMacrotask();if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay");this.isRunning__=false;return}this.logger_.logStep?.("scheduleExecution_","executing_effect");await this.config_.run()}catch(err){this.logger_.error("scheduleExecution_","effect_failed",err)}this.isRunning__=false}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=true;for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.config_.onDestroy?.();this.config_=null}};function createEventSignal(config){return new EventSignal(config)}function createStateSignal(config){return new StateSignal(config)}function createComputedSignal(config){return new ComputedSignal(config)}function createEffect(config){return new EffectSignal(config)}var import_debounce=require("@alwatr/debounce");function createDebouncedSignal(sourceSignal,config){const name=config.name??`${sourceSignal.name}-debounced`;const internalSignal=new StateSignal({name:`${name}-internal`,initialValue:sourceSignal.get()});const debouncer=(0,import_debounce.createDebouncer)({...config,func:value=>{internalSignal.set(value)}});const subscription=sourceSignal.subscribe(value=>debouncer.trigger(value),{receivePrevious:false});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{if(internalSignal.isDestroyed)return;subscription.unsubscribe();debouncer.cancel();internalSignal.destroy();config.onDestroy?.();config=null}})}0&&(module.exports={ComputedSignal,EffectSignal,EventSignal,SignalBase,StateSignal,createComputedSignal,createDebouncedSignal,createEffect,createEventSignal,createStateSignal});
|
|
3
4
|
//# sourceMappingURL=main.cjs.map
|
package/dist/main.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/main.ts", "../src/core/signal-base.ts", "../src/core/event-signal.ts", "../src/core/state-signal.ts", "../src/core/computed-signal.ts", "../src/core/effect-signal.ts", "../src/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/operators/debounce.ts"],
|
|
4
|
-
"sourcesContent": ["export * from './core/signal-base.js';\nexport * from './core/event-signal.js';\nexport * from './core/state-signal.js';\nexport * from './core/computed-signal.js';\nexport * from './core/effect-signal.js';\n\nexport * from './creators/event.js';\nexport * from './creators/state.js';\nexport * from './creators/computed.js';\nexport * from './creators/effect.js';\n\nexport * from './operators/debounce.js';\n\nexport type * from './type.js';\n", "import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\n\n/**\n * An abstract base class for signal implementations.\n * It provides the core functionality for managing subscriptions (observers).\n *\n * @template T The type of data that the signal holds or dispatches.\n */\nexport abstract class SignalBase<T> {\n /**\n * The unique identifier for this signal instance.\n * Useful for debugging and logging.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected abstract logger_: AlwatrLogger;\n\n /**\n * The list of observers (listeners) subscribed to this signal.\n * @protected\n */\n protected readonly observers_: Observer_<T>[] = [];\n\n /**\n * A flag indicating whether the signal has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n public constructor(protected config_: SignalConfig) {}\n\n /**\n * Removes a specific observer from the observers list.\n *\n * @param observer The observer instance to remove.\n * @protected\n */\n protected removeObserver_(observer: Observer_<T>): void {\n this.logger_.logMethod?.('removeObserver_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('removeObserver_', 'remove_observer_on_destroyed_signal');\n return;\n }\n\n const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\n }\n\n /**\n * Subscribes a listener function to this signal.\n *\n * The listener will be called whenever the signal is notified (e.g., when `dispatch` or `set` is called).\n *\n * @param callback The function to be called when the signal is dispatched.\n * @param options Subscription options to customize the behavior (e.g., `once`, `priority`).\n * @returns A `SubscribeResult` object with an `unsubscribe` method to remove the listener.\n */\n public subscribe(callback: ListenerCallback<T>, options?: SubscribeOptions): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe.base', options);\n this.checkDestroyed_();\n\n const observer: Observer_<T> = {callback, options};\n\n if (options?.priority) {\n // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(observer);\n }\n\n // The returned unsubscribe function is a closure that calls the internal removal method.\n return {\n unsubscribe: (): void => this.removeObserver_(observer),\n };\n }\n\n /**\n * Notifies all registered observers about a new value.\n *\n * This method iterates through a snapshot of the current observers to prevent issues\n * with subscriptions changing during notification (e.g., an observer unsubscribing itself).\n *\n * @param value The new value to notify observers about.\n * @protected\n */\n protected notify_(value: T): void {\n this.logger_.logMethodArgs?.('notify_', value);\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('notify_', 'notify_on_destroyed_signal');\n return;\n }\n\n // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\n\n try {\n const result = observer.callback(value);\n if (result instanceof Promise) {\n result.catch((err) => this.logger_.error('notify_', 'async_callback_failed', err, {observer}));\n }\n }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\n }\n }\n\n /**\n * Returns a Promise that resolves with the next value dispatched by the signal.\n * This provides an elegant way to wait for a single, future event using `async/await`.\n *\n * @returns A Promise that resolves with the next dispatched value.\n *\n * @example\n * async function onButtonClick() {\n * console.log('Waiting for the next signal...');\n * const nextValue = await mySignal.untilNext();\n * console.log('Signal received:', nextValue);\n * }\n */\n public untilNext(): Promise<T> {\n this.logger_.logMethod?.('untilNext');\n this.checkDestroyed_();\n return new Promise((resolve) => {\n this.subscribe(resolve, {\n once: true,\n priority: true, // Resolve the promise before other listeners are called.\n receivePrevious: false, // We only want the *next* value, not the current one.\n });\n });\n }\n\n /**\n * Destroys the signal, clearing all its listeners and making it inactive.\n *\n * After destruction, any interaction with the signal (like `subscribe` or `untilNext`)\n * will throw an error. This is crucial for preventing memory leaks by allowing\n * garbage collection of the signal and its observers.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy_', 'double_destroy_attempt');\n return;\n }\n this.isDestroyed__ = true;\n this.observers_.length = 0; // Clear all observers.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as SignalConfig; // Help GC by breaking references.\n }\n\n /**\n * Throws an error if the signal has been destroyed.\n * This is a safeguard to prevent interaction with a defunct signal.\n * @protected\n */\n protected checkDestroyed_(): void {\n if (this.isDestroyed__) {\n this.logger_.accident('checkDestroyed_', 'attempt_to_use_destroyed_signal');\n throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`);\n }\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * A stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events. Defaults to `void` for events without a payload.\n *\n * @example\n * // Create a signal for user click events.\n * const onUserClick = new EventSignal<{ x: number, y: number }>({ name: 'on-user-click' });\n *\n * // Subscribe to the event.\n * onUserClick.subscribe(clickPosition => {\n * console.log(`User clicked at: ${clickPosition.x}, ${clickPosition.y}`);\n * });\n *\n * // Dispatch an event.\n * onUserClick.dispatch({ x: 100, y: 250 }); // Notifies the listener.\n *\n * // --- Example with no payload ---\n * const onAppReady = new EventSignal({ name: 'on-app-ready' });\n * onAppReady.subscribe(() => console.log('Application is ready!'));\n * onAppReady.dispatch(); // Notifies the listener.\n */\nexport class EventSignal<T = void> extends SignalBase<T> {\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`event-signal:${this.name}`);\n\n public constructor(config: SignalConfig) {\n super(config);\n this.logger_.logMethod?.('constructor');\n }\n\n /**\n * Dispatches an event with an optional payload to all active listeners.\n * The notification is scheduled as a microtask to prevent blocking and ensure\n * a consistent, non-blocking flow.\n *\n * @param payload The data to send with the event.\n */\n public dispatch(payload: T): void {\n this.logger_.logMethodArgs?.('dispatch', {payload});\n this.checkDestroyed_();\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(payload));\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {StateSignalConfig, ListenerCallback, SubscribeOptions, SubscribeResult, IReadonlySignal} from '../type.js';\n\n/**\n * A stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n * @implements {IReadonlySignal<T>}\n *\n * @example\n * // Create a new state signal with an initial value.\n * const counter = new StateSignal<number>({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * // Get the current value.\n * console.log(counter.get()); // Outputs: 0\n *\n * // Subscribe to changes.\n * const subscription = counter.subscribe(newValue => {\n * console.log(`Counter changed to: ${newValue}`);\n * });\n *\n * // Set a new value, which triggers the notification.\n * counter.set(1); // Outputs: \"Counter changed to: 1\"\n *\n * // Update value based on the previous value.\n * counter.update(current => current + 1); // Outputs: \"Counter changed to: 2\"\n *\n * // Unsubscribe when no longer needed.\n * subscription.unsubscribe();\n */\nexport class StateSignal<T> extends SignalBase<T> implements IReadonlySignal<T> {\n /**\n * The current value of the signal.\n * @private\n */\n private value__: T;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`state-signal:${this.name}`);\n\n public constructor(config: StateSignalConfig<T>) {\n super(config);\n this.value__ = config.initialValue;\n this.logger_.logMethodArgs?.('constructor', {initialValue: this.value__});\n }\n\n /**\n * Retrieves the current value of the signal.\n *\n * @returns The current value.\n *\n * @example\n * console.log(mySignal.get());\n */\n public get(): T {\n this.checkDestroyed_();\n return this.value__;\n }\n\n /**\n * Updates the signal's value and notifies all active listeners.\n *\n * The notification is scheduled as a microtask, which means the update is deferred\n * slightly to batch multiple synchronous changes.\n *\n * @param newValue The new value to set.\n *\n * @example\n * // For primitive types\n * mySignal.set(42);\n *\n * // For object types, it's best practice to set an immutable new object.\n * mySignal.set({ ...mySignal.get(), property: 'new-value' });\n */\n public set(newValue: T): void {\n this.logger_.logMethodArgs?.('set', {newValue});\n this.checkDestroyed_();\n\n // For primitives (including null), do not notify if the value is the same.\n if (Object.is(this.value__, newValue) && (typeof newValue !== 'object' || newValue === null)) {\n return;\n }\n\n this.value__ = newValue;\n\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(newValue));\n }\n\n /**\n * Updates the signal's value based on its previous value.\n *\n * This method is particularly useful for state transitions that depend on the current value,\n * especially for objects or arrays, as it promotes an immutable update pattern.\n *\n * @param updater A function that receives the current value and returns the new value.\n *\n * @example\n * // For a counter\n * counterSignal.update(current => current + 1);\n *\n * // For an object state\n * userSignal.update(currentUser => ({ ...currentUser, loggedIn: true }));\n */\n public update(updater: (previousValue: T) => T): void {\n this.checkDestroyed_();\n const newValue = updater(this.value__);\n this.logger_.logMethodFull?.('update', this.value__, newValue);\n this.set(newValue);\n }\n\n /**\n * Subscribes a listener to this signal.\n *\n * By default, the listener is immediately called with the signal's current value (`receivePrevious: true`).\n * This behavior can be customized via the `options` parameter.\n *\n * @param callback The function to be called when the signal's value changes.\n * @param options Subscription options, including `receivePrevious` and `once`.\n * @returns An object with an `unsubscribe` method to remove the listener.\n */\n public override subscribe(callback: ListenerCallback<T>, options: SubscribeOptions = {}): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe', options);\n this.checkDestroyed_();\n\n // By default, new subscribers to a StateSignal should receive the current value.\n if (options.receivePrevious !== false) {\n // Immediately (but asynchronously) call the listener with the current value.\n // This is done in a microtask to ensure it happens after the subscription is fully registered.\n delay\n .nextMicrotask()\n .then(() => {\n this.logger_.logStep?.('subscribe', 'immediate_callback');\n callback(this.value__);\n })\n .catch((err) => this.logger_.error('subscribe', 'immediate_callback_failed', err));\n\n // If it's a 'once' subscription that receives the previous value, it's now fulfilled.\n // We don't need to add it to the observers list for future updates.\n if (options.once) {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return {unsubscribe: () => {}};\n }\n }\n\n return super.subscribe(callback, options);\n }\n\n /**\n * Destroys the signal, clearing its value and all listeners.\n * This is crucial for memory management to prevent leaks.\n */\n public override destroy(): void {\n this.value__ = null as T; // Clear the value to allow for garbage collection.\n super.destroy();\n }\n\n public asReadonly(): IReadonlySignal<T> {\n return this;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {StateSignal} from './state-signal.js';\n\nimport type {ComputedSignalConfig, IReadonlySignal, SubscribeResult, SubscribeOptions} from '../type.js';\n\n/**\n * A read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @example\n * // --- Create dependency signals ---\n * const firstName = new StateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = new StateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * // --- Create a computed signal ---\n * const fullName = new ComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // Outputs: \"John Doe\"\n *\n * // --- Subscribe to the computed value ---\n * fullName.subscribe(newFullName => {\n * console.log(`Name changed to: ${newFullName}`);\n * });\n *\n * // --- Update a dependency ---\n * lastName.set('Smith'); // Recalculates and logs: \"Name changed to: John Smith\"\n * console.log(fullName.get()); // Outputs: \"John Smith\"\n *\n * // --- IMPORTANT: Clean up when done ---\n * fullName.destroy();\n */\nexport class ComputedSignal<T> implements IReadonlySignal<T> {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\n\n /**\n * The internal `StateSignal` that holds the computed value.\n * This is how the computed signal provides `.get()` and `.subscribe()` methods.\n * @protected\n */\n protected readonly internalSignal_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent recalculations.\n * @private\n */\n private isRecalculating__ = false;\n\n public constructor(protected config_: ComputedSignalConfig<T>) {\n this.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\n\n // Subscribe to all dependencies to trigger recalculation on change.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_, {receivePrevious: false}));\n }\n }\n\n /**\n * The current value of the computed signal.\n * Accessing this property returns the memoized value and does not trigger a recalculation.\n *\n * @returns The current computed value.\n * @throws {Error} If accessed after the signal has been destroyed.\n */\n public get(): T {\n return this.internalSignal_.get();\n }\n\n /**\n * Indicates whether the computed signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.internalSignal_.isDestroyed;\n }\n\n /**\n * Subscribes a listener to this signal.\n * The listener will be called whenever the computed value changes.\n *\n * @param callback The function to be called with the new value.\n * @param options Subscription options.\n * @returns A `SubscribeResult` object with an `unsubscribe` method.\n */\n public subscribe(callback: (value: T) => void, options?: SubscribeOptions): SubscribeResult {\n return this.internalSignal_.subscribe(callback, options);\n }\n\n /**\n * Returns a Promise that resolves with the next computed value.\n *\n * @returns A Promise that resolves with the next value.\n */\n public untilNext(): Promise<T> {\n return this.internalSignal_.untilNext();\n }\n\n /**\n * Permanently disposes of the computed signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping future recalculations and allowing the signal to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks.\n *\n * After `destroy()` is called, any attempt to access `.get()` or `.subscribe()` will throw an error.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n /**\n * If already destroyed, log an incident and return early.\n */\n if (this.isDestroyed) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.internalSignal_.destroy(); // Destroy the internal signal.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as ComputedSignalConfig<T>; // Release config closure.\n }\n\n /**\n * Schedules a recalculation of the signal's value.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `get` function runs only once per event loop tick, even if multiple dependencies\n * change in the same synchronous block of code.\n * @protected\n */\n protected async recalculate_(): Promise<void> {\n this.logger_.logMethod?.('recalculate_');\n\n if (this.internalSignal_.isDestroyed) {\n // This check is important in case a dependency fires after this signal is destroyed.\n this.logger_.incident?.('recalculate_', 'recalculate_on_destroyed_signal');\n return;\n }\n\n if (this.isRecalculating__) {\n // If a recalculation is already scheduled, do nothing.\n this.logger_.logStep?.('recalculate_', 'skipping_recalculation_already_scheduled');\n return;\n }\n\n this.isRecalculating__ = true;\n\n try {\n // Wait for the next macrotask to start the recalculation.\n // This batches all synchronous dependency updates in the current event loop.\n await delay.nextMacrotask();\n\n if (this.isDestroyed) {\n this.logger_.incident?.('recalculate_', 'destroyed_during_delay');\n this.isRecalculating__ = false;\n return;\n }\n\n this.logger_.logStep?.('recalculate_', 'recalculating_value');\n\n // Set the new value on the internal signal, which will notify our subscribers.\n this.internalSignal_.set(this.config_.get());\n }\n catch (err) {\n this.logger_.error('recalculate_', 'recalculation_failed', err);\n }\n\n // Allow the next recalculation to be scheduled.\n this.isRecalculating__ = false;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n public constructor(protected config_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates a stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates a stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates a read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["export * from './core/signal-base.js';\nexport * from './core/event-signal.js';\nexport * from './core/state-signal.js';\nexport * from './core/computed-signal.js';\nexport * from './core/effect-signal.js';\n\nexport * from './creators/event.js';\nexport * from './creators/state.js';\nexport * from './creators/computed.js';\nexport * from './creators/effect.js';\n\nexport * from './operators/debounce.js';\n\nexport type * from './type.js';\n", "import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\n\n/**\n * An abstract base class for signal implementations.\n * It provides the core functionality for managing subscriptions (observers).\n *\n * @template T The type of data that the signal holds or dispatches.\n */\nexport abstract class SignalBase<T> {\n /**\n * The unique identifier for this signal instance.\n * Useful for debugging and logging.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected abstract logger_: AlwatrLogger;\n\n /**\n * The list of observers (listeners) subscribed to this signal.\n * @protected\n */\n protected readonly observers_: Observer_<T>[] = [];\n\n /**\n * A flag indicating whether the signal has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n constructor(protected config_: SignalConfig) {}\n\n /**\n * Removes a specific observer from the observers list.\n *\n * @param observer The observer instance to remove.\n * @protected\n */\n protected removeObserver_(observer: Observer_<T>): void {\n this.logger_.logMethod?.('removeObserver_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('removeObserver_', 'remove_observer_on_destroyed_signal');\n return;\n }\n\n const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\n }\n\n /**\n * Subscribes a listener function to this signal.\n *\n * The listener will be called whenever the signal is notified (e.g., when `dispatch` or `set` is called).\n *\n * @param callback The function to be called when the signal is dispatched.\n * @param options Subscription options to customize the behavior (e.g., `once`, `priority`).\n * @returns A `SubscribeResult` object with an `unsubscribe` method to remove the listener.\n */\n public subscribe(callback: ListenerCallback<T>, options?: SubscribeOptions): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe.base', options);\n this.checkDestroyed_();\n\n const observer: Observer_<T> = {callback, options};\n\n if (options?.priority) {\n // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(observer);\n }\n\n // The returned unsubscribe function is a closure that calls the internal removal method.\n return {\n unsubscribe: (): void => this.removeObserver_(observer),\n };\n }\n\n /**\n * Notifies all registered observers about a new value.\n *\n * This method iterates through a snapshot of the current observers to prevent issues\n * with subscriptions changing during notification (e.g., an observer unsubscribing itself).\n *\n * @param value The new value to notify observers about.\n * @protected\n */\n protected notify_(value: T): void {\n this.logger_.logMethodArgs?.('notify_', value);\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('notify_', 'notify_on_destroyed_signal');\n return;\n }\n\n // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\n\n try {\n const result = observer.callback(value);\n if (result instanceof Promise) {\n result.catch((err) => this.logger_.error('notify_', 'async_callback_failed', err, {observer}));\n }\n }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\n }\n }\n\n /**\n * Returns a Promise that resolves with the next value dispatched by the signal.\n * This provides an elegant way to wait for a single, future event using `async/await`.\n *\n * @returns A Promise that resolves with the next dispatched value.\n *\n * @example\n * async function onButtonClick() {\n * console.log('Waiting for the next signal...');\n * const nextValue = await mySignal.untilNext();\n * console.log('Signal received:', nextValue);\n * }\n */\n public untilNext(): Promise<T> {\n this.logger_.logMethod?.('untilNext');\n this.checkDestroyed_();\n return new Promise((resolve) => {\n this.subscribe(resolve, {\n once: true,\n priority: true, // Resolve the promise before other listeners are called.\n receivePrevious: false, // We only want the *next* value, not the current one.\n });\n });\n }\n\n /**\n * Destroys the signal, clearing all its listeners and making it inactive.\n *\n * After destruction, any interaction with the signal (like `subscribe` or `untilNext`)\n * will throw an error. This is crucial for preventing memory leaks by allowing\n * garbage collection of the signal and its observers.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy_', 'double_destroy_attempt');\n return;\n }\n this.isDestroyed__ = true;\n this.observers_.length = 0; // Clear all observers.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as SignalConfig; // Help GC by breaking references.\n }\n\n /**\n * Throws an error if the signal has been destroyed.\n * This is a safeguard to prevent interaction with a defunct signal.\n * @protected\n */\n protected checkDestroyed_(): void {\n if (this.isDestroyed__) {\n this.logger_.accident('checkDestroyed_', 'attempt_to_use_destroyed_signal');\n throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`);\n }\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * A stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events. Defaults to `void` for events without a payload.\n *\n * @example\n * // Create a signal for user click events.\n * const onUserClick = new EventSignal<{ x: number, y: number }>({ name: 'on-user-click' });\n *\n * // Subscribe to the event.\n * onUserClick.subscribe(clickPosition => {\n * console.log(`User clicked at: ${clickPosition.x}, ${clickPosition.y}`);\n * });\n *\n * // Dispatch an event.\n * onUserClick.dispatch({ x: 100, y: 250 }); // Notifies the listener.\n *\n * // --- Example with no payload ---\n * const onAppReady = new EventSignal({ name: 'on-app-ready' });\n * onAppReady.subscribe(() => console.log('Application is ready!'));\n * onAppReady.dispatch(); // Notifies the listener.\n */\nexport class EventSignal<T = void> extends SignalBase<T> {\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`event-signal:${this.name}`);\n\n constructor(config: SignalConfig) {\n super(config);\n this.logger_.logMethod?.('constructor');\n }\n\n /**\n * Dispatches an event with an optional payload to all active listeners.\n * The notification is scheduled as a microtask to prevent blocking and ensure\n * a consistent, non-blocking flow.\n *\n * @param payload The data to send with the event.\n */\n public dispatch(payload: T): void {\n this.logger_.logMethodArgs?.('dispatch', {payload});\n this.checkDestroyed_();\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(payload));\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {StateSignalConfig, ListenerCallback, SubscribeOptions, SubscribeResult, IReadonlySignal} from '../type.js';\n\n/**\n * A stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n * @implements {IReadonlySignal<T>}\n *\n * @example\n * // Create a new state signal with an initial value.\n * const counter = new StateSignal<number>({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * // Get the current value.\n * console.log(counter.get()); // Outputs: 0\n *\n * // Subscribe to changes.\n * const subscription = counter.subscribe(newValue => {\n * console.log(`Counter changed to: ${newValue}`);\n * });\n *\n * // Set a new value, which triggers the notification.\n * counter.set(1); // Outputs: \"Counter changed to: 1\"\n *\n * // Update value based on the previous value.\n * counter.update(current => current + 1); // Outputs: \"Counter changed to: 2\"\n *\n * // Unsubscribe when no longer needed.\n * subscription.unsubscribe();\n */\nexport class StateSignal<T> extends SignalBase<T> implements IReadonlySignal<T> {\n /**\n * The current value of the signal.\n * @private\n */\n private value__: T;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`state-signal:${this.name}`);\n\n constructor(config: StateSignalConfig<T>) {\n super(config);\n this.value__ = config.initialValue;\n this.logger_.logMethodArgs?.('constructor', {initialValue: this.value__});\n }\n\n /**\n * Retrieves the current value of the signal.\n *\n * @returns The current value.\n *\n * @example\n * console.log(mySignal.get());\n */\n public get(): T {\n this.checkDestroyed_();\n return this.value__;\n }\n\n /**\n * Updates the signal's value and notifies all active listeners.\n *\n * The notification is scheduled as a microtask, which means the update is deferred\n * slightly to batch multiple synchronous changes.\n *\n * @param newValue The new value to set.\n *\n * @example\n * // For primitive types\n * mySignal.set(42);\n *\n * // For object types, it's best practice to set an immutable new object.\n * mySignal.set({ ...mySignal.get(), property: 'new-value' });\n */\n public set(newValue: T): void {\n this.logger_.logMethodArgs?.('set', {newValue});\n this.checkDestroyed_();\n\n // For primitives (including null), do not notify if the value is the same.\n if (Object.is(this.value__, newValue) && (typeof newValue !== 'object' || newValue === null)) {\n return;\n }\n\n this.value__ = newValue;\n\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(newValue));\n }\n\n /**\n * Updates the signal's value based on its previous value.\n *\n * This method is particularly useful for state transitions that depend on the current value,\n * especially for objects or arrays, as it promotes an immutable update pattern.\n *\n * @param updater A function that receives the current value and returns the new value.\n *\n * @example\n * // For a counter\n * counterSignal.update(current => current + 1);\n *\n * // For an object state\n * userSignal.update(currentUser => ({ ...currentUser, loggedIn: true }));\n */\n public update(updater: (previousValue: T) => T): void {\n this.checkDestroyed_();\n const newValue = updater(this.value__);\n this.logger_.logMethodFull?.('update', this.value__, newValue);\n this.set(newValue);\n }\n\n /**\n * Subscribes a listener to this signal.\n *\n * By default, the listener is immediately called with the signal's current value (`receivePrevious: true`).\n * This behavior can be customized via the `options` parameter.\n *\n * @param callback The function to be called when the signal's value changes.\n * @param options Subscription options, including `receivePrevious` and `once`.\n * @returns An object with an `unsubscribe` method to remove the listener.\n */\n public override subscribe(callback: ListenerCallback<T>, options: SubscribeOptions = {}): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe', options);\n this.checkDestroyed_();\n\n // By default, new subscribers to a StateSignal should receive the current value.\n if (options.receivePrevious !== false) {\n // Immediately (but asynchronously) call the listener with the current value.\n // This is done in a microtask to ensure it happens after the subscription is fully registered.\n delay\n .nextMicrotask()\n .then(() => {\n this.logger_.logStep?.('subscribe', 'immediate_callback');\n callback(this.value__);\n })\n .catch((err) => this.logger_.error('subscribe', 'immediate_callback_failed', err));\n\n // If it's a 'once' subscription that receives the previous value, it's now fulfilled.\n // We don't need to add it to the observers list for future updates.\n if (options.once) {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return {unsubscribe: () => {}};\n }\n }\n\n return super.subscribe(callback, options);\n }\n\n /**\n * Destroys the signal, clearing its value and all listeners.\n * This is crucial for memory management to prevent leaks.\n */\n public override destroy(): void {\n this.value__ = null as T; // Clear the value to allow for garbage collection.\n super.destroy();\n }\n\n public asReadonly(): IReadonlySignal<T> {\n return this;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {StateSignal} from './state-signal.js';\n\nimport type {ComputedSignalConfig, IReadonlySignal, SubscribeResult, SubscribeOptions} from '../type.js';\n\n/**\n * A read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @example\n * // --- Create dependency signals ---\n * const firstName = new StateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = new StateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * // --- Create a computed signal ---\n * const fullName = new ComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // Outputs: \"John Doe\"\n *\n * // --- Subscribe to the computed value ---\n * fullName.subscribe(newFullName => {\n * console.log(`Name changed to: ${newFullName}`);\n * });\n *\n * // --- Update a dependency ---\n * lastName.set('Smith'); // Recalculates and logs: \"Name changed to: John Smith\"\n * console.log(fullName.get()); // Outputs: \"John Smith\"\n *\n * // --- IMPORTANT: Clean up when done ---\n * fullName.destroy();\n */\nexport class ComputedSignal<T> implements IReadonlySignal<T> {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\n\n /**\n * The internal `StateSignal` that holds the computed value.\n * This is how the computed signal provides `.get()` and `.subscribe()` methods.\n * @protected\n */\n protected readonly internalSignal_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent recalculations.\n * @private\n */\n private isRecalculating__ = false;\n\n constructor(protected config_: ComputedSignalConfig<T>) {\n this.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\n\n // Subscribe to all dependencies to trigger recalculation on change.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_, {receivePrevious: false}));\n }\n }\n\n /**\n * The current value of the computed signal.\n * Accessing this property returns the memoized value and does not trigger a recalculation.\n *\n * @returns The current computed value.\n * @throws {Error} If accessed after the signal has been destroyed.\n */\n public get(): T {\n return this.internalSignal_.get();\n }\n\n /**\n * Indicates whether the computed signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.internalSignal_.isDestroyed;\n }\n\n /**\n * Subscribes a listener to this signal.\n * The listener will be called whenever the computed value changes.\n *\n * @param callback The function to be called with the new value.\n * @param options Subscription options.\n * @returns A `SubscribeResult` object with an `unsubscribe` method.\n */\n public subscribe(callback: (value: T) => void, options?: SubscribeOptions): SubscribeResult {\n return this.internalSignal_.subscribe(callback, options);\n }\n\n /**\n * Returns a Promise that resolves with the next computed value.\n *\n * @returns A Promise that resolves with the next value.\n */\n public untilNext(): Promise<T> {\n return this.internalSignal_.untilNext();\n }\n\n /**\n * Permanently disposes of the computed signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping future recalculations and allowing the signal to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks.\n *\n * After `destroy()` is called, any attempt to access `.get()` or `.subscribe()` will throw an error.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n /**\n * If already destroyed, log an incident and return early.\n */\n if (this.isDestroyed) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.internalSignal_.destroy(); // Destroy the internal signal.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as ComputedSignalConfig<T>; // Release config closure.\n }\n\n /**\n * Schedules a recalculation of the signal's value.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `get` function runs only once per event loop tick, even if multiple dependencies\n * change in the same synchronous block of code.\n * @protected\n */\n protected async recalculate_(): Promise<void> {\n this.logger_.logMethod?.('recalculate_');\n\n if (this.internalSignal_.isDestroyed) {\n // This check is important in case a dependency fires after this signal is destroyed.\n this.logger_.incident?.('recalculate_', 'recalculate_on_destroyed_signal');\n return;\n }\n\n if (this.isRecalculating__) {\n // If a recalculation is already scheduled, do nothing.\n this.logger_.logStep?.('recalculate_', 'skipping_recalculation_already_scheduled');\n return;\n }\n\n this.isRecalculating__ = true;\n\n try {\n // Wait for the next macrotask to start the recalculation.\n // This batches all synchronous dependency updates in the current event loop.\n await delay.nextMacrotask();\n\n if (this.isDestroyed) {\n this.logger_.incident?.('recalculate_', 'destroyed_during_delay');\n this.isRecalculating__ = false;\n return;\n }\n\n this.logger_.logStep?.('recalculate_', 'recalculating_value');\n\n // Set the new value on the internal signal, which will notify our subscribers.\n this.internalSignal_.set(this.config_.get());\n }\n catch (err) {\n this.logger_.error('recalculate_', 'recalculation_failed', err);\n }\n\n // Allow the next recalculation to be scheduled.\n this.isRecalculating__ = false;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n constructor(protected config_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates a stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates a stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates a read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n"],
|
|
5
|
+
"mappings": ";;qqBAAA,qbCUO,IAAe,WAAf,KAA6B,CAmClC,YAAsB,QAAuB,CAAvB,qBA9BtB,KAAgB,KAAO,KAAK,QAAQ,KAYpC,KAAmB,WAA6B,CAAC,EAMjD,KAAQ,cAAgB,KAYsB,CAJ9C,IAAW,aAAuB,CAChC,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vB,OAAO,YAAY,EACnB,OAAS,IACX,CACF,CAAC,CACH",
|
|
6
6
|
"names": ["import_delay", "import_logger", "import_delay", "import_logger", "import_delay", "import_logger"]
|
|
7
7
|
}
|
package/dist/main.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
/** 📦 @alwatr/signal v6.0.2 */
|
|
2
|
+
__dev_mode__: console.debug("📦 @alwatr/signal v6.0.2");
|
|
2
3
|
var SignalBase=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.observers_=[];this.isDestroyed__=false}get isDestroyed(){return this.isDestroyed__}removeObserver_(observer){this.logger_.logMethod?.("removeObserver_");if(this.isDestroyed__){this.logger_.incident?.("removeObserver_","remove_observer_on_destroyed_signal");return}const index=this.observers_.indexOf(observer);if(index!==-1){this.observers_.splice(index,1)}}subscribe(callback,options){this.logger_.logMethodArgs?.("subscribe.base",options);this.checkDestroyed_();const observer={callback,options};if(options?.priority){this.observers_.unshift(observer)}else{this.observers_.push(observer)}return{unsubscribe:()=>this.removeObserver_(observer)}}notify_(value){this.logger_.logMethodArgs?.("notify_",value);if(this.isDestroyed__){this.logger_.incident?.("notify_","notify_on_destroyed_signal");return}const currentObservers=[...this.observers_];for(const observer of currentObservers){if(observer.options?.once){this.removeObserver_(observer)}try{const result=observer.callback(value);if(result instanceof Promise){result.catch(err=>this.logger_.error("notify_","async_callback_failed",err,{observer}))}}catch(err){this.logger_.error("notify_","sync_callback_failed",err)}}}untilNext(){this.logger_.logMethod?.("untilNext");this.checkDestroyed_();return new Promise(resolve=>{this.subscribe(resolve,{once:true,priority:true,receivePrevious:false})})}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy_","double_destroy_attempt");return}this.isDestroyed__=true;this.observers_.length=0;this.config_.onDestroy?.();this.config_=null}checkDestroyed_(){if(this.isDestroyed__){this.logger_.accident("checkDestroyed_","attempt_to_use_destroyed_signal");throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`)}}};import{delay}from"@alwatr/delay";import{createLogger}from"@alwatr/logger";var EventSignal=class extends SignalBase{constructor(config){super(config);this.logger_=createLogger(`event-signal:${this.name}`);this.logger_.logMethod?.("constructor")}dispatch(payload){this.logger_.logMethodArgs?.("dispatch",{payload});this.checkDestroyed_();delay.nextMicrotask().then(()=>this.notify_(payload))}};import{delay as delay2}from"@alwatr/delay";import{createLogger as createLogger2}from"@alwatr/logger";var StateSignal=class extends SignalBase{constructor(config){super(config);this.logger_=createLogger2(`state-signal:${this.name}`);this.value__=config.initialValue;this.logger_.logMethodArgs?.("constructor",{initialValue:this.value__})}get(){this.checkDestroyed_();return this.value__}set(newValue){this.logger_.logMethodArgs?.("set",{newValue});this.checkDestroyed_();if(Object.is(this.value__,newValue)&&(typeof newValue!=="object"||newValue===null)){return}this.value__=newValue;delay2.nextMicrotask().then(()=>this.notify_(newValue))}update(updater){this.checkDestroyed_();const newValue=updater(this.value__);this.logger_.logMethodFull?.("update",this.value__,newValue);this.set(newValue)}subscribe(callback,options={}){this.logger_.logMethodArgs?.("subscribe",options);this.checkDestroyed_();if(options.receivePrevious!==false){delay2.nextMicrotask().then(()=>{this.logger_.logStep?.("subscribe","immediate_callback");callback(this.value__)}).catch(err=>this.logger_.error("subscribe","immediate_callback_failed",err));if(options.once){return{unsubscribe:()=>{}}}}return super.subscribe(callback,options)}destroy(){this.value__=null;super.destroy()}asReadonly(){return this}};import{delay as delay3}from"@alwatr/delay";import{createLogger as createLogger3}from"@alwatr/logger";var ComputedSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name;this.logger_=createLogger3(`computed-signal:${this.name}`);this.internalSignal_=new StateSignal({name:`compute-${this.name}_`,initialValue:this.config_.get()});this.dependencySubscriptions__=[];this.isRecalculating__=false;this.logger_.logMethod?.("constructor");this.recalculate_=this.recalculate_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_,{receivePrevious:false}))}}get(){return this.internalSignal_.get()}get isDestroyed(){return this.internalSignal_.isDestroyed}subscribe(callback,options){return this.internalSignal_.subscribe(callback,options)}untilNext(){return this.internalSignal_.untilNext()}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed){this.logger_.incident?.("destroy","already_destroyed");return}for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.internalSignal_.destroy();this.config_.onDestroy?.();this.config_=null}async recalculate_(){this.logger_.logMethod?.("recalculate_");if(this.internalSignal_.isDestroyed){this.logger_.incident?.("recalculate_","recalculate_on_destroyed_signal");return}if(this.isRecalculating__){this.logger_.logStep?.("recalculate_","skipping_recalculation_already_scheduled");return}this.isRecalculating__=true;try{await delay3.nextMacrotask();if(this.isDestroyed){this.logger_.incident?.("recalculate_","destroyed_during_delay");this.isRecalculating__=false;return}this.logger_.logStep?.("recalculate_","recalculating_value");this.internalSignal_.set(this.config_.get())}catch(err){this.logger_.error("recalculate_","recalculation_failed",err)}this.isRecalculating__=false}};import{delay as delay4}from"@alwatr/delay";import{createLogger as createLogger4}from"@alwatr/logger";var EffectSignal=class{constructor(config_){this.config_=config_;this.name=this.config_.name??`[${this.config_.deps.map(dep=>dep.name).join(", ")}]`;this.logger_=createLogger4(`effect-signal:${this.name}`);this.dependencySubscriptions__=[];this.isRunning__=false;this.isDestroyed__=false;this.logger_.logMethod?.("constructor");this.scheduleExecution_=this.scheduleExecution_.bind(this);for(const signal of config_.deps){this.logger_.logStep?.("constructor","subscribing_to_dependency",{signal:signal.name});this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_,{receivePrevious:false}))}if(config_.runImmediately===true){this.logger_.logStep?.("constructor","scheduling_initial_execution");void this.scheduleExecution_()}}get isDestroyed(){return this.isDestroyed__}async scheduleExecution_(){this.logger_.logMethod?.("scheduleExecution_");if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","schedule_execution_on_destroyed_signal");return}if(this.isRunning__){this.logger_.logStep?.("scheduleExecution_","skipped_because_already_running");return}this.isRunning__=true;try{await delay4.nextMacrotask();if(this.isDestroyed__){this.logger_.incident?.("scheduleExecution_","destroyed_during_delay");this.isRunning__=false;return}this.logger_.logStep?.("scheduleExecution_","executing_effect");await this.config_.run()}catch(err){this.logger_.error("scheduleExecution_","effect_failed",err)}this.isRunning__=false}destroy(){this.logger_.logMethod?.("destroy");if(this.isDestroyed__){this.logger_.incident?.("destroy","already_destroyed");return}this.isDestroyed__=true;for(const subscription of this.dependencySubscriptions__){subscription.unsubscribe()}this.dependencySubscriptions__.length=0;this.config_.onDestroy?.();this.config_=null}};function createEventSignal(config){return new EventSignal(config)}function createStateSignal(config){return new StateSignal(config)}function createComputedSignal(config){return new ComputedSignal(config)}function createEffect(config){return new EffectSignal(config)}import{createDebouncer}from"@alwatr/debounce";function createDebouncedSignal(sourceSignal,config){const name=config.name??`${sourceSignal.name}-debounced`;const internalSignal=new StateSignal({name:`${name}-internal`,initialValue:sourceSignal.get()});const debouncer=createDebouncer({...config,func:value=>{internalSignal.set(value)}});const subscription=sourceSignal.subscribe(value=>debouncer.trigger(value),{receivePrevious:false});return createComputedSignal({name,deps:[internalSignal],get:()=>internalSignal.get(),onDestroy:()=>{if(internalSignal.isDestroyed)return;subscription.unsubscribe();debouncer.cancel();internalSignal.destroy();config.onDestroy?.();config=null}})}export{ComputedSignal,EffectSignal,EventSignal,SignalBase,StateSignal,createComputedSignal,createDebouncedSignal,createEffect,createEventSignal,createStateSignal};
|
|
3
4
|
//# sourceMappingURL=main.mjs.map
|
package/dist/main.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/core/signal-base.ts", "../src/core/event-signal.ts", "../src/core/state-signal.ts", "../src/core/computed-signal.ts", "../src/core/effect-signal.ts", "../src/creators/event.ts", "../src/creators/state.ts", "../src/creators/computed.ts", "../src/creators/effect.ts", "../src/operators/debounce.ts"],
|
|
4
|
-
"sourcesContent": ["import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\n\n/**\n * An abstract base class for signal implementations.\n * It provides the core functionality for managing subscriptions (observers).\n *\n * @template T The type of data that the signal holds or dispatches.\n */\nexport abstract class SignalBase<T> {\n /**\n * The unique identifier for this signal instance.\n * Useful for debugging and logging.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected abstract logger_: AlwatrLogger;\n\n /**\n * The list of observers (listeners) subscribed to this signal.\n * @protected\n */\n protected readonly observers_: Observer_<T>[] = [];\n\n /**\n * A flag indicating whether the signal has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n public constructor(protected config_: SignalConfig) {}\n\n /**\n * Removes a specific observer from the observers list.\n *\n * @param observer The observer instance to remove.\n * @protected\n */\n protected removeObserver_(observer: Observer_<T>): void {\n this.logger_.logMethod?.('removeObserver_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('removeObserver_', 'remove_observer_on_destroyed_signal');\n return;\n }\n\n const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\n }\n\n /**\n * Subscribes a listener function to this signal.\n *\n * The listener will be called whenever the signal is notified (e.g., when `dispatch` or `set` is called).\n *\n * @param callback The function to be called when the signal is dispatched.\n * @param options Subscription options to customize the behavior (e.g., `once`, `priority`).\n * @returns A `SubscribeResult` object with an `unsubscribe` method to remove the listener.\n */\n public subscribe(callback: ListenerCallback<T>, options?: SubscribeOptions): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe.base', options);\n this.checkDestroyed_();\n\n const observer: Observer_<T> = {callback, options};\n\n if (options?.priority) {\n // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(observer);\n }\n\n // The returned unsubscribe function is a closure that calls the internal removal method.\n return {\n unsubscribe: (): void => this.removeObserver_(observer),\n };\n }\n\n /**\n * Notifies all registered observers about a new value.\n *\n * This method iterates through a snapshot of the current observers to prevent issues\n * with subscriptions changing during notification (e.g., an observer unsubscribing itself).\n *\n * @param value The new value to notify observers about.\n * @protected\n */\n protected notify_(value: T): void {\n this.logger_.logMethodArgs?.('notify_', value);\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('notify_', 'notify_on_destroyed_signal');\n return;\n }\n\n // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\n\n try {\n const result = observer.callback(value);\n if (result instanceof Promise) {\n result.catch((err) => this.logger_.error('notify_', 'async_callback_failed', err, {observer}));\n }\n }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\n }\n }\n\n /**\n * Returns a Promise that resolves with the next value dispatched by the signal.\n * This provides an elegant way to wait for a single, future event using `async/await`.\n *\n * @returns A Promise that resolves with the next dispatched value.\n *\n * @example\n * async function onButtonClick() {\n * console.log('Waiting for the next signal...');\n * const nextValue = await mySignal.untilNext();\n * console.log('Signal received:', nextValue);\n * }\n */\n public untilNext(): Promise<T> {\n this.logger_.logMethod?.('untilNext');\n this.checkDestroyed_();\n return new Promise((resolve) => {\n this.subscribe(resolve, {\n once: true,\n priority: true, // Resolve the promise before other listeners are called.\n receivePrevious: false, // We only want the *next* value, not the current one.\n });\n });\n }\n\n /**\n * Destroys the signal, clearing all its listeners and making it inactive.\n *\n * After destruction, any interaction with the signal (like `subscribe` or `untilNext`)\n * will throw an error. This is crucial for preventing memory leaks by allowing\n * garbage collection of the signal and its observers.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy_', 'double_destroy_attempt');\n return;\n }\n this.isDestroyed__ = true;\n this.observers_.length = 0; // Clear all observers.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as SignalConfig; // Help GC by breaking references.\n }\n\n /**\n * Throws an error if the signal has been destroyed.\n * This is a safeguard to prevent interaction with a defunct signal.\n * @protected\n */\n protected checkDestroyed_(): void {\n if (this.isDestroyed__) {\n this.logger_.accident('checkDestroyed_', 'attempt_to_use_destroyed_signal');\n throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`);\n }\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * A stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events. Defaults to `void` for events without a payload.\n *\n * @example\n * // Create a signal for user click events.\n * const onUserClick = new EventSignal<{ x: number, y: number }>({ name: 'on-user-click' });\n *\n * // Subscribe to the event.\n * onUserClick.subscribe(clickPosition => {\n * console.log(`User clicked at: ${clickPosition.x}, ${clickPosition.y}`);\n * });\n *\n * // Dispatch an event.\n * onUserClick.dispatch({ x: 100, y: 250 }); // Notifies the listener.\n *\n * // --- Example with no payload ---\n * const onAppReady = new EventSignal({ name: 'on-app-ready' });\n * onAppReady.subscribe(() => console.log('Application is ready!'));\n * onAppReady.dispatch(); // Notifies the listener.\n */\nexport class EventSignal<T = void> extends SignalBase<T> {\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`event-signal:${this.name}`);\n\n public constructor(config: SignalConfig) {\n super(config);\n this.logger_.logMethod?.('constructor');\n }\n\n /**\n * Dispatches an event with an optional payload to all active listeners.\n * The notification is scheduled as a microtask to prevent blocking and ensure\n * a consistent, non-blocking flow.\n *\n * @param payload The data to send with the event.\n */\n public dispatch(payload: T): void {\n this.logger_.logMethodArgs?.('dispatch', {payload});\n this.checkDestroyed_();\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(payload));\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {StateSignalConfig, ListenerCallback, SubscribeOptions, SubscribeResult, IReadonlySignal} from '../type.js';\n\n/**\n * A stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n * @implements {IReadonlySignal<T>}\n *\n * @example\n * // Create a new state signal with an initial value.\n * const counter = new StateSignal<number>({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * // Get the current value.\n * console.log(counter.get()); // Outputs: 0\n *\n * // Subscribe to changes.\n * const subscription = counter.subscribe(newValue => {\n * console.log(`Counter changed to: ${newValue}`);\n * });\n *\n * // Set a new value, which triggers the notification.\n * counter.set(1); // Outputs: \"Counter changed to: 1\"\n *\n * // Update value based on the previous value.\n * counter.update(current => current + 1); // Outputs: \"Counter changed to: 2\"\n *\n * // Unsubscribe when no longer needed.\n * subscription.unsubscribe();\n */\nexport class StateSignal<T> extends SignalBase<T> implements IReadonlySignal<T> {\n /**\n * The current value of the signal.\n * @private\n */\n private value__: T;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`state-signal:${this.name}`);\n\n public constructor(config: StateSignalConfig<T>) {\n super(config);\n this.value__ = config.initialValue;\n this.logger_.logMethodArgs?.('constructor', {initialValue: this.value__});\n }\n\n /**\n * Retrieves the current value of the signal.\n *\n * @returns The current value.\n *\n * @example\n * console.log(mySignal.get());\n */\n public get(): T {\n this.checkDestroyed_();\n return this.value__;\n }\n\n /**\n * Updates the signal's value and notifies all active listeners.\n *\n * The notification is scheduled as a microtask, which means the update is deferred\n * slightly to batch multiple synchronous changes.\n *\n * @param newValue The new value to set.\n *\n * @example\n * // For primitive types\n * mySignal.set(42);\n *\n * // For object types, it's best practice to set an immutable new object.\n * mySignal.set({ ...mySignal.get(), property: 'new-value' });\n */\n public set(newValue: T): void {\n this.logger_.logMethodArgs?.('set', {newValue});\n this.checkDestroyed_();\n\n // For primitives (including null), do not notify if the value is the same.\n if (Object.is(this.value__, newValue) && (typeof newValue !== 'object' || newValue === null)) {\n return;\n }\n\n this.value__ = newValue;\n\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(newValue));\n }\n\n /**\n * Updates the signal's value based on its previous value.\n *\n * This method is particularly useful for state transitions that depend on the current value,\n * especially for objects or arrays, as it promotes an immutable update pattern.\n *\n * @param updater A function that receives the current value and returns the new value.\n *\n * @example\n * // For a counter\n * counterSignal.update(current => current + 1);\n *\n * // For an object state\n * userSignal.update(currentUser => ({ ...currentUser, loggedIn: true }));\n */\n public update(updater: (previousValue: T) => T): void {\n this.checkDestroyed_();\n const newValue = updater(this.value__);\n this.logger_.logMethodFull?.('update', this.value__, newValue);\n this.set(newValue);\n }\n\n /**\n * Subscribes a listener to this signal.\n *\n * By default, the listener is immediately called with the signal's current value (`receivePrevious: true`).\n * This behavior can be customized via the `options` parameter.\n *\n * @param callback The function to be called when the signal's value changes.\n * @param options Subscription options, including `receivePrevious` and `once`.\n * @returns An object with an `unsubscribe` method to remove the listener.\n */\n public override subscribe(callback: ListenerCallback<T>, options: SubscribeOptions = {}): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe', options);\n this.checkDestroyed_();\n\n // By default, new subscribers to a StateSignal should receive the current value.\n if (options.receivePrevious !== false) {\n // Immediately (but asynchronously) call the listener with the current value.\n // This is done in a microtask to ensure it happens after the subscription is fully registered.\n delay\n .nextMicrotask()\n .then(() => {\n this.logger_.logStep?.('subscribe', 'immediate_callback');\n callback(this.value__);\n })\n .catch((err) => this.logger_.error('subscribe', 'immediate_callback_failed', err));\n\n // If it's a 'once' subscription that receives the previous value, it's now fulfilled.\n // We don't need to add it to the observers list for future updates.\n if (options.once) {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return {unsubscribe: () => {}};\n }\n }\n\n return super.subscribe(callback, options);\n }\n\n /**\n * Destroys the signal, clearing its value and all listeners.\n * This is crucial for memory management to prevent leaks.\n */\n public override destroy(): void {\n this.value__ = null as T; // Clear the value to allow for garbage collection.\n super.destroy();\n }\n\n public asReadonly(): IReadonlySignal<T> {\n return this;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {StateSignal} from './state-signal.js';\n\nimport type {ComputedSignalConfig, IReadonlySignal, SubscribeResult, SubscribeOptions} from '../type.js';\n\n/**\n * A read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @example\n * // --- Create dependency signals ---\n * const firstName = new StateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = new StateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * // --- Create a computed signal ---\n * const fullName = new ComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // Outputs: \"John Doe\"\n *\n * // --- Subscribe to the computed value ---\n * fullName.subscribe(newFullName => {\n * console.log(`Name changed to: ${newFullName}`);\n * });\n *\n * // --- Update a dependency ---\n * lastName.set('Smith'); // Recalculates and logs: \"Name changed to: John Smith\"\n * console.log(fullName.get()); // Outputs: \"John Smith\"\n *\n * // --- IMPORTANT: Clean up when done ---\n * fullName.destroy();\n */\nexport class ComputedSignal<T> implements IReadonlySignal<T> {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\n\n /**\n * The internal `StateSignal` that holds the computed value.\n * This is how the computed signal provides `.get()` and `.subscribe()` methods.\n * @protected\n */\n protected readonly internalSignal_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent recalculations.\n * @private\n */\n private isRecalculating__ = false;\n\n public constructor(protected config_: ComputedSignalConfig<T>) {\n this.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\n\n // Subscribe to all dependencies to trigger recalculation on change.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_, {receivePrevious: false}));\n }\n }\n\n /**\n * The current value of the computed signal.\n * Accessing this property returns the memoized value and does not trigger a recalculation.\n *\n * @returns The current computed value.\n * @throws {Error} If accessed after the signal has been destroyed.\n */\n public get(): T {\n return this.internalSignal_.get();\n }\n\n /**\n * Indicates whether the computed signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.internalSignal_.isDestroyed;\n }\n\n /**\n * Subscribes a listener to this signal.\n * The listener will be called whenever the computed value changes.\n *\n * @param callback The function to be called with the new value.\n * @param options Subscription options.\n * @returns A `SubscribeResult` object with an `unsubscribe` method.\n */\n public subscribe(callback: (value: T) => void, options?: SubscribeOptions): SubscribeResult {\n return this.internalSignal_.subscribe(callback, options);\n }\n\n /**\n * Returns a Promise that resolves with the next computed value.\n *\n * @returns A Promise that resolves with the next value.\n */\n public untilNext(): Promise<T> {\n return this.internalSignal_.untilNext();\n }\n\n /**\n * Permanently disposes of the computed signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping future recalculations and allowing the signal to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks.\n *\n * After `destroy()` is called, any attempt to access `.get()` or `.subscribe()` will throw an error.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n /**\n * If already destroyed, log an incident and return early.\n */\n if (this.isDestroyed) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.internalSignal_.destroy(); // Destroy the internal signal.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as ComputedSignalConfig<T>; // Release config closure.\n }\n\n /**\n * Schedules a recalculation of the signal's value.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `get` function runs only once per event loop tick, even if multiple dependencies\n * change in the same synchronous block of code.\n * @protected\n */\n protected async recalculate_(): Promise<void> {\n this.logger_.logMethod?.('recalculate_');\n\n if (this.internalSignal_.isDestroyed) {\n // This check is important in case a dependency fires after this signal is destroyed.\n this.logger_.incident?.('recalculate_', 'recalculate_on_destroyed_signal');\n return;\n }\n\n if (this.isRecalculating__) {\n // If a recalculation is already scheduled, do nothing.\n this.logger_.logStep?.('recalculate_', 'skipping_recalculation_already_scheduled');\n return;\n }\n\n this.isRecalculating__ = true;\n\n try {\n // Wait for the next macrotask to start the recalculation.\n // This batches all synchronous dependency updates in the current event loop.\n await delay.nextMacrotask();\n\n if (this.isDestroyed) {\n this.logger_.incident?.('recalculate_', 'destroyed_during_delay');\n this.isRecalculating__ = false;\n return;\n }\n\n this.logger_.logStep?.('recalculate_', 'recalculating_value');\n\n // Set the new value on the internal signal, which will notify our subscribers.\n this.internalSignal_.set(this.config_.get());\n }\n catch (err) {\n this.logger_.error('recalculate_', 'recalculation_failed', err);\n }\n\n // Allow the next recalculation to be scheduled.\n this.isRecalculating__ = false;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n public constructor(protected config_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates a stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates a stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates a read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type {Observer_, SubscribeOptions, SubscribeResult, ListenerCallback, SignalConfig} from '../type.js';\nimport type {AlwatrLogger} from '@alwatr/logger';\nimport type {} from '@alwatr/nano-build';\n\n/**\n * An abstract base class for signal implementations.\n * It provides the core functionality for managing subscriptions (observers).\n *\n * @template T The type of data that the signal holds or dispatches.\n */\nexport abstract class SignalBase<T> {\n /**\n * The unique identifier for this signal instance.\n * Useful for debugging and logging.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected abstract logger_: AlwatrLogger;\n\n /**\n * The list of observers (listeners) subscribed to this signal.\n * @protected\n */\n protected readonly observers_: Observer_<T>[] = [];\n\n /**\n * A flag indicating whether the signal has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n constructor(protected config_: SignalConfig) {}\n\n /**\n * Removes a specific observer from the observers list.\n *\n * @param observer The observer instance to remove.\n * @protected\n */\n protected removeObserver_(observer: Observer_<T>): void {\n this.logger_.logMethod?.('removeObserver_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('removeObserver_', 'remove_observer_on_destroyed_signal');\n return;\n }\n\n const index = this.observers_.indexOf(observer);\n if (index !== -1) {\n this.observers_.splice(index, 1);\n }\n }\n\n /**\n * Subscribes a listener function to this signal.\n *\n * The listener will be called whenever the signal is notified (e.g., when `dispatch` or `set` is called).\n *\n * @param callback The function to be called when the signal is dispatched.\n * @param options Subscription options to customize the behavior (e.g., `once`, `priority`).\n * @returns A `SubscribeResult` object with an `unsubscribe` method to remove the listener.\n */\n public subscribe(callback: ListenerCallback<T>, options?: SubscribeOptions): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe.base', options);\n this.checkDestroyed_();\n\n const observer: Observer_<T> = {callback, options};\n\n if (options?.priority) {\n // High-priority observers are added to the front of the queue.\n this.observers_.unshift(observer);\n }\n else {\n this.observers_.push(observer);\n }\n\n // The returned unsubscribe function is a closure that calls the internal removal method.\n return {\n unsubscribe: (): void => this.removeObserver_(observer),\n };\n }\n\n /**\n * Notifies all registered observers about a new value.\n *\n * This method iterates through a snapshot of the current observers to prevent issues\n * with subscriptions changing during notification (e.g., an observer unsubscribing itself).\n *\n * @param value The new value to notify observers about.\n * @protected\n */\n protected notify_(value: T): void {\n this.logger_.logMethodArgs?.('notify_', value);\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('notify_', 'notify_on_destroyed_signal');\n return;\n }\n\n // Create a snapshot of the observers array to iterate over.\n // This prevents issues if the observers_ array is modified during the loop.\n const currentObservers = [...this.observers_];\n\n for (const observer of currentObservers) {\n if (observer.options?.once) {\n this.removeObserver_(observer);\n }\n\n try {\n const result = observer.callback(value);\n if (result instanceof Promise) {\n result.catch((err) => this.logger_.error('notify_', 'async_callback_failed', err, {observer}));\n }\n }\n catch (err) {\n this.logger_.error('notify_', 'sync_callback_failed', err);\n }\n }\n }\n\n /**\n * Returns a Promise that resolves with the next value dispatched by the signal.\n * This provides an elegant way to wait for a single, future event using `async/await`.\n *\n * @returns A Promise that resolves with the next dispatched value.\n *\n * @example\n * async function onButtonClick() {\n * console.log('Waiting for the next signal...');\n * const nextValue = await mySignal.untilNext();\n * console.log('Signal received:', nextValue);\n * }\n */\n public untilNext(): Promise<T> {\n this.logger_.logMethod?.('untilNext');\n this.checkDestroyed_();\n return new Promise((resolve) => {\n this.subscribe(resolve, {\n once: true,\n priority: true, // Resolve the promise before other listeners are called.\n receivePrevious: false, // We only want the *next* value, not the current one.\n });\n });\n }\n\n /**\n * Destroys the signal, clearing all its listeners and making it inactive.\n *\n * After destruction, any interaction with the signal (like `subscribe` or `untilNext`)\n * will throw an error. This is crucial for preventing memory leaks by allowing\n * garbage collection of the signal and its observers.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy_', 'double_destroy_attempt');\n return;\n }\n this.isDestroyed__ = true;\n this.observers_.length = 0; // Clear all observers.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as SignalConfig; // Help GC by breaking references.\n }\n\n /**\n * Throws an error if the signal has been destroyed.\n * This is a safeguard to prevent interaction with a defunct signal.\n * @protected\n */\n protected checkDestroyed_(): void {\n if (this.isDestroyed__) {\n this.logger_.accident('checkDestroyed_', 'attempt_to_use_destroyed_signal');\n throw new Error(`Cannot interact with a destroyed signal (id: ${this.name})`);\n }\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * A stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events. Defaults to `void` for events without a payload.\n *\n * @example\n * // Create a signal for user click events.\n * const onUserClick = new EventSignal<{ x: number, y: number }>({ name: 'on-user-click' });\n *\n * // Subscribe to the event.\n * onUserClick.subscribe(clickPosition => {\n * console.log(`User clicked at: ${clickPosition.x}, ${clickPosition.y}`);\n * });\n *\n * // Dispatch an event.\n * onUserClick.dispatch({ x: 100, y: 250 }); // Notifies the listener.\n *\n * // --- Example with no payload ---\n * const onAppReady = new EventSignal({ name: 'on-app-ready' });\n * onAppReady.subscribe(() => console.log('Application is ready!'));\n * onAppReady.dispatch(); // Notifies the listener.\n */\nexport class EventSignal<T = void> extends SignalBase<T> {\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`event-signal:${this.name}`);\n\n constructor(config: SignalConfig) {\n super(config);\n this.logger_.logMethod?.('constructor');\n }\n\n /**\n * Dispatches an event with an optional payload to all active listeners.\n * The notification is scheduled as a microtask to prevent blocking and ensure\n * a consistent, non-blocking flow.\n *\n * @param payload The data to send with the event.\n */\n public dispatch(payload: T): void {\n this.logger_.logMethodArgs?.('dispatch', {payload});\n this.checkDestroyed_();\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(payload));\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {SignalBase} from './signal-base.js';\n\nimport type {StateSignalConfig, ListenerCallback, SubscribeOptions, SubscribeResult, IReadonlySignal} from '../type.js';\n\n/**\n * A stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n * @implements {IReadonlySignal<T>}\n *\n * @example\n * // Create a new state signal with an initial value.\n * const counter = new StateSignal<number>({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * // Get the current value.\n * console.log(counter.get()); // Outputs: 0\n *\n * // Subscribe to changes.\n * const subscription = counter.subscribe(newValue => {\n * console.log(`Counter changed to: ${newValue}`);\n * });\n *\n * // Set a new value, which triggers the notification.\n * counter.set(1); // Outputs: \"Counter changed to: 1\"\n *\n * // Update value based on the previous value.\n * counter.update(current => current + 1); // Outputs: \"Counter changed to: 2\"\n *\n * // Unsubscribe when no longer needed.\n * subscription.unsubscribe();\n */\nexport class StateSignal<T> extends SignalBase<T> implements IReadonlySignal<T> {\n /**\n * The current value of the signal.\n * @private\n */\n private value__: T;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected logger_ = createLogger(`state-signal:${this.name}`);\n\n constructor(config: StateSignalConfig<T>) {\n super(config);\n this.value__ = config.initialValue;\n this.logger_.logMethodArgs?.('constructor', {initialValue: this.value__});\n }\n\n /**\n * Retrieves the current value of the signal.\n *\n * @returns The current value.\n *\n * @example\n * console.log(mySignal.get());\n */\n public get(): T {\n this.checkDestroyed_();\n return this.value__;\n }\n\n /**\n * Updates the signal's value and notifies all active listeners.\n *\n * The notification is scheduled as a microtask, which means the update is deferred\n * slightly to batch multiple synchronous changes.\n *\n * @param newValue The new value to set.\n *\n * @example\n * // For primitive types\n * mySignal.set(42);\n *\n * // For object types, it's best practice to set an immutable new object.\n * mySignal.set({ ...mySignal.get(), property: 'new-value' });\n */\n public set(newValue: T): void {\n this.logger_.logMethodArgs?.('set', {newValue});\n this.checkDestroyed_();\n\n // For primitives (including null), do not notify if the value is the same.\n if (Object.is(this.value__, newValue) && (typeof newValue !== 'object' || newValue === null)) {\n return;\n }\n\n this.value__ = newValue;\n\n // Dispatch as a microtask to ensure consistent, non-blocking behavior.\n delay.nextMicrotask().then(() => this.notify_(newValue));\n }\n\n /**\n * Updates the signal's value based on its previous value.\n *\n * This method is particularly useful for state transitions that depend on the current value,\n * especially for objects or arrays, as it promotes an immutable update pattern.\n *\n * @param updater A function that receives the current value and returns the new value.\n *\n * @example\n * // For a counter\n * counterSignal.update(current => current + 1);\n *\n * // For an object state\n * userSignal.update(currentUser => ({ ...currentUser, loggedIn: true }));\n */\n public update(updater: (previousValue: T) => T): void {\n this.checkDestroyed_();\n const newValue = updater(this.value__);\n this.logger_.logMethodFull?.('update', this.value__, newValue);\n this.set(newValue);\n }\n\n /**\n * Subscribes a listener to this signal.\n *\n * By default, the listener is immediately called with the signal's current value (`receivePrevious: true`).\n * This behavior can be customized via the `options` parameter.\n *\n * @param callback The function to be called when the signal's value changes.\n * @param options Subscription options, including `receivePrevious` and `once`.\n * @returns An object with an `unsubscribe` method to remove the listener.\n */\n public override subscribe(callback: ListenerCallback<T>, options: SubscribeOptions = {}): SubscribeResult {\n this.logger_.logMethodArgs?.('subscribe', options);\n this.checkDestroyed_();\n\n // By default, new subscribers to a StateSignal should receive the current value.\n if (options.receivePrevious !== false) {\n // Immediately (but asynchronously) call the listener with the current value.\n // This is done in a microtask to ensure it happens after the subscription is fully registered.\n delay\n .nextMicrotask()\n .then(() => {\n this.logger_.logStep?.('subscribe', 'immediate_callback');\n callback(this.value__);\n })\n .catch((err) => this.logger_.error('subscribe', 'immediate_callback_failed', err));\n\n // If it's a 'once' subscription that receives the previous value, it's now fulfilled.\n // We don't need to add it to the observers list for future updates.\n if (options.once) {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return {unsubscribe: () => {}};\n }\n }\n\n return super.subscribe(callback, options);\n }\n\n /**\n * Destroys the signal, clearing its value and all listeners.\n * This is crucial for memory management to prevent leaks.\n */\n public override destroy(): void {\n this.value__ = null as T; // Clear the value to allow for garbage collection.\n super.destroy();\n }\n\n public asReadonly(): IReadonlySignal<T> {\n return this;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport {StateSignal} from './state-signal.js';\n\nimport type {ComputedSignalConfig, IReadonlySignal, SubscribeResult, SubscribeOptions} from '../type.js';\n\n/**\n * A read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @example\n * // --- Create dependency signals ---\n * const firstName = new StateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = new StateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * // --- Create a computed signal ---\n * const fullName = new ComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // Outputs: \"John Doe\"\n *\n * // --- Subscribe to the computed value ---\n * fullName.subscribe(newFullName => {\n * console.log(`Name changed to: ${newFullName}`);\n * });\n *\n * // --- Update a dependency ---\n * lastName.set('Smith'); // Recalculates and logs: \"Name changed to: John Smith\"\n * console.log(fullName.get()); // Outputs: \"John Smith\"\n *\n * // --- IMPORTANT: Clean up when done ---\n * fullName.destroy();\n */\nexport class ComputedSignal<T> implements IReadonlySignal<T> {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`computed-signal:${this.name}`);\n\n /**\n * The internal `StateSignal` that holds the computed value.\n * This is how the computed signal provides `.get()` and `.subscribe()` methods.\n * @protected\n */\n protected readonly internalSignal_ = new StateSignal<T>({\n name: `compute-${this.name}_`,\n initialValue: this.config_.get(),\n });\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent recalculations.\n * @private\n */\n private isRecalculating__ = false;\n\n constructor(protected config_: ComputedSignalConfig<T>) {\n this.logger_.logMethod?.('constructor');\n this.recalculate_ = this.recalculate_.bind(this);\n\n // Subscribe to all dependencies to trigger recalculation on change.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.recalculate_, {receivePrevious: false}));\n }\n }\n\n /**\n * The current value of the computed signal.\n * Accessing this property returns the memoized value and does not trigger a recalculation.\n *\n * @returns The current computed value.\n * @throws {Error} If accessed after the signal has been destroyed.\n */\n public get(): T {\n return this.internalSignal_.get();\n }\n\n /**\n * Indicates whether the computed signal has been destroyed.\n * A destroyed signal cannot be used and will throw an error if interacted with.\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.internalSignal_.isDestroyed;\n }\n\n /**\n * Subscribes a listener to this signal.\n * The listener will be called whenever the computed value changes.\n *\n * @param callback The function to be called with the new value.\n * @param options Subscription options.\n * @returns A `SubscribeResult` object with an `unsubscribe` method.\n */\n public subscribe(callback: (value: T) => void, options?: SubscribeOptions): SubscribeResult {\n return this.internalSignal_.subscribe(callback, options);\n }\n\n /**\n * Returns a Promise that resolves with the next computed value.\n *\n * @returns A Promise that resolves with the next value.\n */\n public untilNext(): Promise<T> {\n return this.internalSignal_.untilNext();\n }\n\n /**\n * Permanently disposes of the computed signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping future recalculations and allowing the signal to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks.\n *\n * After `destroy()` is called, any attempt to access `.get()` or `.subscribe()` will throw an error.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n /**\n * If already destroyed, log an incident and return early.\n */\n if (this.isDestroyed) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.internalSignal_.destroy(); // Destroy the internal signal.\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as ComputedSignalConfig<T>; // Release config closure.\n }\n\n /**\n * Schedules a recalculation of the signal's value.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `get` function runs only once per event loop tick, even if multiple dependencies\n * change in the same synchronous block of code.\n * @protected\n */\n protected async recalculate_(): Promise<void> {\n this.logger_.logMethod?.('recalculate_');\n\n if (this.internalSignal_.isDestroyed) {\n // This check is important in case a dependency fires after this signal is destroyed.\n this.logger_.incident?.('recalculate_', 'recalculate_on_destroyed_signal');\n return;\n }\n\n if (this.isRecalculating__) {\n // If a recalculation is already scheduled, do nothing.\n this.logger_.logStep?.('recalculate_', 'skipping_recalculation_already_scheduled');\n return;\n }\n\n this.isRecalculating__ = true;\n\n try {\n // Wait for the next macrotask to start the recalculation.\n // This batches all synchronous dependency updates in the current event loop.\n await delay.nextMacrotask();\n\n if (this.isDestroyed) {\n this.logger_.incident?.('recalculate_', 'destroyed_during_delay');\n this.isRecalculating__ = false;\n return;\n }\n\n this.logger_.logStep?.('recalculate_', 'recalculating_value');\n\n // Set the new value on the internal signal, which will notify our subscribers.\n this.internalSignal_.set(this.config_.get());\n }\n catch (err) {\n this.logger_.error('recalculate_', 'recalculation_failed', err);\n }\n\n // Allow the next recalculation to be scheduled.\n this.isRecalculating__ = false;\n }\n}\n", "import {delay} from '@alwatr/delay';\nimport {createLogger} from '@alwatr/logger';\n\nimport type {EffectSignalConfig, IEffectSignal, SubscribeResult} from '../type.js';\n\n/**\n * Manages a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @implements {IEffectSignal}\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = new StateSignal({ initialValue: 0, name: 'counter' });\n * const user = new StateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = new EffectSignal({\n * name: 'analytics-effect',\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport class EffectSignal implements IEffectSignal {\n /**\n * The unique identifier for this signal instance.\n */\n public readonly name = this.config_.name ?? `[${this.config_.deps.map((dep) => dep.name).join(', ')}]`;\n\n /**\n * The logger instance for this signal.\n * @protected\n */\n protected readonly logger_ = createLogger(`effect-signal:${this.name}`);\n\n /**\n * A list of subscriptions to dependency signals.\n * @private\n */\n private readonly dependencySubscriptions__: SubscribeResult[] = [];\n\n /**\n * A flag to prevent concurrent executions of the effect.\n * @private\n */\n private isRunning__ = false;\n\n /**\n * A flag indicating whether the effect has been destroyed.\n * @private\n */\n private isDestroyed__ = false;\n\n /**\n * Indicates whether the effect signal has been destroyed.\n * A destroyed signal will no longer execute its effect and cannot be reused.\n *\n * @returns `true` if the signal is destroyed, `false` otherwise.\n */\n public get isDestroyed(): boolean {\n return this.isDestroyed__;\n }\n\n constructor(protected config_: EffectSignalConfig) {\n this.logger_.logMethod?.('constructor');\n this.scheduleExecution_ = this.scheduleExecution_.bind(this);\n\n // Subscribe to all dependencies. We don't need the previous value,\n // as the `runImmediately` option controls the initial execution.\n for (const signal of config_.deps) {\n this.logger_.logStep?.('constructor', 'subscribing_to_dependency', {signal: signal.name});\n this.dependencySubscriptions__.push(signal.subscribe(this.scheduleExecution_, {receivePrevious: false}));\n }\n\n // Run the effect immediately if requested.\n if (config_.runImmediately === true) {\n this.logger_.logStep?.('constructor', 'scheduling_initial_execution');\n // We don't need to await this, let it run in the background.\n void this.scheduleExecution_();\n }\n }\n\n /**\n * Schedules the execution of the effect's `run` function.\n *\n * This method batches updates using a macrotask (`delay.nextMacrotask`) to ensure the\n * `run` function executes only once per event loop tick, even if multiple\n * dependencies change simultaneously.\n * @protected\n */\n protected async scheduleExecution_(): Promise<void> {\n this.logger_.logMethod?.('scheduleExecution_');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'schedule_execution_on_destroyed_signal');\n return;\n }\n if (this.isRunning__) {\n // If an execution is already scheduled, do nothing.\n this.logger_.logStep?.('scheduleExecution_', 'skipped_because_already_running');\n return;\n }\n\n this.isRunning__ = true;\n\n try {\n // Wait for the next macrotask to batch simultaneous updates.\n await delay.nextMacrotask();\n if (this.isDestroyed__) {\n this.logger_.incident?.('scheduleExecution_', 'destroyed_during_delay');\n this.isRunning__ = false;\n return;\n }\n\n this.logger_.logStep?.('scheduleExecution_', 'executing_effect');\n await this.config_.run();\n }\n catch (err) {\n this.logger_.error('scheduleExecution_', 'effect_failed', err);\n }\n\n // Reset the flag after the current execution is complete.\n this.isRunning__ = false;\n }\n\n /**\n * Permanently disposes of the effect signal.\n *\n * This is a critical cleanup step. It unsubscribes from all dependency signals,\n * stopping any future executions of the effect and allowing it to be garbage collected.\n * Failure to call `destroy()` will result in memory leaks and potentially unwanted side effects.\n */\n public destroy(): void {\n this.logger_.logMethod?.('destroy');\n\n if (this.isDestroyed__) {\n this.logger_.incident?.('destroy', 'already_destroyed');\n return;\n }\n\n this.isDestroyed__ = true;\n\n // Unsubscribe from all upstream dependencies.\n for (const subscription of this.dependencySubscriptions__) {\n subscription.unsubscribe();\n }\n this.dependencySubscriptions__.length = 0; // Clear the array of subscriptions.\n\n this.config_.onDestroy?.(); // Call the optional onDestroy callback.\n this.config_ = null as unknown as EffectSignalConfig; // Release config closure.\n }\n}\n", "import {EventSignal} from '../core/event-signal.js';\n\nimport type {SignalConfig} from '../type.js';\n\n/**\n * Creates a stateless signal for dispatching transient events.\n *\n * `EventSignal` is ideal for broadcasting events that do not have a persistent state.\n * Unlike `StateSignal`, it does not hold a value. Listeners are only notified of new\n * events as they are dispatched. This makes it suitable for modeling user interactions,\n * system notifications, or any one-off message.\n *\n * @template T The type of the payload for the events.\n *\n * @param config The configuration for the event signal.\n * @returns A new instance of EventSignal.\n *\n * @example\n * const onUserClick = createEventSignal<{ x: number, y: number }>({\n * name: 'on-user-click'\n * });\n *\n * onUserClick.subscribe(pos => {\n * console.log(`User clicked at: ${pos.x}, ${pos.y}`);\n * });\n *\n * onUserClick.dispatch({ x: 100, y: 250 });\n */\nexport function createEventSignal<T = void>(config: SignalConfig): EventSignal<T> {\n return new EventSignal<T>(config);\n}\n", "import {StateSignal} from '../core/state-signal.js';\n\nimport type {StateSignalConfig} from '../type.js';\n\n/**\n * Creates a stateful signal that holds a value and notifies listeners when the value changes.\n *\n * `StateSignal` is the core of the signal library, representing a piece of mutable state.\n * It always has a value, and new subscribers immediately receive the current value by default.\n *\n * @template T The type of the state it holds.\n *\n * @param config The configuration for the state signal.\n * @returns A new instance of StateSignal.\n *\n * @example\n * const counter = createStateSignal({\n * name: 'counter-signal',\n * initialValue: 0,\n * });\n *\n * console.log(counter.get()); // Outputs: 0\n * counter.set(1);\n * console.log(counter.get()); // Outputs: 1\n */\nexport function createStateSignal<T>(config: StateSignalConfig<T>): StateSignal<T> {\n return new StateSignal(config);\n}\n", "import {ComputedSignal} from '../core/computed-signal.js';\n\nimport type {ComputedSignalConfig} from '../type.js';\n\n/**\n * Creates a read-only signal that derives its value from a set of dependency signals.\n *\n * `ComputedSignal` is a powerful tool for creating values that reactively update when their underlying\n * data sources change. Its value is memoized, meaning the `get` function is only re-evaluated when\n * one of its dependencies has actually changed.\n *\n * A key feature is its lifecycle management: a `ComputedSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks from its subscriptions to dependency signals.\n *\n * @template T The type of the computed value.\n *\n * @param config The configuration for the computed signal.\n * @returns A new, read-only computed signal.\n *\n * @example\n * const firstName = createStateSignal({ name: 'firstName', initialValue: 'John' });\n * const lastName = createStateSignal({ name: 'lastName', initialValue: 'Doe' });\n *\n * const fullName = createComputedSignal({\n * name: 'fullName',\n * deps: [firstName, lastName],\n * get: () => `${firstName.get()} ${lastName.get()}`,\n * });\n *\n * console.log(fullName.get()); // \"John Doe\"\n *\n * // IMPORTANT: Always destroy a computed signal when no longer needed.\n * // fullName.destroy();\n */\nexport function createComputedSignal<T>(config: ComputedSignalConfig<T>): ComputedSignal<T> {\n return new ComputedSignal(config);\n}\n", "import {EffectSignal} from '../core/effect-signal.js';\n\nimport type {EffectSignalConfig} from '../type.js';\n\n/**\n * Creates a side-effect that runs in response to changes in dependency signals.\n *\n * `EffectSignal` is designed for running logic that interacts with the \"outside world\"—such as\n * logging, network requests, or DOM manipulation—whenever its dependencies are updated.\n * It encapsulates the subscription and cleanup logic, providing a robust and memory-safe\n * way to handle reactive side-effects.\n *\n * A key feature is its lifecycle management: an `EffectSignal` **must** be destroyed when no longer\n * needed to prevent memory leaks and stop the effect from running unnecessarily.\n *\n * @param config The configuration for the effect.\n * @returns An object with a `destroy` method to stop the effect.\n *\n * @example\n * // --- Create dependency signals ---\n * const counter = createStateSignal({ initialValue: 0, name: 'counter' });\n * const user = createStateSignal({ initialValue: 'guest', name: 'user' });\n *\n * // --- Create an effect ---\n * const analyticsEffect = createEffect({\n * deps: [counter, user],\n * run: () => {\n * console.log(`Analytics: User '${user.get()}' clicked ${counter.get()} times.`);\n * },\n * runImmediately: true, // Optional: run once on creation\n * });\n * // Immediately logs: \"Analytics: User 'guest' clicked 0 times.\"\n *\n * // --- Trigger the effect by updating a dependency ---\n * counter.set(1);\n * // After a macrotask, logs: \"Analytics: User 'guest' clicked 1 times.\"\n *\n * // --- IMPORTANT: Clean up when the effect is no longer needed ---\n * analyticsEffect.destroy();\n *\n * // Further updates will not trigger the effect.\n * counter.set(2); // Nothing is logged.\n */\nexport function createEffect(config: EffectSignalConfig): EffectSignal {\n return new EffectSignal(config);\n}\n", "import {createDebouncer} from '@alwatr/debounce';\n\nimport {StateSignal} from '../core/state-signal.js';\nimport {createComputedSignal} from '../creators/computed.js';\n\nimport type {ComputedSignal} from '../core/computed-signal.js';\nimport type {IReadonlySignal, DebounceSignalConfig} from '../type.js';\n\n/**\n * Creates a new computed signal that debounces updates from a source signal.\n *\n * The returned signal is a `ComputedSignal`, meaning it is read-only and its value is\n * derived from the source. It only updates its value after a specified period of\n * inactivity from the source signal.\n *\n * This operator is essential for handling high-frequency events, such as user input\n * in a search box, resizing a window, or any other event that fires rapidly.\n * By debouncing, you can ensure that expensive operations (like API calls or heavy\n * computations) are only executed once the events have settled.\n *\n * @template T The type of the signal's value.\n *\n * @param {IReadonlySignal<T>} sourceSignal The original signal to debounce.\n * It can be a `StateSignal`, `ComputedSignal`, or any signal implementing `IReadonlySignal`.\n * @param {DebounceSignalConfig} config Configuration object for the debouncer,\n * including `delay`, `leading`, and `trailing` options from `@alwatr/debounce`.\n *\n * @returns {IComputedSignal<T>} A new, read-only computed signal that emits debounced values.\n * Crucially, you **must** call `.destroy()` on this signal when it's no longer\n * needed to prevent memory leaks by cleaning up internal subscriptions and timers.\n *\n * @example\n * ```typescript\n * // Create a source signal for user input.\n * const searchInput = createStateSignal({\n * name: 'search-input',\n * initialValue: '',\n * });\n *\n * // Create a debounced signal that waits 300ms after the user stops typing.\n * const debouncedSearch = createDebouncedSignal(searchInput, { delay: 300 });\n *\n * // Use an effect to react to the debounced value.\n * createEffect({\n * deps: [debouncedSearch],\n * run: () => {\n * if (debouncedSearch.get()) {\n * console.log(`🚀 Sending API request for: \"${debouncedSearch.get()}\"`);\n * }\n * },\n * });\n *\n * searchInput.set('Alwatr');\n * searchInput.set('Alwatr Signal');\n * // (after 300ms of inactivity)\n * // Logs: \"🚀 Sending API request for: \"Alwatr Signal\"\"\n *\n * // IMPORTANT: Clean up when the component unmounts.\n * // debouncedSearch.destroy();\n * ```\n */\nexport function createDebouncedSignal<T>(sourceSignal: IReadonlySignal<T>, config: DebounceSignalConfig): ComputedSignal<T> {\n const name = config.name ?? `${sourceSignal.name}-debounced`;\n\n const internalSignal = new StateSignal<T>({\n name: `${name}-internal`,\n initialValue: sourceSignal.get(),\n });\n\n const debouncer = createDebouncer({\n ...config,\n func: (value: T): void => {\n internalSignal.set(value);\n },\n });\n\n const subscription = sourceSignal.subscribe((value) => debouncer.trigger(value), {receivePrevious: false});\n\n return createComputedSignal({\n name: name,\n deps: [internalSignal],\n get: () => internalSignal.get(),\n onDestroy: () => {\n if (internalSignal.isDestroyed) return;\n subscription.unsubscribe();\n debouncer.cancel();\n internalSignal.destroy();\n config.onDestroy?.();\n config = null as unknown as DebounceSignalConfig;\n },\n });\n}\n"],
|
|
5
|
+
"mappings": ";;AAUO,IAAe,WAAf,KAA6B,CAmClC,YAAsB,QAAuB,CAAvB,qBA9BtB,KAAgB,KAAO,KAAK,QAAQ,KAYpC,KAAmB,WAA6B,CAAC,EAMjD,KAAQ,cAAgB,KAYsB,CAJ9C,IAAW,aA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AAI,eAAe,YAAa,OAChC,aAAa,YAAY,EACzB,UAAU,OAAO,EACjB,eAAe,QAAQ,EACvB,OAAO,YAAY,EACnB,OAAS,IACX,CACF,CAAC,CACH",
|
|
6
6
|
"names": ["delay", "createLogger", "createLogger", "delay", "delay", "createLogger", "createLogger", "delay", "delay", "createLogger"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/signal",
|
|
3
3
|
"description": "Alwatr Signal is a powerful, lightweight, and modern reactive programming library. It is inspired by the best concepts from major reactive libraries but engineered to be faster and more efficient than all of them. It provides a robust and elegant way to manage application state through a system of signals, offering fine-grained reactivity, predictability, and excellent performance.",
|
|
4
|
-
"version": "6.0.
|
|
4
|
+
"version": "6.0.2",
|
|
5
5
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
|
|
6
6
|
"bugs": "https://github.com/Alwatr/flux/issues",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@alwatr/debounce": "^1.1.
|
|
9
|
-
"@alwatr/delay": "^6.0.
|
|
10
|
-
"@alwatr/logger": "^6.0.
|
|
8
|
+
"@alwatr/debounce": "^1.1.6",
|
|
9
|
+
"@alwatr/delay": "^6.0.8",
|
|
10
|
+
"@alwatr/logger": "^6.0.5"
|
|
11
11
|
},
|
|
12
12
|
"devDependencies": {
|
|
13
|
-
"@alwatr/nano-build": "^6.
|
|
14
|
-
"@alwatr/prettier-config": "^5.0.
|
|
15
|
-
"@alwatr/tsconfig-base": "^6.0.
|
|
16
|
-
"@alwatr/type-helper": "^6.1.
|
|
13
|
+
"@alwatr/nano-build": "^6.3.1",
|
|
14
|
+
"@alwatr/prettier-config": "^5.0.4",
|
|
15
|
+
"@alwatr/tsconfig-base": "^6.0.2",
|
|
16
|
+
"@alwatr/type-helper": "^6.1.1",
|
|
17
17
|
"@jest/globals": "^30.1.2",
|
|
18
18
|
"@types/node": "^22.18.6",
|
|
19
19
|
"jest": "^30.1.3",
|
|
@@ -66,7 +66,8 @@
|
|
|
66
66
|
"watch:es": "yarn run build:es --watch",
|
|
67
67
|
"watch:ts": "yarn run build:ts --watch --preserveWatchOutput"
|
|
68
68
|
},
|
|
69
|
+
"sideEffects": false,
|
|
69
70
|
"type": "module",
|
|
70
71
|
"types": "./dist/main.d.ts",
|
|
71
|
-
"gitHead": "
|
|
72
|
+
"gitHead": "2737f7356db922ed1985d0779f0503fdb09996a4"
|
|
72
73
|
}
|