@zajno/common 2.8.1 → 2.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +2 -2
  2. package/cjs/functions/{throttle.js → debounce.js} +8 -8
  3. package/cjs/functions/{throttle.js.map → debounce.js.map} +1 -1
  4. package/cjs/functions/index.js +1 -1
  5. package/cjs/lazy/lazy.js +8 -0
  6. package/cjs/lazy/lazy.js.map +1 -1
  7. package/cjs/lazy/promise.js +118 -89
  8. package/cjs/lazy/promise.js.map +1 -1
  9. package/cjs/observing/debouncedEvent.js +20 -0
  10. package/cjs/observing/{throttledEvent.js.map → debouncedEvent.js.map} +1 -1
  11. package/cjs/structures/promiseCache.js +2 -2
  12. package/esm/functions/{throttle.js → debounce.js} +5 -5
  13. package/esm/functions/{throttle.js.map → debounce.js.map} +1 -1
  14. package/esm/functions/index.js +1 -1
  15. package/esm/lazy/lazy.js +8 -0
  16. package/esm/lazy/lazy.js.map +1 -1
  17. package/esm/lazy/promise.js +118 -89
  18. package/esm/lazy/promise.js.map +1 -1
  19. package/esm/observing/debouncedEvent.js +16 -0
  20. package/esm/observing/{throttledEvent.js.map → debouncedEvent.js.map} +1 -1
  21. package/esm/structures/promiseCache.js +2 -2
  22. package/package.json +1 -1
  23. package/tsconfig.cjs.tsbuildinfo +1 -1
  24. package/tsconfig.esm.tsbuildinfo +1 -1
  25. package/tsconfig.types.tsbuildinfo +1 -1
  26. package/types/functions/{throttle.d.ts → debounce.d.ts} +2 -2
  27. package/types/functions/index.d.ts +1 -1
  28. package/types/lazy/lazy.d.ts +8 -0
  29. package/types/lazy/promise.d.ts +39 -30
  30. package/types/lazy/types.d.ts +63 -54
  31. package/types/observing/{throttledEvent.d.ts → debouncedEvent.d.ts} +2 -2
  32. package/cjs/observing/throttledEvent.js +0 -20
  33. package/esm/observing/throttledEvent.js +0 -16
@@ -2,6 +2,11 @@ import { type IDisposable } from '../functions/disposer.js';
2
2
  import type { IResettableModel } from '../models/types.js';
3
3
  import type { IExpireTracker } from '../structures/expire.js';
4
4
  import type { IControllableLazyPromise, ILazyPromiseExtension, LazyFactory } from './types.js';
5
+ /**
6
+ * Asynchronous lazy-loading container that initializes via a promise-based factory.
7
+ * Handles concurrent operations with "latest wins" semantics: multiple refreshes are automatically
8
+ * coordinated so all awaiting promises receive the final value. Supports extensions for custom behavior.
9
+ */
5
10
  export declare class LazyPromise<T, TInitial extends T | undefined = undefined> implements IControllableLazyPromise<T, TInitial>, IDisposable, IResettableModel {
6
11
  private _factory;
7
12
  private readonly _initial;
@@ -9,68 +14,72 @@ export declare class LazyPromise<T, TInitial extends T | undefined = undefined>
9
14
  private _isLoading;
10
15
  private _promise;
11
16
  private _expireTracker;
12
- private _lastRefreshingPromise;
17
+ private _activeFactoryPromise;
13
18
  private _error;
19
+ private _ownDisposer?;
14
20
  constructor(factory: LazyFactory<T>, initial?: TInitial);
15
21
  get isLoading(): boolean | null;
16
22
  get hasValue(): boolean;
17
23
  get error(): string | null;
18
24
  get promise(): Promise<T>;
19
25
  get value(): T | TInitial;
20
- /** does not calls factory */
26
+ /** Returns current value without triggering loading. */
21
27
  get currentValue(): T | TInitial;
28
+ /** Configures automatic cache expiration using an expire tracker. */
22
29
  withExpire(tracker: IExpireTracker | undefined): this;
23
30
  /**
24
- * Extends this instance with additional functionality by applying extensions in place.
31
+ * Extends this instance with additional functionality via in-place mutation.
25
32
  *
26
33
  * **Capabilities:**
27
- * - `overrideFactory`: Wrap the factory function (logging, retry, caching, etc.)
28
- * - `extendShape`: Add custom properties/methods to the instance
34
+ * - `overrideFactory`: Wrap the factory (logging, retry, caching, etc.)
35
+ * - `extendShape`: Add custom properties/methods
36
+ * - `dispose`: Cleanup resources when disposed
29
37
  *
30
38
  * **Type Safety:**
31
39
  * - Use `ILazyPromiseExtension<any>` for universal extensions
32
- * - Use `ILazyPromiseExtension<ConcreteType>` for type-specific extensions (e.g., number-only)
40
+ * - Use `ILazyPromiseExtension<ConcreteType>` for type-specific extensions
33
41
  *
34
- * **Note:** Extensions mutate the instance and can be chained. Subclasses preserve their type.
42
+ * **Note:** Extensions mutate the instance and can be chained.
35
43
  *
36
- * @param extension - Configuration with factory override and/or shape extensions
37
- * @returns The same instance (this) with applied extensions
44
+ * @param extension - Extension configuration
45
+ * @returns The same instance with applied extensions
38
46
  *
39
47
  * @example
40
48
  * ```typescript
41
- * // Universal logging extension
42
49
  * const logged = lazy.extend({
43
50
  * overrideFactory: (factory) => async (refreshing) => {
44
51
  * console.log('Loading...');
45
52
  * return await factory(refreshing);
46
53
  * }
47
54
  * });
48
- *
49
- * // Type-specific extension with custom methods
50
- * const enhanced = lazyNumber.extend<{ double: () => number | undefined }>({
51
- * extendShape: (instance) => Object.assign(instance, {
52
- * double: () => instance.currentValue !== undefined
53
- * ? instance.currentValue * 2
54
- * : undefined
55
- * })
56
- * });
57
- *
58
- * // Chaining multiple extensions
59
- * const composed = lazy
60
- * .extend(cacheExtension)
61
- * .extend(loggingExtension);
62
55
  * ```
63
56
  */
64
57
  extend<TExtShape extends object = object>(extension: Partial<ILazyPromiseExtension<any, TExtShape>>): object extends TExtShape ? this : this & TExtShape;
65
- protected ensureInstanceLoading(): void;
66
- protected doLoad(): void;
67
- protected onResolved(res: T): T;
68
- protected onRejected(e: unknown): T;
58
+ /**
59
+ * Manually sets the value and marks loading as complete.
60
+ * Clears any errors and restarts the expiration tracker if configured.
61
+ *
62
+ * @param res - The value to set
63
+ * @returns The value that was set
64
+ */
69
65
  setInstance(res: T): T;
70
- protected setError(err: unknown): void;
71
- protected clearError(): void;
66
+ /**
67
+ * Re-executes the factory to get fresh data.
68
+ *
69
+ * **Concurrency handling:**
70
+ * - Supersedes any in-progress load or refresh
71
+ * - Multiple concurrent refreshes: latest wins
72
+ * - All awaiting promises receive the final refreshed value
73
+ *
74
+ * @returns Promise resolving to the refreshed value
75
+ */
72
76
  refresh(): Promise<T>;
73
77
  reset(): void;
74
78
  dispose(): void;
79
+ protected ensureInstanceLoading(): void;
80
+ private startLoading;
81
+ protected onRejected(e: unknown): T | TInitial;
82
+ protected setError(err: unknown): void;
83
+ protected clearError(): void;
75
84
  protected parseError(err: unknown): string;
76
85
  }
@@ -1,58 +1,54 @@
1
1
  import type { IResettableModel } from '../models/types.js';
2
- /** Represents a lazily loaded value. */
2
+ /** Represents a lazily loaded value that initializes on first access. */
3
3
  export interface ILazy<T> {
4
- /** Returns current value. If not loaded, loading is triggered. */
4
+ /** Returns current value, triggering loading if not yet loaded. */
5
5
  readonly value: T;
6
- /** Returns whether has current value. Accessing this property does not trigger loading. */
6
+ /** Returns true if value has been loaded. Does not trigger loading. */
7
7
  readonly hasValue: boolean;
8
- /** Returns current value or undefined if not present. Accessing this property does not trigger loading. */
8
+ /** Returns current value or undefined if not loaded. Does not trigger loading. */
9
9
  readonly currentValue: T | undefined;
10
- /** Returns error message if loading failed, null otherwise. Accessing this property does not trigger loading. */
10
+ /** Returns error message if loading failed, null otherwise. Does not trigger loading. */
11
11
  readonly error: string | null;
12
12
  }
13
- /** Represents a lazily asynchronously loaded value. */
13
+ /** Represents a lazily asynchronously loaded value with promise-based access. */
14
14
  export interface ILazyPromise<T, TInitial extends T | undefined = undefined> extends ILazy<T | TInitial> {
15
15
  /**
16
- * Returns true if loading is in progress, false if loading is completed, null if loading was not initiated.
17
- *
18
- * Accessing this property does not trigger loading.
16
+ * Returns loading state: true (loading), false (loaded), null (not started).
17
+ * Does not trigger loading.
19
18
  */
20
19
  readonly isLoading: boolean | null;
21
- /** Returns the promise for the current value. If not loaded, accessing this property triggers loading. */
20
+ /** Returns the promise for the value, triggering loading if not started. */
22
21
  readonly promise: Promise<T>;
23
22
  /**
24
- * Refreshes the value by re-executing the factory function.
25
- * The factory will be called with `refreshing: true` parameter.
26
- * If multiple refreshes are called concurrently, only the last one will update the instance.
23
+ * Re-executes the factory to get fresh data. If concurrent refreshes occur, the latest wins.
24
+ * All awaiting promises will resolve to the final refreshed value.
27
25
  *
28
- * **⚠️ Use sparingly:** This method should only be called when you explicitly need fresh data.
29
- * Over-using refresh defeats the purpose of lazy loading and caching.
26
+ * **⚠️ Use sparingly:** Only refresh when explicitly needed for fresh data.
27
+ * Over-use defeats lazy loading and caching benefits.
30
28
  *
31
- * **Common valid use cases:**
32
- * - User-initiated refresh action (pull-to-refresh, refresh button)
33
- * - Cache invalidation after a mutation (e.g., after updating data on server)
34
- * - Time-based refresh with proper debouncing/throttling
35
- * - Recovery from an error state
29
+ * **Valid use cases:**
30
+ * - User-initiated refresh (pull-to-refresh, refresh button)
31
+ * - Cache invalidation after mutation
32
+ * - Time-based refresh with throttling
33
+ * - Error recovery
36
34
  *
37
- * **Anti-patterns to avoid:**
38
- * - Calling refresh on every render or component mount
39
- * - Using refresh instead of proper cache expiration (use `withExpire` instead)
40
- * - Calling refresh in loops or high-frequency events without debouncing
41
- * - Using refresh as a substitute for real-time updates (consider WebSockets/polling instead)
35
+ * **Avoid:**
36
+ * - Refreshing on every render/mount
37
+ * - Using instead of cache expiration (use `withExpire`)
38
+ * - Calling in loops or high-frequency events without debouncing
42
39
  *
43
- * @returns Promise that resolves to the refreshed value, or current value if refresh fails.
40
+ * @returns Promise resolving to the refreshed value
44
41
  */
45
42
  refresh(): Promise<T>;
46
43
  }
47
44
  /**
48
- * Represents a controllable lazy promise with manual state management capabilities.
49
- * Extends ILazyPromise and IResettableModel with methods to manually set values and reset state.
50
- * Use this interface in extensions that need direct control over the lazy value lifecycle.
45
+ * Controllable lazy promise with manual state management.
46
+ * Extends ILazyPromise with methods to manually set values and reset state.
51
47
  */
52
48
  export interface IControllableLazyPromise<T, TInitial extends T | undefined = undefined> extends ILazyPromise<T, TInitial>, IResettableModel {
53
49
  /**
54
- * Manually sets the instance value and marks loading as complete.
55
- * Useful for cache synchronization and manual state management.
50
+ * Manually sets the value and marks loading as complete.
51
+ * Useful for cache synchronization and manual state updates.
56
52
  *
57
53
  * @param value - The value to set
58
54
  * @returns The value that was set
@@ -60,28 +56,20 @@ export interface IControllableLazyPromise<T, TInitial extends T | undefined = un
60
56
  setInstance(value: T): T;
61
57
  }
62
58
  /**
63
- * Factory function to retrieve the fresh value.
59
+ * Factory function that retrieves the value for LazyPromise.
64
60
  *
65
- * @param refreshing - indicates whether manual refresh is requested
66
- * */
61
+ * @param refreshing - True when called via refresh(), false on initial load
62
+ */
67
63
  export type LazyFactory<T> = (refreshing?: boolean) => Promise<T>;
68
64
  /**
69
- * Extension for LazyPromise instances.
65
+ * Extension for LazyPromise instances, enabling factory wrapping and instance augmentation.
70
66
  *
71
- * @template T - The type of value the extension is compatible with. Use `any` for universal extensions.
72
- * @template TExtShape - Additional shape added to the extended instance (properties/methods).
67
+ * @template T - Value type the extension is compatible with (use `any` for universal extensions)
68
+ * @template TExtShape - Additional properties/methods added to the instance
73
69
  *
74
70
  * @example
75
71
  * ```typescript
76
- * // Type-specific extension (only for numbers)
77
- * const doublingExtension: ILazyPromiseExtension<number> = {
78
- * overrideFactory: (original) => async (refreshing) => {
79
- * const result = await original(refreshing);
80
- * return result * 2;
81
- * }
82
- * };
83
- *
84
- * // Universal extension (works with any type)
72
+ * // Universal logging extension
85
73
  * const loggingExtension: ILazyPromiseExtension<any> = {
86
74
  * overrideFactory: (original) => async (refreshing) => {
87
75
  * console.log('Loading...');
@@ -92,19 +80,40 @@ export type LazyFactory<T> = (refreshing?: boolean) => Promise<T>;
92
80
  */
93
81
  export interface ILazyPromiseExtension<T = any, TExtShape extends object = object> {
94
82
  /**
95
- * Override or wrap the factory function.
83
+ * Augment the instance with additional properties/methods.
84
+ * Receives IControllableLazyPromise with setInstance() and reset() for manual control.
85
+ *
86
+ * @param previous - The controllable LazyPromise instance
87
+ * @returns The instance with additional shape
88
+ */
89
+ extendShape?: <TInitial extends T | undefined = undefined>(previous: IControllableLazyPromise<T, TInitial>) => IControllableLazyPromise<T, TInitial> & TExtShape;
90
+ /**
91
+ * Wrap or replace the factory function.
92
+ *
96
93
  * @param original - The original factory function
97
94
  * @param target - The LazyPromise instance being extended
98
95
  * @returns A new factory function
99
96
  */
100
- overrideFactory?: <TInitial extends T | undefined = undefined>(original: LazyFactory<T>, target: ILazyPromise<T, TInitial>) => LazyFactory<T>;
97
+ overrideFactory?: <TInitial extends T | undefined = undefined>(original: LazyFactory<T>, target: ILazyPromise<T, TInitial> & TExtShape) => LazyFactory<T>;
101
98
  /**
102
- * Extend the instance with additional properties/methods.
103
- * Receives IControllableLazyPromise which includes setInstance() and reset() methods
104
- * for manual state management and cache synchronization.
99
+ * Cleanup function called when the LazyPromise is disposed.
100
+ * Use for cleaning up resources (timers, subscriptions, listeners).
101
+ * Executes in reverse order: newest extension first, oldest last.
105
102
  *
106
- * @param previous - The controllable LazyPromise instance to extend
107
- * @returns The instance with additional shape
103
+ * @param instance - The extended LazyPromise instance being disposed
104
+ *
105
+ * @example
106
+ * ```typescript
107
+ * const intervalExtension: ILazyPromiseExtension<any, { stopTimer: () => void }> = {
108
+ * extendShape: (instance) => {
109
+ * let intervalId: NodeJS.Timeout | null = null;
110
+ * return Object.assign(instance, {
111
+ * stopTimer: () => { if (intervalId) clearInterval(intervalId); }
112
+ * });
113
+ * },
114
+ * dispose: (instance) => instance.stopTimer()
115
+ * };
116
+ * ```
108
117
  */
109
- extendShape?: <TInitial extends T | undefined = undefined>(previous: IControllableLazyPromise<T, TInitial>) => IControllableLazyPromise<T, TInitial> & TExtShape;
118
+ dispose?: (instance: ILazyPromise<T, any> & TExtShape) => void;
110
119
  }
@@ -1,6 +1,6 @@
1
1
  import { Event } from './event.js';
2
- export declare class ThrottledEvent extends Event {
3
- private readonly _throttle;
2
+ export declare class DebouncedEvent extends Event {
3
+ private readonly _debounce;
4
4
  setTimeout(timeout: number): this;
5
5
  trigger(): void;
6
6
  triggerAsync(): Promise<Error[]>;
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ThrottledEvent = void 0;
4
- const event_js_1 = require("./event.js");
5
- const throttle_js_1 = require("../functions/throttle.js");
6
- class ThrottledEvent extends event_js_1.Event {
7
- _throttle = new throttle_js_1.ThrottleAction(100);
8
- setTimeout(timeout) {
9
- this._throttle.timeout = timeout;
10
- return this;
11
- }
12
- trigger() {
13
- this._throttle.tryRun(() => super.trigger());
14
- }
15
- triggerAsync() {
16
- throw new Error('ThrottledEvent does not support triggerAsync');
17
- }
18
- }
19
- exports.ThrottledEvent = ThrottledEvent;
20
- //# sourceMappingURL=throttledEvent.js.map
@@ -1,16 +0,0 @@
1
- import { Event } from './event.js';
2
- import { ThrottleAction } from '../functions/throttle.js';
3
- export class ThrottledEvent extends Event {
4
- _throttle = new ThrottleAction(100);
5
- setTimeout(timeout) {
6
- this._throttle.timeout = timeout;
7
- return this;
8
- }
9
- trigger() {
10
- this._throttle.tryRun(() => super.trigger());
11
- }
12
- triggerAsync() {
13
- throw new Error('ThrottledEvent does not support triggerAsync');
14
- }
15
- }
16
- //# sourceMappingURL=throttledEvent.js.map