@asaidimu/utils-store 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.mts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { EventBus } from '@asaidimu/events';
2
- import { SimplePersistence as SimplePersistence$1 } from '@asaidimu/utils-persistence';
3
2
 
4
3
  interface SimplePersistence<T> {
5
4
  /**
@@ -387,59 +386,116 @@ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
387
386
  * Defines the lifecycle scope of an artifact.
388
387
  */
389
388
  declare enum ArtifactScope {
390
- Singleton = "singleton",// Created once, cached, tracks dependencies
389
+ /**
390
+ * Created once and cached.
391
+ * The container tracks its dependencies and rebuilds it if they change.
392
+ */
393
+ Singleton = "singleton",
394
+ /**
395
+ * Created every time it is resolved.
396
+ * Dependencies are NOT tracked, and it is never cached.
397
+ */
391
398
  Transient = "transient"
392
399
  }
393
400
  /**
394
- * Dependency resolution context provided to the use() callback.
401
+ * Dependency resolution context provided to the `use()` callback.
402
+ * Used to declare dependencies on other artifacts or state slices.
395
403
  */
396
404
  interface UseDependencyContext<TState extends object> {
397
405
  /**
398
406
  * Resolve another artifact.
399
- * This records a dependency between the caller and the requested artifact.
407
+ * This records a dependency: if the target artifact is invalidated, the caller will be too.
408
+ *
409
+ * @param key The key of the artifact to resolve.
400
410
  */
401
- resolve<TArtifact>(key: string): Promise<TArtifact>;
411
+ resolve<TArtifact>(key: string): Promise<ResolvedArtifact<TArtifact>>;
402
412
  /**
403
413
  * Select a slice of state.
404
- * This records a dependency between the artifact and the specific state paths.
414
+ * This records a dependency: if the selected state changes, the artifact will be invalidated.
415
+ *
416
+ * @param selector A function that selects a part of the global state.
405
417
  */
406
418
  select<S>(selector: (state: TState) => S): S;
407
419
  }
408
420
  /**
409
421
  * The context object provided to an artifact's factory function.
422
+ * Provides tools for state access, dependency injection, and lifecycle management.
410
423
  */
411
424
  interface ArtifactFactoryContext<TState extends object> {
412
425
  /**
413
426
  * Get the current state snapshot immediately.
414
- * WARNING: Calling this does NOT create a subscription.
415
- * Use ctx.use(c => c.select(...)) for reactive behavior.
427
+ * **Note:** Calling this does NOT create a subscription. Use `ctx.use(c => c.select(...))` for reactive behavior.
416
428
  */
417
429
  state(): TState;
418
430
  /**
419
- * The existing instance if being re-evaluated.
420
- * Useful for preserving internal state (like connections) during hot-swaps.
431
+ * The existing instance if the artifact is being re-evaluated/rebuilt.
432
+ * Useful for preserving internal state (like active connections) during hot-swaps.
421
433
  */
422
434
  current?: unknown;
423
435
  /**
424
436
  * Execute a callback to capture dependencies.
425
- * All resolve() and select() calls inside this callback are recorded
426
- * to build the dependency graph for this artifact.
437
+ * All `resolve()` and `select()` calls inside this callback are recorded
438
+ * to build the reactive dependency graph.
439
+ *
440
+ * @param callback The function where dependencies are declared.
427
441
  */
428
442
  use<K>(callback: (ctx: UseDependencyContext<TState>) => K | Promise<K>): Promise<K>;
443
+ /**
444
+ * Register a cleanup function to be called when the artifact is disposed or rebuilt.
445
+ * Multiple cleanup functions can be registered; they will be called in reverse order (LIFO).
446
+ *
447
+ * @param cleanup A function to execute during teardown.
448
+ */
449
+ onCleanup(cleanup: ArtifactCleanup): void;
450
+ /**
451
+ * Hot-swap the artifact instance without triggering a full teardown.
452
+ *
453
+ * **Behavior:**
454
+ * 1. Updates the internal instance **synchronously** (immediate consistency).
455
+ * 2. Invalidates downstream dependents **asynchronously** (graph consistency).
456
+ * 3. Notifies listeners (UI updates) only after the graph is consistent.
457
+ *
458
+ * @param value The new instance value to set.
459
+ *
460
+ * @example
461
+ * // Updating a WebSocket connection without losing the wrapping artifact
462
+ * factory: async (ctx) => {
463
+ * const ws = new WebSocket(url);
464
+ * ws.onmessage = (msg) => ctx.yield(JSON.parse(msg.data));
465
+ * return ws; // Initial value
466
+ * }
467
+ */
468
+ yield(value: unknown): void;
429
469
  }
430
470
  /**
431
- * Cleanup function type.
471
+ * A function to clean up resources (close sockets, remove listeners, etc.).
432
472
  */
433
473
  type ArtifactCleanup = () => void | Promise<void>;
434
474
  /**
435
- * Represents the output of an artifact factory:
436
- * either the artifact instance itself, or a tuple [instance, cleanup].
475
+ * The result of resolving an artifact.
476
+ * Wraps the instance with metadata, error state, and control methods.
437
477
  */
438
- type ArtifactResult<T> = T | [T, ArtifactCleanup];
478
+ interface ResolvedArtifact<TArtifact> {
479
+ /** The resolved artifact instance. */
480
+ instance: TArtifact;
481
+ /** A function that runs all registered cleanups for this artifact. */
482
+ cleanup?: ArtifactCleanup;
483
+ /** Any error that occurred during creation. */
484
+ error?: any;
485
+ /**
486
+ * Manually invalidate this artifact.
487
+ * @param replace If `true`, forces an immediate rebuild (Eager). If `false`, marks as stale (Lazy).
488
+ */
489
+ invalidate(replace?: boolean): Promise<void>;
490
+ }
439
491
  /**
440
492
  * A factory function that creates an instance of an artifact.
441
493
  */
442
- type ArtifactFactory<TState extends object, TArtifact> = (context: ArtifactFactoryContext<TState>) => ArtifactResult<TArtifact> | Promise<ArtifactResult<TArtifact>>;
494
+ type ArtifactFactory<TState extends object, TArtifact> = (context: ArtifactFactoryContext<TState>) => TArtifact | Promise<TArtifact>;
495
+ /**
496
+ * A reactive dependency injection container.
497
+ * Manages the lifecycle, caching, and dependency graph of application artifacts.
498
+ */
443
499
  declare class ArtifactContainer<TState extends object> {
444
500
  private readonly artifacts;
445
501
  private readonly resolvingStack;
@@ -447,15 +503,36 @@ declare class ArtifactContainer<TState extends object> {
447
503
  private readonly getState;
448
504
  private readonly subscribe;
449
505
  /**
450
- * @param getState Function to retrieve current state snapshot
451
- * @param subscribe Function to subscribe to path changes. Must return an unsubscribe function.
506
+ * @param props Interface to the external state store (e.g., Zustand, Redux).
452
507
  */
453
508
  constructor(props: Pick<DataStore<TState>, "watch" | "get">);
454
- subscribeToArtifact(key: string, callback: () => void): () => void;
455
- get(key: string): any | undefined;
456
- private notifyListeners;
457
509
  /**
458
- * Registers an artifact.
510
+ * Watch an artifact for changes and retrieve its current state.
511
+ *
512
+ * @param id The artifact key to watch.
513
+ * @returns An object containing the ID, a getter, and a subscribe method.
514
+ *
515
+ * @example
516
+ * const watcher = container.watch("current-user");
517
+ * const unsub = watcher.subscribe(() => {
518
+ * const user = watcher.get()?.instance;
519
+ * console.log("User updated:", user);
520
+ * });
521
+ */
522
+ watch<TArtifact>(id: string): {
523
+ id: string;
524
+ get(): ResolvedArtifact<TArtifact> | null;
525
+ subscribe(callback: () => void): () => void;
526
+ };
527
+ /**
528
+ * Direct sync access to an artifact instance.
529
+ * Use this sparingly; prefer `resolve()` or `watch()`.
530
+ */
531
+ get(id: string): any | undefined;
532
+ /**
533
+ * Registers a new artifact factory.
534
+ *
535
+ * @param options Configuration for the artifact.
459
536
  * @returns A function to unregister the artifact.
460
537
  */
461
538
  register<TArtifact>(options: {
@@ -464,33 +541,54 @@ declare class ArtifactContainer<TState extends object> {
464
541
  scope?: ArtifactScope;
465
542
  lazy?: boolean;
466
543
  }): () => void;
544
+ /**
545
+ * Unregisters an artifact and cleans up its resources.
546
+ */
467
547
  unregister(key: string): Promise<void>;
468
548
  /**
469
- * Resolves an artifact instance.
549
+ * Resolves an artifact, creating it if necessary.
550
+ * Handles dependency tracking, caching, and error states.
551
+ *
552
+ * @param key The artifact identifier.
470
553
  */
471
- resolve<TArtifact>(key: string): Promise<TArtifact>;
554
+ resolve<TArtifact>(key: string): Promise<ResolvedArtifact<TArtifact>>;
472
555
  /**
473
- * Internal: Executes the factory and captures dependencies into provided Sets.
556
+ * Helper to wrap a definition into the standard public return type.
557
+ */
558
+ private packageArtifact;
559
+ /**
560
+ * Executes the factory and captures dependencies.
561
+ * Contains the "Yield" implementation.
474
562
  */
475
563
  private createArtifactInstance;
476
564
  /**
477
- * Updates the dependency graph and state subscriptions after a successful creation.
565
+ * Orchestrates the invalidation and notification sequence for a yield event.
566
+ * Ensures downstream dependents are invalidated BEFORE listeners are notified.
567
+ */
568
+ private processYieldPropagation;
569
+ /**
570
+ * Updates the dependency graph structure after a successful build.
478
571
  */
479
572
  private updateGraph;
480
573
  /**
481
574
  * Cascading invalidation logic.
482
- * Destroys the artifact, destroys dependents, then rebuilds eager artifacts.
575
+ * Destroys the artifact, destroys dependents, then conditionally rebuilds.
576
+ *
577
+ * @param key The artifact key to invalidate
578
+ * @param replace If true, eagerly rebuild after invalidation. If false, respect lazy flag.
483
579
  */
484
580
  private invalidate;
485
581
  /**
486
582
  * Cleans up a specific artifact definition's instance and subscriptions.
487
- * Keeps the definition registered.
583
+ * Keeps the definition registered but clears the instance.
488
584
  */
489
585
  private disposeInstance;
490
586
  /**
491
587
  * Fully removes an artifact from the system.
492
588
  */
493
589
  private disposeArtifact;
590
+ private createCompositeCleanup;
591
+ private notifyListeners;
494
592
  private detectCycles;
495
593
  dispose(): void;
496
594
  isLoading(key: string): boolean;
@@ -824,65 +922,4 @@ declare class ActionManager<T extends object> {
824
922
  private emit;
825
923
  }
826
924
 
827
- interface ActionContext<TState extends object, TResolvedArtifacts extends object> {
828
- /**
829
- * Resolve an artifact.
830
- * This records a dependency between the caller and the requested artifact.
831
- */
832
- resolve<K extends keyof TResolvedArtifacts>(key: K): Promise<TResolvedArtifacts[K]>;
833
- state: TState;
834
- }
835
- type ActionImplementation<TState extends object, TResolvedArtifacts extends object, TArgs extends any[]> = (ctx: ActionContext<TState, TResolvedArtifacts>, ...args: TArgs) => DeepPartial<TState> | Promise<DeepPartial<TState>>;
836
- type ArtifactDefinition<TState extends Object, R> = {
837
- factory: ArtifactFactory<TState, R>;
838
- scope?: ArtifactScope;
839
- lazy?: boolean;
840
- };
841
- type ArtifactsMap<TState extends object> = Record<string, ArtifactDefinition<TState, any>>;
842
- type ExtractArtifactInstanceFromConfig<T> = T extends {
843
- factory: ArtifactFactory<any, infer I>;
844
- } ? I : never;
845
- type ExtractInstanceFromMap<TMap extends ArtifactsMap<any>, TKey extends keyof TMap> = ExtractArtifactInstanceFromConfig<TMap[TKey]>;
846
- type ResolvedArtifactsMap<TArtifactsMap extends ArtifactsMap<any>> = {
847
- [K in keyof TArtifactsMap]: ExtractInstanceFromMap<TArtifactsMap, K>;
848
- };
849
- type ActionMap<TState extends object, TArtifactsMap extends ArtifactsMap<TState>> = Record<string, ActionImplementation<TState, ResolvedArtifactsMap<TArtifactsMap>, any[]>>;
850
- /**
851
- * Bounds the actions for the resulting store hook, removing the context argument.
852
- */
853
- type BoundActions<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> = {
854
- [K in keyof TActions]: (...args: Parameters<TActions[K]> extends [ActionContext<any, any>, ...infer R] ? R : never) => Promise<TState>;
855
- };
856
- type LoadingState<TActions> = Partial<Record<keyof TActions, boolean>>;
857
- type StoreOptions<T> = ObserverOptions & {
858
- enableMetrics?: boolean;
859
- persistence?: SimplePersistence$1<T>;
860
- };
861
- interface StoreDefinition<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> {
862
- state: TState;
863
- actions: TActions;
864
- artifacts?: TArtifactsMap;
865
- loading?: LoadingState<TActions>;
866
- sync?: (args: TState) => void;
867
- blockingMiddleware?: Record<string, BlockingMiddleware<TState>>;
868
- middleware?: Record<string, Middleware<TState>>;
869
- }
870
- type StoreHook<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> = () => {
871
- store: any;
872
- observer: any;
873
- select: <S>(selector: (state: TState) => S) => S;
874
- actions: BoundActions<TState, TArtifactsMap, TActions>;
875
- /**
876
- * Reactive Artifact Resolver.
877
- * Returns [instance, isReady].
878
- */
879
- resolve: <K extends keyof TArtifactsMap>(key: K) => readonly [ExtractInstanceFromMap<TArtifactsMap, K>, true] | readonly [ExtractInstanceFromMap<TArtifactsMap, K> | undefined, false];
880
- isReady: boolean;
881
- actionTracker: any;
882
- watch: (action: keyof TActions) => boolean;
883
- state: () => TState;
884
- };
885
-
886
- declare function createStore<TState extends Record<string, unknown>, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>>(definition: StoreDefinition<TState, TArtifactsMap, TActions>, { enableMetrics, ...options }?: StoreOptions<TState>): StoreHook<TState, TArtifactsMap, TActions>;
887
-
888
- export { type ActionCompletePayload, type ActionContext, type ActionErrorPayload, type ActionImplementation, ActionManager, type ActionMap, type ActionStartPayload, type ArtifactCleanup, ArtifactContainer, type ArtifactDefinition, type ArtifactFactory, type ArtifactFactoryContext, type ArtifactResult, ArtifactScope, type ArtifactsMap, type BlockingMiddleware, type BoundActions, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, type ExtractArtifactInstanceFromConfig, type ExtractInstanceFromMap, type LoadingState, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type ResolvedArtifactsMap, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreDefinition, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreHook, type StoreMetrics, StoreObserver, type StoreOptions, type TransformMiddleware, type UseDependencyContext, createDerivePaths, createDiff, createMerge, createStore, derivePaths, diff, merge, shallowClone };
925
+ export { type ActionCompletePayload, type ActionErrorPayload, ActionManager, type ActionStartPayload, type ArtifactCleanup, ArtifactContainer, type ArtifactFactory, type ArtifactFactoryContext, ArtifactScope, type BlockingMiddleware, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type ResolvedArtifact, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreMetrics, StoreObserver, type TransformMiddleware, type UseDependencyContext, createDerivePaths, createDiff, createMerge, derivePaths, diff, merge, shallowClone };
package/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { EventBus } from '@asaidimu/events';
2
- import { SimplePersistence as SimplePersistence$1 } from '@asaidimu/utils-persistence';
3
2
 
4
3
  interface SimplePersistence<T> {
5
4
  /**
@@ -387,59 +386,116 @@ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
387
386
  * Defines the lifecycle scope of an artifact.
388
387
  */
389
388
  declare enum ArtifactScope {
390
- Singleton = "singleton",// Created once, cached, tracks dependencies
389
+ /**
390
+ * Created once and cached.
391
+ * The container tracks its dependencies and rebuilds it if they change.
392
+ */
393
+ Singleton = "singleton",
394
+ /**
395
+ * Created every time it is resolved.
396
+ * Dependencies are NOT tracked, and it is never cached.
397
+ */
391
398
  Transient = "transient"
392
399
  }
393
400
  /**
394
- * Dependency resolution context provided to the use() callback.
401
+ * Dependency resolution context provided to the `use()` callback.
402
+ * Used to declare dependencies on other artifacts or state slices.
395
403
  */
396
404
  interface UseDependencyContext<TState extends object> {
397
405
  /**
398
406
  * Resolve another artifact.
399
- * This records a dependency between the caller and the requested artifact.
407
+ * This records a dependency: if the target artifact is invalidated, the caller will be too.
408
+ *
409
+ * @param key The key of the artifact to resolve.
400
410
  */
401
- resolve<TArtifact>(key: string): Promise<TArtifact>;
411
+ resolve<TArtifact>(key: string): Promise<ResolvedArtifact<TArtifact>>;
402
412
  /**
403
413
  * Select a slice of state.
404
- * This records a dependency between the artifact and the specific state paths.
414
+ * This records a dependency: if the selected state changes, the artifact will be invalidated.
415
+ *
416
+ * @param selector A function that selects a part of the global state.
405
417
  */
406
418
  select<S>(selector: (state: TState) => S): S;
407
419
  }
408
420
  /**
409
421
  * The context object provided to an artifact's factory function.
422
+ * Provides tools for state access, dependency injection, and lifecycle management.
410
423
  */
411
424
  interface ArtifactFactoryContext<TState extends object> {
412
425
  /**
413
426
  * Get the current state snapshot immediately.
414
- * WARNING: Calling this does NOT create a subscription.
415
- * Use ctx.use(c => c.select(...)) for reactive behavior.
427
+ * **Note:** Calling this does NOT create a subscription. Use `ctx.use(c => c.select(...))` for reactive behavior.
416
428
  */
417
429
  state(): TState;
418
430
  /**
419
- * The existing instance if being re-evaluated.
420
- * Useful for preserving internal state (like connections) during hot-swaps.
431
+ * The existing instance if the artifact is being re-evaluated/rebuilt.
432
+ * Useful for preserving internal state (like active connections) during hot-swaps.
421
433
  */
422
434
  current?: unknown;
423
435
  /**
424
436
  * Execute a callback to capture dependencies.
425
- * All resolve() and select() calls inside this callback are recorded
426
- * to build the dependency graph for this artifact.
437
+ * All `resolve()` and `select()` calls inside this callback are recorded
438
+ * to build the reactive dependency graph.
439
+ *
440
+ * @param callback The function where dependencies are declared.
427
441
  */
428
442
  use<K>(callback: (ctx: UseDependencyContext<TState>) => K | Promise<K>): Promise<K>;
443
+ /**
444
+ * Register a cleanup function to be called when the artifact is disposed or rebuilt.
445
+ * Multiple cleanup functions can be registered; they will be called in reverse order (LIFO).
446
+ *
447
+ * @param cleanup A function to execute during teardown.
448
+ */
449
+ onCleanup(cleanup: ArtifactCleanup): void;
450
+ /**
451
+ * Hot-swap the artifact instance without triggering a full teardown.
452
+ *
453
+ * **Behavior:**
454
+ * 1. Updates the internal instance **synchronously** (immediate consistency).
455
+ * 2. Invalidates downstream dependents **asynchronously** (graph consistency).
456
+ * 3. Notifies listeners (UI updates) only after the graph is consistent.
457
+ *
458
+ * @param value The new instance value to set.
459
+ *
460
+ * @example
461
+ * // Updating a WebSocket connection without losing the wrapping artifact
462
+ * factory: async (ctx) => {
463
+ * const ws = new WebSocket(url);
464
+ * ws.onmessage = (msg) => ctx.yield(JSON.parse(msg.data));
465
+ * return ws; // Initial value
466
+ * }
467
+ */
468
+ yield(value: unknown): void;
429
469
  }
430
470
  /**
431
- * Cleanup function type.
471
+ * A function to clean up resources (close sockets, remove listeners, etc.).
432
472
  */
433
473
  type ArtifactCleanup = () => void | Promise<void>;
434
474
  /**
435
- * Represents the output of an artifact factory:
436
- * either the artifact instance itself, or a tuple [instance, cleanup].
475
+ * The result of resolving an artifact.
476
+ * Wraps the instance with metadata, error state, and control methods.
437
477
  */
438
- type ArtifactResult<T> = T | [T, ArtifactCleanup];
478
+ interface ResolvedArtifact<TArtifact> {
479
+ /** The resolved artifact instance. */
480
+ instance: TArtifact;
481
+ /** A function that runs all registered cleanups for this artifact. */
482
+ cleanup?: ArtifactCleanup;
483
+ /** Any error that occurred during creation. */
484
+ error?: any;
485
+ /**
486
+ * Manually invalidate this artifact.
487
+ * @param replace If `true`, forces an immediate rebuild (Eager). If `false`, marks as stale (Lazy).
488
+ */
489
+ invalidate(replace?: boolean): Promise<void>;
490
+ }
439
491
  /**
440
492
  * A factory function that creates an instance of an artifact.
441
493
  */
442
- type ArtifactFactory<TState extends object, TArtifact> = (context: ArtifactFactoryContext<TState>) => ArtifactResult<TArtifact> | Promise<ArtifactResult<TArtifact>>;
494
+ type ArtifactFactory<TState extends object, TArtifact> = (context: ArtifactFactoryContext<TState>) => TArtifact | Promise<TArtifact>;
495
+ /**
496
+ * A reactive dependency injection container.
497
+ * Manages the lifecycle, caching, and dependency graph of application artifacts.
498
+ */
443
499
  declare class ArtifactContainer<TState extends object> {
444
500
  private readonly artifacts;
445
501
  private readonly resolvingStack;
@@ -447,15 +503,36 @@ declare class ArtifactContainer<TState extends object> {
447
503
  private readonly getState;
448
504
  private readonly subscribe;
449
505
  /**
450
- * @param getState Function to retrieve current state snapshot
451
- * @param subscribe Function to subscribe to path changes. Must return an unsubscribe function.
506
+ * @param props Interface to the external state store (e.g., Zustand, Redux).
452
507
  */
453
508
  constructor(props: Pick<DataStore<TState>, "watch" | "get">);
454
- subscribeToArtifact(key: string, callback: () => void): () => void;
455
- get(key: string): any | undefined;
456
- private notifyListeners;
457
509
  /**
458
- * Registers an artifact.
510
+ * Watch an artifact for changes and retrieve its current state.
511
+ *
512
+ * @param id The artifact key to watch.
513
+ * @returns An object containing the ID, a getter, and a subscribe method.
514
+ *
515
+ * @example
516
+ * const watcher = container.watch("current-user");
517
+ * const unsub = watcher.subscribe(() => {
518
+ * const user = watcher.get()?.instance;
519
+ * console.log("User updated:", user);
520
+ * });
521
+ */
522
+ watch<TArtifact>(id: string): {
523
+ id: string;
524
+ get(): ResolvedArtifact<TArtifact> | null;
525
+ subscribe(callback: () => void): () => void;
526
+ };
527
+ /**
528
+ * Direct sync access to an artifact instance.
529
+ * Use this sparingly; prefer `resolve()` or `watch()`.
530
+ */
531
+ get(id: string): any | undefined;
532
+ /**
533
+ * Registers a new artifact factory.
534
+ *
535
+ * @param options Configuration for the artifact.
459
536
  * @returns A function to unregister the artifact.
460
537
  */
461
538
  register<TArtifact>(options: {
@@ -464,33 +541,54 @@ declare class ArtifactContainer<TState extends object> {
464
541
  scope?: ArtifactScope;
465
542
  lazy?: boolean;
466
543
  }): () => void;
544
+ /**
545
+ * Unregisters an artifact and cleans up its resources.
546
+ */
467
547
  unregister(key: string): Promise<void>;
468
548
  /**
469
- * Resolves an artifact instance.
549
+ * Resolves an artifact, creating it if necessary.
550
+ * Handles dependency tracking, caching, and error states.
551
+ *
552
+ * @param key The artifact identifier.
470
553
  */
471
- resolve<TArtifact>(key: string): Promise<TArtifact>;
554
+ resolve<TArtifact>(key: string): Promise<ResolvedArtifact<TArtifact>>;
472
555
  /**
473
- * Internal: Executes the factory and captures dependencies into provided Sets.
556
+ * Helper to wrap a definition into the standard public return type.
557
+ */
558
+ private packageArtifact;
559
+ /**
560
+ * Executes the factory and captures dependencies.
561
+ * Contains the "Yield" implementation.
474
562
  */
475
563
  private createArtifactInstance;
476
564
  /**
477
- * Updates the dependency graph and state subscriptions after a successful creation.
565
+ * Orchestrates the invalidation and notification sequence for a yield event.
566
+ * Ensures downstream dependents are invalidated BEFORE listeners are notified.
567
+ */
568
+ private processYieldPropagation;
569
+ /**
570
+ * Updates the dependency graph structure after a successful build.
478
571
  */
479
572
  private updateGraph;
480
573
  /**
481
574
  * Cascading invalidation logic.
482
- * Destroys the artifact, destroys dependents, then rebuilds eager artifacts.
575
+ * Destroys the artifact, destroys dependents, then conditionally rebuilds.
576
+ *
577
+ * @param key The artifact key to invalidate
578
+ * @param replace If true, eagerly rebuild after invalidation. If false, respect lazy flag.
483
579
  */
484
580
  private invalidate;
485
581
  /**
486
582
  * Cleans up a specific artifact definition's instance and subscriptions.
487
- * Keeps the definition registered.
583
+ * Keeps the definition registered but clears the instance.
488
584
  */
489
585
  private disposeInstance;
490
586
  /**
491
587
  * Fully removes an artifact from the system.
492
588
  */
493
589
  private disposeArtifact;
590
+ private createCompositeCleanup;
591
+ private notifyListeners;
494
592
  private detectCycles;
495
593
  dispose(): void;
496
594
  isLoading(key: string): boolean;
@@ -824,65 +922,4 @@ declare class ActionManager<T extends object> {
824
922
  private emit;
825
923
  }
826
924
 
827
- interface ActionContext<TState extends object, TResolvedArtifacts extends object> {
828
- /**
829
- * Resolve an artifact.
830
- * This records a dependency between the caller and the requested artifact.
831
- */
832
- resolve<K extends keyof TResolvedArtifacts>(key: K): Promise<TResolvedArtifacts[K]>;
833
- state: TState;
834
- }
835
- type ActionImplementation<TState extends object, TResolvedArtifacts extends object, TArgs extends any[]> = (ctx: ActionContext<TState, TResolvedArtifacts>, ...args: TArgs) => DeepPartial<TState> | Promise<DeepPartial<TState>>;
836
- type ArtifactDefinition<TState extends Object, R> = {
837
- factory: ArtifactFactory<TState, R>;
838
- scope?: ArtifactScope;
839
- lazy?: boolean;
840
- };
841
- type ArtifactsMap<TState extends object> = Record<string, ArtifactDefinition<TState, any>>;
842
- type ExtractArtifactInstanceFromConfig<T> = T extends {
843
- factory: ArtifactFactory<any, infer I>;
844
- } ? I : never;
845
- type ExtractInstanceFromMap<TMap extends ArtifactsMap<any>, TKey extends keyof TMap> = ExtractArtifactInstanceFromConfig<TMap[TKey]>;
846
- type ResolvedArtifactsMap<TArtifactsMap extends ArtifactsMap<any>> = {
847
- [K in keyof TArtifactsMap]: ExtractInstanceFromMap<TArtifactsMap, K>;
848
- };
849
- type ActionMap<TState extends object, TArtifactsMap extends ArtifactsMap<TState>> = Record<string, ActionImplementation<TState, ResolvedArtifactsMap<TArtifactsMap>, any[]>>;
850
- /**
851
- * Bounds the actions for the resulting store hook, removing the context argument.
852
- */
853
- type BoundActions<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> = {
854
- [K in keyof TActions]: (...args: Parameters<TActions[K]> extends [ActionContext<any, any>, ...infer R] ? R : never) => Promise<TState>;
855
- };
856
- type LoadingState<TActions> = Partial<Record<keyof TActions, boolean>>;
857
- type StoreOptions<T> = ObserverOptions & {
858
- enableMetrics?: boolean;
859
- persistence?: SimplePersistence$1<T>;
860
- };
861
- interface StoreDefinition<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> {
862
- state: TState;
863
- actions: TActions;
864
- artifacts?: TArtifactsMap;
865
- loading?: LoadingState<TActions>;
866
- sync?: (args: TState) => void;
867
- blockingMiddleware?: Record<string, BlockingMiddleware<TState>>;
868
- middleware?: Record<string, Middleware<TState>>;
869
- }
870
- type StoreHook<TState extends object, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>> = () => {
871
- store: any;
872
- observer: any;
873
- select: <S>(selector: (state: TState) => S) => S;
874
- actions: BoundActions<TState, TArtifactsMap, TActions>;
875
- /**
876
- * Reactive Artifact Resolver.
877
- * Returns [instance, isReady].
878
- */
879
- resolve: <K extends keyof TArtifactsMap>(key: K) => readonly [ExtractInstanceFromMap<TArtifactsMap, K>, true] | readonly [ExtractInstanceFromMap<TArtifactsMap, K> | undefined, false];
880
- isReady: boolean;
881
- actionTracker: any;
882
- watch: (action: keyof TActions) => boolean;
883
- state: () => TState;
884
- };
885
-
886
- declare function createStore<TState extends Record<string, unknown>, TArtifactsMap extends ArtifactsMap<TState>, TActions extends ActionMap<TState, TArtifactsMap>>(definition: StoreDefinition<TState, TArtifactsMap, TActions>, { enableMetrics, ...options }?: StoreOptions<TState>): StoreHook<TState, TArtifactsMap, TActions>;
887
-
888
- export { type ActionCompletePayload, type ActionContext, type ActionErrorPayload, type ActionImplementation, ActionManager, type ActionMap, type ActionStartPayload, type ArtifactCleanup, ArtifactContainer, type ArtifactDefinition, type ArtifactFactory, type ArtifactFactoryContext, type ArtifactResult, ArtifactScope, type ArtifactsMap, type BlockingMiddleware, type BoundActions, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, type ExtractArtifactInstanceFromConfig, type ExtractInstanceFromMap, type LoadingState, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type ResolvedArtifactsMap, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreDefinition, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreHook, type StoreMetrics, StoreObserver, type StoreOptions, type TransformMiddleware, type UseDependencyContext, createDerivePaths, createDiff, createMerge, createStore, derivePaths, diff, merge, shallowClone };
925
+ export { type ActionCompletePayload, type ActionErrorPayload, ActionManager, type ActionStartPayload, type ArtifactCleanup, ArtifactContainer, type ArtifactFactory, type ArtifactFactoryContext, ArtifactScope, type BlockingMiddleware, DELETE_SYMBOL, type DataStore, type DeepPartial, type DiffFunction, type MergeFunction, type Middleware, type MiddlewareConfig, type MiddlewareExecution, type ObserverOptions, type PersistenceFailedPayload, type PersistenceInitErrorPayload, type PersistenceQueueClearedPayload, type PersistenceQueuedPayload, type PersistenceRetryPayload, type PersistenceSuccessPayload, ReactiveDataStore, type ReactiveSelector, type ResolvedArtifact, type SelectorAccessedPayload, type SelectorChangedPayload, type StateDelta, type StateUpdater, type StoreAction, type StoreEvent, type StoreEvents, type StoreExecutionState, type StoreMetrics, StoreObserver, type TransformMiddleware, type UseDependencyContext, createDerivePaths, createDiff, createMerge, derivePaths, diff, merge, shallowClone };
package/index.js CHANGED
@@ -1,26 +1 @@
1
- "use strict";var e=require("uuid"),t=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,o=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,i=(e,t)=>function(){return t||(0,e[s(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(e,i,c)=>(c=null!=e?t(o(e)):{},((e,t,o,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of s(t))a.call(e,c)||c===o||r(e,c,{get:()=>t[c],enumerable:!(i=n(t,c))||i.enumerable});return e})(e&&e.__esModule?c:r(c,"default",{value:e,enumerable:!0}),e)),u=i({"node_modules/.bun/@asaidimu+events@1.1.2/node_modules/@asaidimu/events/index.js"(e,t){var r,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(i,{createEventBus:()=>c}),t.exports=(r=i,((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))a.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(i=s(t,c))||i.enumerable});return e})(n({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],n=0,s=0;const o=new Map,a=new Map;let i=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?i=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{n++,s+=t,o.set(e,(o.get(e)||0)+1)},u=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const n=performance.now();try{(a.get(t)||[]).forEach((e=>e(r)))}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-n)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(u,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?a.set(e,Array.from(r)):a.delete(e)};return i&&(i.onmessage=e=>{const{name:t,payload:r}=e.data;(a.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const n=t.get(e);return n.add(r),d(e),()=>{n.delete(r),0===n.size?(t.delete(e),a.delete(e)):d(e)}},emit:({name:t,payload:n})=>{if(e.async)return r.push({name:t,payload:n}),r.length>=e.batchSize?u():l(),void(i&&i.postMessage({name:t,payload:n}));const s=performance.now();try{(a.get(t)||[]).forEach((e=>e(n))),i&&i.postMessage({name:t,payload:n})}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-s)},getMetrics:()=>({totalEvents:n,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:o,averageEmitDuration:n>0?s/n:0}),clear:()=>{t.clear(),a.clear(),r=[],n=0,s=0,o.clear(),i&&(i.close(),i=null)}}}}}),l=i({"node_modules/.bun/react@19.2.0/node_modules/react/cjs/react.production.js"(e){var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),i=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),l=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;var p={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,y={};function g(e,t,r){this.props=e,this.context=t,this.refs=y,this.updater=r||p}function b(){}function v(e,t,r){this.props=e,this.context=t,this.refs=y,this.updater=r||p}g.prototype.isReactComponent={},g.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},g.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},b.prototype=g.prototype;var w=v.prototype=new b;w.constructor=v,m(w,g.prototype),w.isPureReactComponent=!0;var S=Array.isArray;function E(){}var _={H:null,A:null,T:null,S:null},k=Object.prototype.hasOwnProperty;function T(e,r,n){var s=n.ref;return{$$typeof:t,type:e,key:r,ref:void 0!==s?s:null,props:n}}function x(e){return"object"==typeof e&&null!==e&&e.$$typeof===t}var C=/\/+/g;function A(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(r=""+e.key,n={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,(function(e){return n[e]}))):t.toString(36);var r,n}function j(e,n,s,o,a){var i=typeof e;"undefined"!==i&&"boolean"!==i||(e=null);var c,u,l=!1;if(null===e)l=!0;else switch(i){case"bigint":case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case t:case r:l=!0;break;case d:return j((l=e._init)(e._payload),n,s,o,a)}}if(l)return a=a(e),l=""===o?"."+A(e,0):o,S(a)?(s="",null!=l&&(s=l.replace(C,"$&/")+"/"),j(a,n,s,"",(function(e){return e}))):null!=a&&(x(a)&&(c=a,u=s+(null==a.key||e&&e.key===a.key?"":(""+a.key).replace(C,"$&/")+"/")+l,a=T(c.type,u,c.props)),n.push(a)),1;l=0;var h,p=""===o?".":o+":";if(S(e))for(var m=0;m<e.length;m++)l+=j(o=e[m],n,s,i=p+A(o,m),a);else if("function"==typeof(m=null===(h=e)||"object"!=typeof h?null:"function"==typeof(h=f&&h[f]||h["@@iterator"])?h:null))for(e=m.call(e),m=0;!(o=e.next()).done;)l+=j(o=o.value,n,s,i=p+A(o,m++),a);else if("object"===i){if("function"==typeof e.then)return j(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(E,E):(e.status="pending",e.then((function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)}),(function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)}))),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(e),n,s,o,a);throw n=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===n?"object with keys {"+Object.keys(e).join(", ")+"}":n)+"). If you meant to render a collection of children, use an array instead.")}return l}function O(e,t,r){if(null==e)return e;var n=[],s=0;return j(e,n,"","",(function(e){return t.call(r,e,s++)})),n}function M(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var P="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},R={map:O,forEach:function(e,t,r){O(e,(function(){t.apply(this,arguments)}),r)},count:function(e){var t=0;return O(e,(function(){t++})),t},toArray:function(e){return O(e,(function(e){return e}))||[]},only:function(e){if(!x(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};e.Activity=h,e.Children=R,e.Component=g,e.Fragment=n,e.Profiler=o,e.PureComponent=v,e.StrictMode=s,e.Suspense=u,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return _.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var n=m({},e.props),s=e.key;if(null!=t)for(o in void 0!==t.key&&(s=""+t.key),t)!k.call(t,o)||"key"===o||"__self"===o||"__source"===o||"ref"===o&&void 0===t.ref||(n[o]=t[o]);var o=arguments.length-2;if(1===o)n.children=r;else if(1<o){for(var a=Array(o),i=0;i<o;i++)a[i]=arguments[i+2];n.children=a}return T(e.type,s,n)},e.createContext=function(e){return(e={$$typeof:i,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider=e,e.Consumer={$$typeof:a,_context:e},e},e.createElement=function(e,t,r){var n,s={},o=null;if(null!=t)for(n in void 0!==t.key&&(o=""+t.key),t)k.call(t,n)&&"key"!==n&&"__self"!==n&&"__source"!==n&&(s[n]=t[n]);var a=arguments.length-2;if(1===a)s.children=r;else if(1<a){for(var i=Array(a),c=0;c<a;c++)i[c]=arguments[c+2];s.children=i}if(e&&e.defaultProps)for(n in a=e.defaultProps)void 0===s[n]&&(s[n]=a[n]);return T(e,o,s)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=x,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:M}},e.memo=function(e,t){return{$$typeof:l,type:e,compare:void 0===t?null:t}},e.startTransition=function(e){var t=_.T,r={};_.T=r;try{var n=e(),s=_.S;null!==s&&s(r,n),"object"==typeof n&&null!==n&&"function"==typeof n.then&&n.then(E,P)}catch(e){P(e)}finally{null!==t&&null!==r.types&&(t.types=r.types),_.T=t}},e.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()},e.use=function(e){return _.H.use(e)},e.useActionState=function(e,t,r){return _.H.useActionState(e,t,r)},e.useCallback=function(e,t){return _.H.useCallback(e,t)},e.useContext=function(e){return _.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return _.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return _.H.useEffect(e,t)},e.useEffectEvent=function(e){return _.H.useEffectEvent(e)},e.useId=function(){return _.H.useId()},e.useImperativeHandle=function(e,t,r){return _.H.useImperativeHandle(e,t,r)},e.useInsertionEffect=function(e,t){return _.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return _.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return _.H.useMemo(e,t)},e.useOptimistic=function(e,t){return _.H.useOptimistic(e,t)},e.useReducer=function(e,t,r){return _.H.useReducer(e,t,r)},e.useRef=function(e){return _.H.useRef(e)},e.useState=function(e){return _.H.useState(e)},e.useSyncExternalStore=function(e,t,r){return _.H.useSyncExternalStore(e,t,r)},e.useTransition=function(){return _.H.useTransition()},e.version="19.2.0"}}),d=i({"node_modules/.bun/react@19.2.0/node_modules/react/cjs/react.development.js"(e,t){"production"!==process.env.NODE_ENV&&function(){function r(e,t){Object.defineProperty(s.prototype,e,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",t[0],t[1])}})}function n(e,t){var r=(e=(e=e.constructor)&&(e.displayName||e.name)||"ReactClass")+"."+t;q[r]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",t,e),q[r]=!0)}function s(e,t,r){this.props=e,this.context=t,this.refs=W,this.updater=r||F}function o(){}function a(e,t,r){this.props=e,this.context=t,this.refs=W,this.updater=r||F}function i(){}function c(e){return""+e}function u(e){try{c(e);var t=!1}catch(e){t=!0}if(t){var r=(t=console).error,n="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return r.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",n),c(e)}}function l(e){if(null==e)return null;if("function"==typeof e)return e.$$typeof===X?null:e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case P:return"Fragment";case $:return"Profiler";case R:return"StrictMode";case I:return"Suspense";case U:return"SuspenseList";case N:return"Activity"}if("object"==typeof e)switch("number"==typeof e.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case M:return"Portal";case D:return e.displayName||"Context";case H:return(e._context.displayName||"Context")+".Consumer";case L:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case B:return null!==(t=e.displayName||null)?t:l(e.type)||"Memo";case z:t=e._payload,e=e._init;try{return l(e(t))}catch(e){}}return null}function d(e){if(e===P)return"<>";if("object"==typeof e&&null!==e&&e.$$typeof===z)return"<...>";try{var t=l(e);return t?"<"+t+">":"<...>"}catch(e){return"<...>"}}function h(){var e=Z.A;return null===e?null:e.getOwner()}function f(){return Error("react-stack-top-frame")}function p(e){if(ee.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}function m(){var e=l(this.type);return re[e]||(re[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(e=this.props.ref)?e:null}function y(e,t,r,n,s,o){var a=r.ref;return e={$$typeof:O,type:e,key:t,props:r,_owner:n},null!==(void 0!==a?a:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:m}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:s}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:o}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function g(e){b(e)?e._store&&(e._store.validated=1):"object"==typeof e&&null!==e&&e.$$typeof===z&&("fulfilled"===e._payload.status?b(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function b(e){return"object"==typeof e&&null!==e&&e.$$typeof===O}function v(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(u(e.key),r=""+e.key,n={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,(function(e){return n[e]}))):t.toString(36);var r,n}function w(e,t,r,n,s){var o=typeof e;"undefined"!==o&&"boolean"!==o||(e=null);var a,c,l,d=!1;if(null===e)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(e.$$typeof){case O:case M:d=!0;break;case z:return w((d=e._init)(e._payload),t,r,n,s)}}if(d){s=s(d=e);var h=""===n?"."+v(d,0):n;return K(s)?(r="",null!=h&&(r=h.replace(ae,"$&/")+"/"),w(s,t,r,"",(function(e){return e}))):null!=s&&(b(s)&&(null!=s.key&&(d&&d.key===s.key||u(s.key)),a=s,c=r+(null==s.key||d&&d.key===s.key?"":(""+s.key).replace(ae,"$&/")+"/")+h,c=y(a.type,c,a.props,a._owner,a._debugStack,a._debugTask),a._store&&(c._store.validated=a._store.validated),r=c,""!==n&&null!=d&&b(d)&&null==d.key&&d._store&&!d._store.validated&&(r._store.validated=2),s=r),t.push(s)),1}if(d=0,h=""===n?".":n+":",K(e))for(var f=0;f<e.length;f++)d+=w(n=e[f],t,r,o=h+v(n,f),s);else if("function"==typeof(f=null===(l=e)||"object"!=typeof l?null:"function"==typeof(l=Q&&l[Q]||l["@@iterator"])?l:null))for(f===e.entries&&(oe||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),oe=!0),e=f.call(e),f=0;!(n=e.next()).done;)d+=w(n=n.value,t,r,o=h+v(n,f++),s);else if("object"===o){if("function"==typeof e.then)return w(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(i,i):(e.status="pending",e.then((function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)}),(function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)}))),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(e),t,r,n,s);throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.")}return d}function S(e,t,r){if(null==e)return e;var n=[],s=0;return w(e,n,"","",(function(e){return t.call(r,e,s++)})),n}function E(e){if(-1===e._status){var t=e._ioInfo;null!=t&&(t.start=t.end=performance.now());var r=(t=e._result)();if(r.then((function(t){if(0===e._status||-1===e._status){e._status=1,e._result=t;var n=e._ioInfo;null!=n&&(n.end=performance.now()),void 0===r.status&&(r.status="fulfilled",r.value=t)}}),(function(t){if(0===e._status||-1===e._status){e._status=2,e._result=t;var n=e._ioInfo;null!=n&&(n.end=performance.now()),void 0===r.status&&(r.status="rejected",r.reason=t)}})),null!=(t=e._ioInfo)){t.value=r;var n=r.displayName;"string"==typeof n&&(t.name=n)}-1===e._status&&(e._status=0,e._result=r)}if(1===e._status)return void 0===(t=e._result)&&console.error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",t),"default"in t||console.error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))",t),t.default;throw e._result}function _(){var e=Z.H;return null===e&&console.error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."),e}function k(){Z.asyncTransitions--}function T(e){if(null===ue)try{var r=("require"+Math.random()).slice(0,7);ue=(t&&t[r]).call(t,"timers").setImmediate}catch(e){ue=function(e){!1===ce&&(ce=!0,"undefined"==typeof MessageChannel&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var t=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(void 0)}}return ue(e)}function x(e){return 1<e.length&&"function"==typeof AggregateError?new AggregateError(e):e[0]}function C(e,t){t!==le-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),le=t}function A(e,t,r){var n=Z.actQueue;if(null!==n)if(0!==n.length)try{return j(n),void T((function(){return A(e,t,r)}))}catch(e){Z.thrownErrors.push(e)}else Z.actQueue=null;0<Z.thrownErrors.length?(n=x(Z.thrownErrors),Z.thrownErrors.length=0,r(n)):t(e)}function j(e){if(!he){he=!0;var t=0;try{for(;t<e.length;t++)for(var r=e[t];;){Z.didUsePromise=!1;var n=r(!1);if(null===n)break;if(Z.didUsePromise)return e[t]=r,void e.splice(0,t);r=n}e.length=0}catch(r){e.splice(0,t+1),Z.thrownErrors.push(r)}finally{he=!1}}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var O=Symbol.for("react.transitional.element"),M=Symbol.for("react.portal"),P=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),$=Symbol.for("react.profiler"),H=Symbol.for("react.consumer"),D=Symbol.for("react.context"),L=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),U=Symbol.for("react.suspense_list"),B=Symbol.for("react.memo"),z=Symbol.for("react.lazy"),N=Symbol.for("react.activity"),Q=Symbol.iterator,q={},F={isMounted:function(){return!1},enqueueForceUpdate:function(e){n(e,"forceUpdate")},enqueueReplaceState:function(e){n(e,"replaceState")},enqueueSetState:function(e){n(e,"setState")}},V=Object.assign,W={};Object.freeze(W),s.prototype.isReactComponent={},s.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},s.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};var Y={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(pe in Y)Y.hasOwnProperty(pe)&&r(pe,Y[pe]);o.prototype=s.prototype,(Y=a.prototype=new o).constructor=a,V(Y,s.prototype),Y.isPureReactComponent=!0;var G,J,K=Array.isArray,X=Symbol.for("react.client.reference"),Z={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},ee=Object.prototype.hasOwnProperty,te=console.createTask?console.createTask:function(){return null},re={},ne=(Y={react_stack_bottom_frame:function(e){return e()}}).react_stack_bottom_frame.bind(Y,f)(),se=te(d(f)),oe=!1,ae=/\/+/g,ie="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},ce=!1,ue=null,le=0,de=!1,he=!1,fe="function"==typeof queueMicrotask?function(e){queueMicrotask((function(){return queueMicrotask(e)}))}:T;Y=Object.freeze({__proto__:null,c:function(e){return _().useMemoCache(e)}});var pe={map:S,forEach:function(e,t,r){S(e,(function(){t.apply(this,arguments)}),r)},count:function(e){var t=0;return S(e,(function(){t++})),t},toArray:function(e){return S(e,(function(e){return e}))||[]},only:function(e){if(!b(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};e.Activity=N,e.Children=pe,e.Component=s,e.Fragment=P,e.Profiler=$,e.PureComponent=a,e.StrictMode=R,e.Suspense=I,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Z,e.__COMPILER_RUNTIME=Y,e.act=function(e){var t=Z.actQueue,r=le;le++;var n=Z.actQueue=null!==t?t:[],s=!1;try{var o=e()}catch(e){Z.thrownErrors.push(e)}if(0<Z.thrownErrors.length)throw C(0,r),e=x(Z.thrownErrors),Z.thrownErrors.length=0,e;if(null!==o&&"object"==typeof o&&"function"==typeof o.then){var a=o;return fe((function(){s||de||(de=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))})),{then:function(e,t){s=!0,a.then((function(s){if(C(0,r),0===r){try{j(n),T((function(){return A(s,e,t)}))}catch(e){Z.thrownErrors.push(e)}if(0<Z.thrownErrors.length){var o=x(Z.thrownErrors);Z.thrownErrors.length=0,t(o)}}else e(s)}),(function(e){C(0,r),0<Z.thrownErrors.length?(e=x(Z.thrownErrors),Z.thrownErrors.length=0,t(e)):t(e)}))}}}var i=o;if(C(0,r),0===r&&(j(n),0!==n.length&&fe((function(){s||de||(de=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))})),Z.actQueue=null),0<Z.thrownErrors.length)throw e=x(Z.thrownErrors),Z.thrownErrors.length=0,e;return{then:function(e,t){s=!0,0===r?(Z.actQueue=n,T((function(){return A(i,e,t)}))):e(i)}}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.captureOwnerStack=function(){var e=Z.getCurrentStack;return null===e?null:e()},e.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var n,s=V({},e.props),o=e.key,a=e._owner;if(null!=t)for(i in(n=!(ee.call(t,"ref")&&(n=Object.getOwnPropertyDescriptor(t,"ref").get)&&n.isReactWarning)&&void 0!==t.ref)&&(a=h()),p(t)&&(u(t.key),o=""+t.key),t)!ee.call(t,i)||"key"===i||"__self"===i||"__source"===i||"ref"===i&&void 0===t.ref||(s[i]=t[i]);var i=arguments.length-2;if(1===i)s.children=r;else if(1<i){n=Array(i);for(var c=0;c<i;c++)n[c]=arguments[c+2];s.children=n}for(s=y(e.type,o,s,a,e._debugStack,e._debugTask),o=2;o<arguments.length;o++)g(arguments[o]);return s},e.createContext=function(e){return(e={$$typeof:D,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider=e,e.Consumer={$$typeof:H,_context:e},e._currentRenderer=null,e._currentRenderer2=null,e},e.createElement=function(e,t,r){for(var n=2;n<arguments.length;n++)g(arguments[n]);n={};var s=null;if(null!=t)for(c in J||!("__self"in t)||"key"in t||(J=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),p(t)&&(u(t.key),s=""+t.key),t)ee.call(t,c)&&"key"!==c&&"__self"!==c&&"__source"!==c&&(n[c]=t[c]);var o=arguments.length-2;if(1===o)n.children=r;else if(1<o){for(var a=Array(o),i=0;i<o;i++)a[i]=arguments[i+2];Object.freeze&&Object.freeze(a),n.children=a}if(e&&e.defaultProps)for(c in o=e.defaultProps)void 0===n[c]&&(n[c]=o[c]);s&&function(e,t){function r(){G||(G=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(n,"function"==typeof e?e.displayName||e.name||"Unknown":e);var c=1e4>Z.recentlyCreatedOwnerStacks++;return y(e,s,n,h(),c?Error("react-stack-top-frame"):ne,c?te(d(e)):se)},e.createRef=function(){var e={current:null};return Object.seal(e),e},e.forwardRef=function(e){null!=e&&e.$$typeof===B?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):"function"!=typeof e?console.error("forwardRef requires a render function but was given %s.",null===e?"null":typeof e):0!==e.length&&2!==e.length&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",1===e.length?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),null!=e&&null!=e.defaultProps&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var t,r={$$typeof:L,render:e};return Object.defineProperty(r,"displayName",{enumerable:!1,configurable:!0,get:function(){return t},set:function(r){t=r,e.name||e.displayName||(Object.defineProperty(e,"name",{value:r}),e.displayName=r)}}),r},e.isValidElement=b,e.lazy=function(e){var t={$$typeof:z,_payload:e={_status:-1,_result:e},_init:E},r={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return e._ioInfo=r,t._debugInfo=[{awaited:r}],t},e.memo=function(e,t){var r;return null==e&&console.error("memo: The first argument must be a component. Instead received: %s",null===e?"null":typeof e),t={$$typeof:B,type:e,compare:void 0===t?null:t},Object.defineProperty(t,"displayName",{enumerable:!1,configurable:!0,get:function(){return r},set:function(t){r=t,e.name||e.displayName||(Object.defineProperty(e,"name",{value:t}),e.displayName=t)}}),t},e.startTransition=function(e){var t=Z.T,r={};r._updatedFibers=new Set,Z.T=r;try{var n=e(),s=Z.S;null!==s&&s(r,n),"object"==typeof n&&null!==n&&"function"==typeof n.then&&(Z.asyncTransitions++,n.then(k,k),n.then(i,ie))}catch(e){ie(e)}finally{null===t&&r._updatedFibers&&(e=r._updatedFibers.size,r._updatedFibers.clear(),10<e&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),null!==t&&null!==r.types&&(null!==t.types&&t.types!==r.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),t.types=r.types),Z.T=t}},e.unstable_useCacheRefresh=function(){return _().useCacheRefresh()},e.use=function(e){return _().use(e)},e.useActionState=function(e,t,r){return _().useActionState(e,t,r)},e.useCallback=function(e,t){return _().useCallback(e,t)},e.useContext=function(e){var t=_();return e.$$typeof===H&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),t.useContext(e)},e.useDebugValue=function(e,t){return _().useDebugValue(e,t)},e.useDeferredValue=function(e,t){return _().useDeferredValue(e,t)},e.useEffect=function(e,t){return null==e&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),_().useEffect(e,t)},e.useEffectEvent=function(e){return _().useEffectEvent(e)},e.useId=function(){return _().useId()},e.useImperativeHandle=function(e,t,r){return _().useImperativeHandle(e,t,r)},e.useInsertionEffect=function(e,t){return null==e&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),_().useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return null==e&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),_().useLayoutEffect(e,t)},e.useMemo=function(e,t){return _().useMemo(e,t)},e.useOptimistic=function(e,t){return _().useOptimistic(e,t)},e.useReducer=function(e,t,r){return _().useReducer(e,t,r)},e.useRef=function(e){return _().useRef(e)},e.useState=function(e){return _().useState(e)},e.useSyncExternalStore=function(e,t,r){return _().useSyncExternalStore(e,t,r)},e.useTransition=function(){return _().useTransition()},e.version="19.2.0","undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()}}),h=i({"node_modules/.bun/react@19.2.0/node_modules/react/index.js"(e,t){"production"===process.env.NODE_ENV?t.exports=l():t.exports=d()}}),f=c(u()),p=Symbol.for("delete"),m=e=>Array.isArray(e)?[...e]:{...e};function y(e){const t=e?.deleteMarker||p;return function(e,r){if("object"!=typeof e||null===e)return"object"==typeof r&&null!==r?o(r):r===t?{}:r;if("object"!=typeof r||null===r)return e;const n=m(e),s=[{target:n,source:r}];for(;s.length>0;){const{target:e,source:r}=s.pop();for(const n of Object.keys(r)){if(!Object.prototype.hasOwnProperty.call(r,n))continue;const a=r[n];if(a!==t)if(Array.isArray(a))e[n]=a.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:o(e)));else if("object"==typeof a&&null!==a){const t=n in e&&"object"==typeof e[n]&&null!==e[n]?e[n]:{};e[n]=m(t),s.push({target:e[n],source:a})}else e[n]=a;else delete e[n]}}return n;function o(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:o(e)));if("object"==typeof e){const r={};for(const[n,s]of Object.entries(e))if(s!==t)if("object"==typeof s&&null!==s){const e=o(s);void 0!==e&&(r[n]=e)}else r[n]=s;return r}return e===t?void 0:e}}}var g=y();c(u());var b=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const r=v(e);this.validateSimpleSelector(e,r);const n=r.sort().join("|"),s=this.pathBasedCache.get(n);if(s)return this.reactiveSelectorCache.set(e,s),s;const o=`selector-${Math.random().toString(36).substring(2,9)}`,a=e(this.getState()),i={id:o,selector:e,lastResult:a,accessedPaths:r,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>i.lastResult,subscribe:t=>(i.subscribers.add(t),()=>{i.subscribers.delete(t),queueMicrotask((()=>{0===i.subscribers.size&&(this.reactiveSelectors.delete(o),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(n))}))}),id:o};return i.reactiveSelectorInstance=c,this.reactiveSelectors.set(o,i),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(n,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:o,accessedPaths:r,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const r=e.toString(),n=r.match(/=>\s*(.+)$/),s=n?n[1].trim():r,o=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of o)if(new RegExp(`\\.${e}\\s*\\(`).test(s))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(s))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(s))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(s))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const a=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(s),i=/\[.*\]/.test(s);if(a&&!i)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=v(e);this.validateSimpleSelector(e,t);let r,n=null;return s=>{const o=this.extractStateSubset(s,t);return n===o||(n=o,r=e(s)),r}}extractStateSubset(e,t){const r=[];for(const n of t){const t=n.split(".");let s=e;for(const e of t){if(null==s){r.push(void 0);break}s=s[e]}r.push(s)}return r}};function v(e,t="."){const r=new Set,n=(e=[])=>new Proxy({},{get:(s,o)=>{if("symbol"==typeof o)return;const a=[...e,o],i=a.join(t);return r.add(i),n(a)}});try{e(n())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const s=Array.from(r);return s.filter((e=>!s.some((r=>r!==e&&r.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let r,n;if(Array.isArray(e)){if(r=e.length,r!=t.length)return!1;for(n=r;n-- >0;)if(!w(e[n],t[n]))return!1;return!0}const[s,o]=[Object.keys(e),Object.keys(t)];if(r=s.length,r!==o.length)return!1;for(n=r;n-- >0;){const r=s[n];if(!Object.prototype.hasOwnProperty.call(t,r)||!w(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function S(e){const t=e?.deleteMarker||p;return function(e,r){const n=[],s=[{pathArray:[],pathStr:"",orig:e||{},part:r||{}}];for(;s.length>0;){const{pathArray:e,pathStr:r,orig:o,part:a}=s.pop();if(null!=a&&!w(o,a))if("object"!=typeof a||Array.isArray(a))r&&n.push({path:r,oldValue:o,newValue:a});else for(const i of Object.keys(a)){const c=[...e,i],u=r?r+"."+i:i,l=a[i],d=o&&"object"==typeof o?o[i]:void 0;l!==t?"object"==typeof l&&null!==l?s.push({pathArray:c,pathStr:u,orig:d,part:l}):w(d,l)||n.push({path:u,oldValue:d,newValue:l}):void 0===d&&o&&"object"==typeof o||n.push({path:u,oldValue:d,newValue:void 0})}}return n}}function E(e){const t=e?.deleteMarker||p;return function(e){const r=new Set,n=[{obj:e,currentPath:""}];for(;n.length>0;){const{obj:e,currentPath:s}=n.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const o of Object.keys(e)){const a=s?`${s}.${o}`:o;r.add(a);const i=a.split(".");if(i.length>1)for(let e=i.length-1;e>0;e--){const t=i.slice(0,e).join(".");if(r.has(t))break;r.add(t)}const c=e[o];"object"==typeof c&&null!==c&&c!==t&&n.push({obj:c,currentPath:a})}}return Array.from(r)}}var _=S(),k=E(),T=class{constructor(e,t,r){this.updateBus=t,this.diff=r,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,r=!1,n=[]){if(t)return this.cache=r?structuredClone(e):e,this.notifyListeners([]),[];0===n.length&&(n=[e]);const s=this.get(!1),o=new Map;for(let e=0;e<n.length;e++){const t=n[e],r=this.diff(s,t);for(let e=0;e<r.length;e++){const t=r[e];o.set(t.path,t)}}const a=o.size?[...o.values()]:[];if(a.length>0){this.cache=r?structuredClone(e):e;const t=new Set;for(let e=0;e<a.length;e++){let r=a[e].path;for(;r&&!t.has(r);){t.add(r);const e=r.lastIndexOf(".");if(e<0)break;r=r.slice(0,e)}}this.notifyListeners(t)}return a}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};c(u());var x=class{constructor(e,t,r){this.eventBus=e,this.executionState=t,this.merge=r}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:r,name:n,id:s}of this.blockingMiddleware){const o={id:s,name:n,startTime:performance.now()};this.executionState.runningMiddleware={id:s,name:n,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:s,name:n,type:"blocking"});try{const a=await Promise.resolve(r(e,t));if(o.endTime=performance.now(),o.duration=o.endTime-o.startTime,!1===a)return o.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:s,name:n,duration:o.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:o}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:s,name:n,type:"blocking",duration:o.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...o,blocked:!1}})}catch(e){return o.endTime=performance.now(),o.duration=o.endTime-o.startTime,o.error=e instanceof Error?e:new Error(String(e)),o.blocked=!0,this.emitMiddlewareError(s,n,o.error,o.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:o}),{blocked:!0,error:o.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let r=e,n=t;for(const{fn:e,name:s,id:o}of this.middleware){const a={id:o,name:s,startTime:performance.now()};this.executionState.runningMiddleware={id:o,name:s,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:o,name:s,type:"transform"});try{const i=await Promise.resolve(e(r,t));a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.blocked=!1,i&&"object"==typeof i&&(r=this.merge(r,i),n=this.merge(n,i)),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),this.emitMiddlewareLifecycle("complete",{id:o,name:s,type:"transform",duration:a.duration})}catch(e){a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:a}),this.emitMiddlewareError(o,s,a.error,a.duration),console.error(`Middleware ${s} error:`,e)}finally{this.executionState.runningMiddleware=null}}return n}addMiddleware(e,t="unnamed-middleware"){const r=this.generateId();return this.middleware.push({fn:e,name:t,id:r}),this.updateExecutionState(),r}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const r=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:r}),this.updateExecutionState(),r}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,r,n){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:r,duration:n,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};c(u());var C=class{constructor(e,t,r,n){this.eventBus=e,this.coreState=t,this.instanceID=r,this.maxRetries=n?.maxRetries??3,this.retryDelay=n?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const r={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(r),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:r.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:r.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const r=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:r,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),r)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};c(u());var A=class{constructor(e,t,r){this.eventBus=e,this.coreState=t,this.executionState=r}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};c(u());var j=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=r=>(this.totalEventsFired++,t.call(e,r)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};c(u());var O=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},M=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(t){const r=t.debounce,n={name:t.name,id:e.v4(),action:t.fn,debounce:r?{...r,condition:r.condition||(()=>!0)}:void 0};return this.actions.set(t.name,n),()=>{const e=this.actions.get(t.name);e?.debounce?.timer&&clearTimeout(e.debounce.timer),this.actions.delete(t.name)}}async dispatch(e,...t){const r=this.actions.get(e);if(!r)throw new Error(`unknown action ${e}`);const{id:n,action:s,debounce:o}=r;return!o||void 0===o.delay||o.delay<=0||o.condition&&!o.condition(o.args,t)?this.executeAction(e,n,s,t):(o.timer&&(clearTimeout(o.timer),o.reject?.(new O)),new Promise(((r,a)=>{o.resolve=r,o.reject=a,o.timer=setTimeout((async()=>{o.timer=void 0,o.resolve=void 0,o.reject=void 0;try{const o=await this.executeAction(e,n,s,t);r(o)}catch(e){a(e)}}),o.delay)})))}async executeAction(e,t,r,n){const s=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:n||[],timestamp:s}});try{const o=await this.set((e=>r(e,...n)),{actionId:t}),a=this.actions.get(e);a?.debounce&&(a.debounce.args=n);const i=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:n,startTime:s,endTime:i,duration:i-s,result:o}}),o}catch(r){const o=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:n,startTime:s,endTime:o,duration:o-s,error:r}}),r}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},P=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,f.createEventBus)();eventBus=(0,f.createEventBus)();executionState;instanceID=e.v4();merge;diff;constructor(e,t,r=p,n){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=y({deleteMarker:r}),this.diff=S({deleteMarker:r}),this.coreState=new T(e,this.updateBus,this.diff),this.middlewareEngine=new x(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new C(this.eventBus,this.coreState,this.instanceID,{maxRetries:n?.persistenceMaxRetries,retryDelay:n?.persistenceRetryDelay}),this.transactionManager=new A(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new j(this.eventBus),this.actionManager=new M(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new b(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const r=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=r.catch((()=>{})),r}async _performUpdate(e,t){this.executionState.executing=!0;const r=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:r,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),r="function"==typeof e?e(t):e;return this.coreState.applyChanges(r,!0),r}let n;const s=this.get(!1);if("function"==typeof e){const t=e(s);n=t instanceof Promise?await t:t}else n=e;const o=await this.middlewareEngine.executeBlocking(s,n);if(o.blocked)throw o.error||new Error("Update blocked by middleware");const a=this.merge(s,n),i=await this.middlewareEngine.executeTransform(a,n),c=this.merge(a,i),u=this.coreState.applyChanges(c,!1,!1,[n,i]),l=performance.now(),d=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:u,duration:l-r,timestamp:Date.now(),actionId:t.actionId,newState:d}}),d}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const r=Array.isArray(e)?e:[e],n=""===e||0===r.length;return this.updateBus.subscribe("update",(e=>{(n||r.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},R=(e=>(e.Singleton="singleton",e.Transient="transient",e))(R||{}),$=class{artifacts=new Map;resolvingStack=[];listeners=new Map;getState;subscribe;constructor(e){this.getState=(...t)=>e.get(...t),this.subscribe=(...t)=>e.watch(...t)}subscribeToArtifact(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const r=this.listeners.get(e);return r.add(t),()=>r.delete(t)}get(e){return this.artifacts.get(e)?.instance}notifyListeners(e){const t=this.listeners.get(e);t&&t.forEach((e=>e()))}register(e){const{key:t,factory:r,scope:n="singleton",lazy:s=!0}=e;this.artifacts.has(t)&&(console.warn(`[ArtifactContainer] Warning: Overwriting existing artifact "${t}".`),this.disposeArtifact(t));const o={key:t,factory:r,scope:n,lazy:s,stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set};return this.artifacts.set(t,o),s||"singleton"!==n||this.resolve(t).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${t}":`,e)})),async()=>{await this.unregister(t)}}async unregister(e){this.artifacts.has(e)&&(await this.disposeArtifact(e),this.artifacts.delete(e))}async resolve(e){if(this.resolvingStack.includes(e))throw new Error(`[ArtifactContainer] Circular dependency: ${this.resolvingStack.join(" -> ")} -> ${e}`);this.resolvingStack.push(e);try{const t=this.artifacts.get(e);if(!t)throw new Error(`[ArtifactContainer] Artifact with key "${e}" not found.`);if("transient"===t.scope)return this.createArtifactInstance(t,new Set,new Set);if(void 0!==t.instance)return t.instance;if(t.initializationPromise)return t.initializationPromise;const r=(async()=>{try{const e=new Set,r=new Set,n=await this.createArtifactInstance(t,e,r);return this.updateGraph(t,e,r),n}catch(e){throw t.initializationPromise=void 0,e}})();return t.initializationPromise=r,await r}finally{this.resolvingStack.pop()}}async createArtifactInstance(e,t,r){const n={state:this.getState,current:e.instance,use:async n=>n({resolve:async r=>{if(r===e.key)throw new Error(`[ArtifactContainer] Self-dependency detected in "${e.key}"`);return t.add(r),this.resolve(r)},select:e=>(v(e).forEach((e=>r.add(e))),e(this.getState()))})},s=await e.factory(n);let o,a;return Array.isArray(s)?[o,a]=s:o=s,"singleton"===e.scope?(e.instance=o,e.instanceCleanup=a):a&&console.warn(`[ArtifactContainer] Cleanup function returned for Transient artifact "${e.key}" will be ignored.`),o}updateGraph(e,t,r){e.artifactDependencies.forEach((t=>{const r=this.artifacts.get(t);r&&r.dependents.delete(e.key)})),e.artifactDependencies=t,t.forEach((t=>{const r=this.artifacts.get(t);r&&r.dependents.add(e.key)})),e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.stateDependencies=r,r.size>0&&(e.stateSubscriptionCleanup=this.subscribe(Array.from(r),(()=>this.invalidate(e.key)))),this.detectCycles(e.key),this.notifyListeners(e.key)}async invalidate(e){const t=this.artifacts.get(e);if(!t||void 0===t.instance)return;await this.disposeInstance(t);const r=Array.from(t.dependents);for(const e of r)await this.invalidate(e);t.lazy||this.resolve(e).catch((t=>{console.error(`[ArtifactContainer] Eager rebuild failed for "${e}":`,t)}))}async disposeInstance(e){if(e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.instanceCleanup){const t=e.instanceCleanup;await Promise.resolve().then((()=>t())).catch((t=>console.error(`[ArtifactContainer] Cleanup error for "${e.key}":`,t)))}e.instance=void 0,e.instanceCleanup=void 0,e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{const r=this.artifacts.get(t);r&&r.dependents.delete(e)})))}detectCycles(e){const t=new Set,r=new Set,n=e=>{if(r.has(e))throw new Error(`[ArtifactContainer] Circular dependency: ${Array.from(r).join(" -> ")} -> ${e}`);if(t.has(e))return;t.add(e),r.add(e);const s=this.artifacts.get(e);s&&s.artifactDependencies.forEach((e=>n(e))),r.delete(e)};n(e)}dispose(){this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear()}isLoading(e){return this.resolvingStack.includes(e)||void 0!==this.artifacts.get(e)?.initializationPromise}},H=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(r=>{"update:complete"!==t||r.blocked||this.isTimeTraveling||this.recordStateSnapshot(r.deltas),"middleware:executed"===t?this.middlewareExecutions.push(r):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),r.batchId&&(t.endsWith("start")?this.activeBatches.add(r.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(r.batchId)),this.recordEvent(t,r),this.enableConsoleLogging&&e&&this._log(t,r),this._checkPerformance(t,r)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const r={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(r),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:r=!0}=e;return(e,n)=>{if(r){(console[t]||console.log)("State Update:",n)}return n}}createValidationMiddleware(e){return(t,r)=>{const n=e(t,r);return"boolean"==typeof n?n:(!n.valid&&n.reason&&this._consoleLog("warn","Validation failed:",n.reason),n.valid)}}getRecentChanges(e=5){const t=[],r=Math.min(e,this.stateHistory.length);for(let e=0;e<r;e++){const r=this.stateHistory[e];if(!r.deltas||0===r.deltas.length)continue;const n={},s={},o=(e,t,r)=>{t.reduce(((e,n,s)=>(s===t.length-1?e[n]=r:e[n]=e[n]??{},e[n])),e)};for(const e of r.deltas){const t=e.path.split(".");o(n,t,e.oldValue),o(s,t,e.newValue)}t.push({timestamp:r.timestamp,changedPaths:r.deltas.map((e=>e.path)),from:n,to:s})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const r=this.store.onStoreEvent("update:complete",(r=>{this.isTimeTraveling||r.blocked||(t=[],e=0)}));this.unsubscribers.push(r);const n=()=>this.stateHistory.length,s=()=>e<n()-1,o=()=>t.length>0;return{canUndo:s,canRedo:o,undo:async()=>{if(!s())return;t.unshift(this.stateHistory[e]),e++;const r=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...r},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!o())return;const r=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...r.state},{force:!0}),this.isTimeTraveling=!1},length:n,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),r={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,r))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=`store-observer-session-${(new Date).toISOString()}.json`,n.click(),URL.revokeObjectURL(r)}importSession(e){return new Promise(((t,r)=>{const n=new FileReader;n.onload=async e=>{try{const r=JSON.parse(e.target?.result);this.eventHistory=r.eventHistory||[],this.stateHistory=r.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){r(e)}},n.onerror=e=>r(e),n.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const r=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${r}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${r}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${r}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${r}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${r}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${r}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${r}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${r}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${r}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${r}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${r}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${r}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${r}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${r}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}},D=c(h()),L=class{executions=[];maxHistory=100;listeners=new Set;track(e){this.executions.unshift(e),this.executions.length>this.maxHistory&&this.executions.pop(),this.notify()}getExecutions(){return[...this.executions]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){this.listeners.forEach((e=>e()))}};
2
- /*! Bundled license information:
3
-
4
- react/cjs/react.production.js:
5
- (**
6
- * @license React
7
- * react.production.js
8
- *
9
- * Copyright (c) Meta Platforms, Inc. and affiliates.
10
- *
11
- * This source code is licensed under the MIT license found in the
12
- * LICENSE file in the root directory of this source tree.
13
- *)
14
-
15
- react/cjs/react.development.js:
16
- (**
17
- * @license React
18
- * react.development.js
19
- *
20
- * Copyright (c) Meta Platforms, Inc. and affiliates.
21
- *
22
- * This source code is licensed under the MIT license found in the
23
- * LICENSE file in the root directory of this source tree.
24
- *)
25
- */
26
- exports.ActionManager=M,exports.ArtifactContainer=$,exports.ArtifactScope=R,exports.DELETE_SYMBOL=p,exports.ReactiveDataStore=P,exports.StoreObserver=H,exports.createDerivePaths=E,exports.createDiff=S,exports.createMerge=y,exports.createStore=function(e,{enableMetrics:t,...r}={}){const n=new P(e.state,r.persistence),s=Object.keys(e.actions).reduce(((e,t)=>(e[t]=!1,e)),{}),o=new P(s),a=t?new H(n,r):void 0,i=t?new L:void 0;t&&i&&(n.on("action:start",(({name:e})=>{o.set((()=>({[e]:!0})))})),n.on("action:complete",(e=>{o.set((()=>({[e.name]:!1}))),i.track({id:e.actionId,name:e.name,params:e.params,startTime:e.startTime,endTime:e.endTime,duration:e.duration,status:"success",result:e.result})})),n.on("action:error",(e=>{o.set((()=>({[e.name]:!1}))),i.track({id:e.actionId,name:e.name,params:e.params,startTime:e.startTime,endTime:e.endTime,duration:e.duration,status:"error",error:e.error})}))),e.middleware&&Object.entries(e.middleware).forEach((([e,t])=>n.use({name:e,action:t}))),e.blockingMiddleware&&Object.entries(e.blockingMiddleware).forEach((([e,t])=>n.use({block:!0,name:e,action:t})));const c=e=>(n.isReady()&&e(),n.on("persistence:ready",e)),u=()=>n.isReady(),l=new $(n);e.artifacts&&Object.entries(e.artifacts).forEach((([e,t])=>{l.register({key:e,factory:t.factory,scope:t.scope,lazy:t.lazy})}));const d=Object.entries(e.actions).reduce(((e,[t,r])=>(n.register({name:t,fn:(e,...t)=>{const n={state:e,resolve:l.resolve.bind(l)};return r(n,...t)}}),e[t]=(...e)=>n.dispatch(t,...e),e)),{});return function(){const e=()=>(0,D.useSyncExternalStore)((e=>n.watch("",e)),(()=>n.get()),(()=>n.get())),t=(0,D.useSyncExternalStore)(c,u,u);return{store:n,observer:a,select:e=>{const t=n.select(e);return(0,D.useSyncExternalStore)((e=>t.subscribe(e)),(()=>t.get()),(()=>t.get()))},actions:d,isReady:t,actionTracker:i,watch:e=>(0,D.useSyncExternalStore)((t=>o.watch(e,t)),(()=>!!o.get()[e]),(()=>!!o.get()[e])),resolve:e=>{const t=(0,D.useSyncExternalStore)((t=>l.subscribeToArtifact(e,t)),(()=>l.get(e)),(()=>l.get(e)));(0,D.useEffect)((()=>{void 0!==t||l.isLoading(e)||l.resolve(e).catch(console.error)}),[e,t]);return[t,null!=t]},get state(){return e}}}},exports.derivePaths=k,exports.diff=_,exports.merge=g,exports.shallowClone=m;
1
+ "use strict";var e,t,s=require("uuid"),i=Object.create,r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,s)=>(s=null!=e?i(o(e)):{},((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of n(t))c.call(e,o)||o===s||r(e,o,{get:()=>t[o],enumerable:!(i=a(t,o))||i.enumerable});return e})(e&&e.__esModule?s:r(s,"default",{value:e,enumerable:!0}),e)),d=(e={"src/store/node_modules/@asaidimu/events/index.js"(e,t){var s,i=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||i(e,c,{get:()=>t[c],enumerable:!(o=r(t,c))||o.enumerable});return e})(i({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],i=0,r=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{i++,r+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(i){e.errorHandler({...i,eventName:t,payload:s})}c(t,performance.now()-i)}))},d=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),h=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const i=t.get(e);return i.add(s),h(e),()=>{i.delete(s),0===i.size?(t.delete(e),n.delete(e)):h(e)}},emit:({name:t,payload:i})=>{if(e.async)return s.push({name:t,payload:i}),s.length>=e.batchSize?l():d(),void(o&&o.postMessage({name:t,payload:i}));const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(i))),o&&o.postMessage({name:t,payload:i})}catch(s){e.errorHandler({...s,eventName:t,payload:i})}c(t,performance.now()-r)},getMetrics:()=>({totalEvents:i,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:i>0?r/i:0}),clear:()=>{t.clear(),n.clear(),s=[],i=0,r=0,a.clear(),o&&(o.close(),o=null)}}}}},function(){return t||(0,e[n(e)[0]])((t={exports:{}}).exports,t),t.exports}),h=l(d()),u=Symbol.for("delete"),p=e=>Array.isArray(e)?[...e]:{...e};function m(e){const t=e?.deleteMarker||u;return function(e,s){if("object"!=typeof e||null===e)return"object"==typeof s&&null!==s?a(s):s===t?{}:s;if("object"!=typeof s||null===s)return e;const i=p(e),r=[{target:i,source:s}];for(;r.length>0;){const{target:e,source:s}=r.pop();for(const i of Object.keys(s)){if(!Object.prototype.hasOwnProperty.call(s,i))continue;const n=s[i];if(n!==t)if(Array.isArray(n))e[i]=n.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));else if("object"==typeof n&&null!==n){const t=i in e&&"object"==typeof e[i]&&null!==e[i]?e[i]:{};e[i]=p(t),r.push({target:e[i],source:n})}else e[i]=n;else delete e[i]}}return i;function a(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));if("object"==typeof e){const s={};for(const[i,r]of Object.entries(e))if(r!==t)if("object"==typeof r&&null!==r){const e=a(r);void 0!==e&&(s[i]=e)}else s[i]=r;return s}return e===t?void 0:e}}}var f=m();l(d());var g=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const s=y(e);this.validateSimpleSelector(e,s);const i=s.sort().join("|"),r=this.pathBasedCache.get(i);if(r)return this.reactiveSelectorCache.set(e,r),r;const a=`selector-${Math.random().toString(36).substring(2,9)}`,n=e(this.getState()),o={id:a,selector:e,lastResult:n,accessedPaths:s,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>o.lastResult,subscribe:t=>(o.subscribers.add(t),()=>{o.subscribers.delete(t),queueMicrotask((()=>{0===o.subscribers.size&&(this.reactiveSelectors.delete(a),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(i))}))}),id:a};return o.reactiveSelectorInstance=c,this.reactiveSelectors.set(a,o),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(i,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:a,accessedPaths:s,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const s=e.toString(),i=s.match(/=>\s*(.+)$/),r=i?i[1].trim():s,a=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of a)if(new RegExp(`\\.${e}\\s*\\(`).test(r))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(r))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(r))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(r))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const n=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(r),o=/\[.*\]/.test(r);if(n&&!o)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=y(e);this.validateSimpleSelector(e,t);let s,i=null;return r=>{const a=this.extractStateSubset(r,t);return i===a||(i=a,s=e(r)),s}}extractStateSubset(e,t){const s=[];for(const i of t){const t=i.split(".");let r=e;for(const e of t){if(null==r){s.push(void 0);break}r=r[e]}s.push(r)}return s}};function y(e,t="."){const s=new Set,i=(e=[])=>new Proxy({},{get:(r,a)=>{if("symbol"==typeof a)return;const n=[...e,a],o=n.join(t);return s.add(o),i(n)}});try{e(i())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const r=Array.from(s);return r.filter((e=>!r.some((s=>s!==e&&s.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let s,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(i=s;i-- >0;)if(!w(e[i],t[i]))return!1;return!0}const[r,a]=[Object.keys(e),Object.keys(t)];if(s=r.length,s!==a.length)return!1;for(i=s;i-- >0;){const s=r[i];if(!Object.prototype.hasOwnProperty.call(t,s)||!w(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}function v(e){const t=e?.deleteMarker||u;return function(e,s){const i=[],r=[{pathArray:[],pathStr:"",orig:e||{},part:s||{}}];for(;r.length>0;){const{pathArray:e,pathStr:s,orig:a,part:n}=r.pop();if(null!=n&&!w(a,n))if("object"!=typeof n||Array.isArray(n))s&&i.push({path:s,oldValue:a,newValue:n});else for(const o of Object.keys(n)){const c=[...e,o],l=s?s+"."+o:o,d=n[o],h=a&&"object"==typeof a?a[o]:void 0;d!==t?"object"==typeof d&&null!==d?r.push({pathArray:c,pathStr:l,orig:h,part:d}):w(h,d)||i.push({path:l,oldValue:h,newValue:d}):void 0===h&&a&&"object"==typeof a||i.push({path:l,oldValue:h,newValue:void 0})}}return i}}function b(e){const t=e?.deleteMarker||u;return function(e){const s=new Set,i=[{obj:e,currentPath:""}];for(;i.length>0;){const{obj:e,currentPath:r}=i.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const a of Object.keys(e)){const n=r?`${r}.${a}`:a;s.add(n);const o=n.split(".");if(o.length>1)for(let e=o.length-1;e>0;e--){const t=o.slice(0,e).join(".");if(s.has(t))break;s.add(t)}const c=e[a];"object"==typeof c&&null!==c&&c!==t&&i.push({obj:c,currentPath:n})}}return Array.from(s)}}var S=v(),E=b(),x=class{constructor(e,t,s){this.updateBus=t,this.diff=s,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,s=!1,i=[]){if(t)return this.cache=s?structuredClone(e):e,this.notifyListeners([]),[];0===i.length&&(i=[e]);const r=this.get(!1),a=new Map;for(let e=0;e<i.length;e++){const t=i[e],s=this.diff(r,t);for(let e=0;e<s.length;e++){const t=s[e];a.set(t.path,t)}}const n=a.size?[...a.values()]:[];if(n.length>0){this.cache=s?structuredClone(e):e;const t=new Set;for(let e=0;e<n.length;e++){let s=n[e].path;for(;s&&!t.has(s);){t.add(s);const e=s.lastIndexOf(".");if(e<0)break;s=s.slice(0,e)}}this.notifyListeners(t)}return n}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};l(d());var k=class{constructor(e,t,s){this.eventBus=e,this.executionState=t,this.merge=s}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:s,name:i,id:r}of this.blockingMiddleware){const a={id:r,name:i,startTime:performance.now()};this.executionState.runningMiddleware={id:r,name:i,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:r,name:i,type:"blocking"});try{const n=await Promise.resolve(s(e,t));if(a.endTime=performance.now(),a.duration=a.endTime-a.startTime,!1===n)return a.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:r,name:i,duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:r,name:i,type:"blocking",duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...a,blocked:!1}})}catch(e){return a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!0,this.emitMiddlewareError(r,i,a.error,a.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0,error:a.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let s=e,i=t;for(const{fn:e,name:r,id:a}of this.middleware){const n={id:a,name:r,startTime:performance.now()};this.executionState.runningMiddleware={id:a,name:r,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:a,name:r,type:"transform"});try{const o=await Promise.resolve(e(s,t));n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.blocked=!1,o&&"object"==typeof o&&(s=this.merge(s,o),i=this.merge(i,o)),this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareLifecycle("complete",{id:a,name:r,type:"transform",duration:n.duration})}catch(e){n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.error=e instanceof Error?e:new Error(String(e)),n.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareError(a,r,n.error,n.duration),console.error(`Middleware ${r} error:`,e)}finally{this.executionState.runningMiddleware=null}}return i}addMiddleware(e,t="unnamed-middleware"){const s=this.generateId();return this.middleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const s=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,s,i){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:s,duration:i,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var T=class{constructor(e,t,s,i){this.eventBus=e,this.coreState=t,this.instanceID=s,this.maxRetries=i?.maxRetries??3,this.retryDelay=i?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const s={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(s),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:s.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:s.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const s=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:s,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),s)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var C=class{constructor(e,t,s){this.eventBus=e,this.coreState=t,this.executionState=s}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var A=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=s=>(this.totalEventsFired++,t.call(e,s)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};l(d());var P=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},M=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(e){const t=e.debounce,i={name:e.name,id:s.v4(),action:e.fn,debounce:t?{...t,condition:t.condition||(()=>!0)}:void 0};return this.actions.set(e.name,i),()=>{const t=this.actions.get(e.name);t?.debounce?.timer&&clearTimeout(t.debounce.timer),this.actions.delete(e.name)}}async dispatch(e,...t){const s=this.actions.get(e);if(!s)throw new Error(`unknown action ${e}`);const{id:i,action:r,debounce:a}=s;return!a||void 0===a.delay||a.delay<=0||a.condition&&!a.condition(a.args,t)?this.executeAction(e,i,r,t):(a.timer&&(clearTimeout(a.timer),a.reject?.(new P)),new Promise(((s,n)=>{a.resolve=s,a.reject=n,a.timer=setTimeout((async()=>{a.timer=void 0,a.resolve=void 0,a.reject=void 0;try{const a=await this.executeAction(e,i,r,t);s(a)}catch(e){n(e)}}),a.delay)})))}async executeAction(e,t,s,i){const r=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:i||[],timestamp:r}});try{const a=await this.set((e=>s(e,...i)),{actionId:t}),n=this.actions.get(e);n?.debounce&&(n.debounce.args=i);const o=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:i,startTime:r,endTime:o,duration:o-r,result:a}}),a}catch(s){const a=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:i,startTime:r,endTime:a,duration:a-r,error:s}}),s}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},B=(e=>(e.Singleton="singleton",e.Transient="transient",e))(B||{});exports.ActionManager=M,exports.ArtifactContainer=class{artifacts=new Map;resolvingStack=[];listeners=new Map;getState;subscribe;constructor(e){this.getState=(...t)=>e.get(...t),this.subscribe=(...t)=>e.watch(...t)}watch(e){return{id:e,get:()=>{const t=this.artifacts.get(e);return t&&(void 0!==t.instance||t.error)?this.packageArtifact(t):null},subscribe:t=>{this.listeners.has(e)||this.listeners.set(e,new Set);const s=this.listeners.get(e);return s.add(t),()=>s.delete(t)}}}get(e){return this.artifacts.get(e)?.instance}register(e){const{key:t,factory:s,scope:i="singleton",lazy:r=!0}=e;this.artifacts.has(t)&&(console.warn(`[ArtifactContainer] Warning: Overwriting existing artifact "${t}".`),this.disposeArtifact(t));const a={key:t,factory:s,scope:i,lazy:r,cleanupFunctions:[],stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set};return this.artifacts.set(t,a),r||"singleton"!==i||this.resolve(t).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${t}":`,e)})),async()=>{await this.unregister(t)}}async unregister(e){this.artifacts.has(e)&&(await this.disposeArtifact(e),this.artifacts.delete(e))}async resolve(e){if(this.resolvingStack.includes(e))throw new Error(`[ArtifactContainer] Circular dependency: ${this.resolvingStack.join(" -> ")} -> ${e}`);this.resolvingStack.push(e);try{const t=this.artifacts.get(e);if(!t)throw new Error(`[ArtifactContainer] Artifact with key "${e}" not found.`);if("transient"===t.scope){const e=await this.createArtifactInstance(t,new Set,new Set);return{instance:e.instance,cleanup:e.cleanup,error:e.error,invalidate:async()=>{}}}if(void 0!==t.instance||void 0!==t.error)return this.packageArtifact(t);if(t.initializationPromise)try{return await t.initializationPromise,this.packageArtifact(t)}catch(e){return this.packageArtifact(t)}const s=(async()=>{try{const e=new Set,s=new Set,i=await this.createArtifactInstance(t,e,s);return this.updateGraph(t,e,s),i.error&&(t.error=i.error),i.instance}catch(e){throw t.error=e,t.initializationPromise=void 0,e}})();t.initializationPromise=s;try{await s}catch(e){}return this.packageArtifact(t)}finally{this.resolvingStack.pop()}}packageArtifact(e){return{instance:e.instance,cleanup:this.createCompositeCleanup(e.cleanupFunctions),error:e.error,invalidate:async t=>this.invalidate(e.key,t)}}async createArtifactInstance(e,t,s){const i=[];let r=!0;i.push((()=>{r=!1}));const a={state:this.getState,current:e.instance,use:async i=>i({resolve:async s=>{if(s===e.key)throw new Error(`[ArtifactContainer] Self-dependency detected in "${e.key}"`);return t.add(s),this.resolve(s)},select:e=>(y(e).forEach((e=>s.add(e))),e(this.getState()))}),onCleanup:e=>{i.push(e)},yield:t=>{r?"transient"!==e.scope?(e.instance=t,e.error=void 0,this.processYieldPropagation(e.key)):console.warn(`[ArtifactContainer] Yield ignored on transient artifact "${e.key}"`):console.warn(`[ArtifactContainer] Ignored yield on disposed artifact "${e.key}"`)}};let n,o;try{n=await e.factory(a)}catch(e){o=e,n=void 0}"singleton"===e.scope&&(void 0!==n&&(e.instance=n),e.cleanupFunctions=i);return{instance:"singleton"===e.scope?e.instance:n,cleanup:this.createCompositeCleanup(i),error:o}}async processYieldPropagation(e){const t=this.artifacts.get(e);if(t&&(void 0!==t.instance||t.error))try{const s=Array.from(t.dependents);await Promise.all(s.map((e=>this.invalidate(e,!1)))),this.notifyListeners(e)}catch(t){console.error(`[ArtifactContainer] Yield propagation failed for "${e}":`,t)}}updateGraph(e,t,s){e.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e.key)})),e.artifactDependencies=t,t.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.add(e.key)}));const i=e.stateSubscriptionCleanup;e.stateDependencies=s,s.size>0?e.stateSubscriptionCleanup=this.subscribe(Array.from(s),(()=>this.invalidate(e.key))):e.stateSubscriptionCleanup=void 0,i&&i(),this.detectCycles(e.key),this.notifyListeners(e.key)}async invalidate(e,t=!1){const s=this.artifacts.get(e);if(!s)return;if(s.initializationPromise)try{await s.initializationPromise}catch(e){}if(s.rebuildPromise)return s.rebuildPromise;const i=(async()=>{try{const i=Array.from(s.dependents);await Promise.all(i.map((e=>this.invalidate(e,t)))),await this.disposeInstance(s),!t&&s.lazy||await this.resolve(e).catch((t=>{console.error(`[ArtifactContainer] Rebuild failed for "${e}":`,t)}))}finally{s.rebuildPromise=void 0}})();return s.rebuildPromise=i,i}async disposeInstance(e){if(e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.cleanupFunctions.length>0)for(let t=e.cleanupFunctions.length-1;t>=0;t--)try{await e.cleanupFunctions[t]()}catch(t){console.error(`[ArtifactContainer] Cleanup error for "${e.key}":`,t)}e.instance=void 0,e.error=void 0,e.cleanupFunctions=[],e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(t.rebuildPromise&&await t.rebuildPromise,await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e)})))}createCompositeCleanup(e){if(0!==e.length)return async()=>{for(let t=e.length-1;t>=0;t--)try{await e[t]()}catch(e){}}}notifyListeners(e){const t=this.listeners.get(e);t&&t.forEach((e=>e()))}detectCycles(e){const t=new Set,s=new Set,i=e=>{if(s.has(e))throw new Error(`[ArtifactContainer] Circular dependency: ${Array.from(s).join(" -> ")} -> ${e}`);if(t.has(e))return;t.add(e),s.add(e);const r=this.artifacts.get(e);r&&r.artifactDependencies.forEach((e=>i(e))),s.delete(e)};i(e)}dispose(){this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear()}isLoading(e){return this.resolvingStack.includes(e)||void 0!==this.artifacts.get(e)?.initializationPromise}},exports.ArtifactScope=B,exports.DELETE_SYMBOL=u,exports.ReactiveDataStore=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,h.createEventBus)();eventBus=(0,h.createEventBus)();executionState;instanceID=s.v4();merge;diff;constructor(e,t,s=u,i){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=m({deleteMarker:s}),this.diff=v({deleteMarker:s}),this.coreState=new x(e,this.updateBus,this.diff),this.middlewareEngine=new k(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new T(this.eventBus,this.coreState,this.instanceID,{maxRetries:i?.persistenceMaxRetries,retryDelay:i?.persistenceRetryDelay}),this.transactionManager=new C(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new A(this.eventBus),this.actionManager=new M(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new g(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const s=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=s.catch((()=>{})),s}async _performUpdate(e,t){this.executionState.executing=!0;const s=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:s,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),s="function"==typeof e?e(t):e;return this.coreState.applyChanges(s,!0),s}let i;const r=this.get(!1);if("function"==typeof e){const t=e(r);i=t instanceof Promise?await t:t}else i=e;const a=await this.middlewareEngine.executeBlocking(r,i);if(a.blocked)throw a.error||new Error("Update blocked by middleware");const n=this.merge(r,i),o=await this.middlewareEngine.executeTransform(n,i),c=this.merge(n,o),l=this.coreState.applyChanges(c,!1,!1,[i,o]),d=performance.now(),h=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:l,duration:d-s,timestamp:Date.now(),actionId:t.actionId,newState:h}}),h}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const s=Array.isArray(e)?e:[e],i=""===e||0===s.length;return this.updateBus.subscribe("update",(e=>{(i||s.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},exports.StoreObserver=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(s=>{"update:complete"!==t||s.blocked||this.isTimeTraveling||this.recordStateSnapshot(s.deltas),"middleware:executed"===t?this.middlewareExecutions.push(s):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),s.batchId&&(t.endsWith("start")?this.activeBatches.add(s.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(s.batchId)),this.recordEvent(t,s),this.enableConsoleLogging&&e&&this._log(t,s),this._checkPerformance(t,s)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const s={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(s),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:s=!0}=e;return(e,i)=>{if(s){(console[t]||console.log)("State Update:",i)}return i}}createValidationMiddleware(e){return(t,s)=>{const i=e(t,s);return"boolean"==typeof i?i:(!i.valid&&i.reason&&this._consoleLog("warn","Validation failed:",i.reason),i.valid)}}getRecentChanges(e=5){const t=[],s=Math.min(e,this.stateHistory.length);for(let e=0;e<s;e++){const s=this.stateHistory[e];if(!s.deltas||0===s.deltas.length)continue;const i={},r={},a=(e,t,s)=>{t.reduce(((e,i,r)=>(r===t.length-1?e[i]=s:e[i]=e[i]??{},e[i])),e)};for(const e of s.deltas){const t=e.path.split(".");a(i,t,e.oldValue),a(r,t,e.newValue)}t.push({timestamp:s.timestamp,changedPaths:s.deltas.map((e=>e.path)),from:i,to:r})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const s=this.store.onStoreEvent("update:complete",(s=>{this.isTimeTraveling||s.blocked||(t=[],e=0)}));this.unsubscribers.push(s);const i=()=>this.stateHistory.length,r=()=>e<i()-1,a=()=>t.length>0;return{canUndo:r,canRedo:a,undo:async()=>{if(!r())return;t.unshift(this.stateHistory[e]),e++;const s=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...s},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!a())return;const s=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...s.state},{force:!0}),this.isTimeTraveling=!1},length:i,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),s={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,s))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(t),i=document.createElement("a");i.href=s,i.download=`store-observer-session-${(new Date).toISOString()}.json`,i.click(),URL.revokeObjectURL(s)}importSession(e){return new Promise(((t,s)=>{const i=new FileReader;i.onload=async e=>{try{const s=JSON.parse(e.target?.result);this.eventHistory=s.eventHistory||[],this.stateHistory=s.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){s(e)}},i.onerror=e=>s(e),i.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const s=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${s}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${s}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${s}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${s}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${s}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${s}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${s}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${s}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${s}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${s}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${s}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}},exports.createDerivePaths=b,exports.createDiff=v,exports.createMerge=m,exports.derivePaths=E,exports.diff=S,exports.merge=f,exports.shallowClone=p;
package/index.mjs CHANGED
@@ -1,25 +1 @@
1
- import{v4 as e}from"uuid";var t=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,o=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,i=(e,t)=>function(){return t||(0,e[s(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(e,i,c)=>(c=null!=e?t(o(e)):{},((e,t,o,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of s(t))a.call(e,c)||c===o||r(e,c,{get:()=>t[c],enumerable:!(i=n(t,c))||i.enumerable});return e})(e&&e.__esModule?c:r(c,"default",{value:e,enumerable:!0}),e)),u=i({"node_modules/.bun/@asaidimu+events@1.1.2/node_modules/@asaidimu/events/index.js"(e,t){var r,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(i,{createEventBus:()=>c}),t.exports=(r=i,((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))a.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(i=s(t,c))||i.enumerable});return e})(n({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],n=0,s=0;const o=new Map,a=new Map;let i=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?i=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{n++,s+=t,o.set(e,(o.get(e)||0)+1)},u=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const n=performance.now();try{(a.get(t)||[]).forEach((e=>e(r)))}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-n)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(u,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?a.set(e,Array.from(r)):a.delete(e)};return i&&(i.onmessage=e=>{const{name:t,payload:r}=e.data;(a.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const n=t.get(e);return n.add(r),d(e),()=>{n.delete(r),0===n.size?(t.delete(e),a.delete(e)):d(e)}},emit:({name:t,payload:n})=>{if(e.async)return r.push({name:t,payload:n}),r.length>=e.batchSize?u():l(),void(i&&i.postMessage({name:t,payload:n}));const s=performance.now();try{(a.get(t)||[]).forEach((e=>e(n))),i&&i.postMessage({name:t,payload:n})}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-s)},getMetrics:()=>({totalEvents:n,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:o,averageEmitDuration:n>0?s/n:0}),clear:()=>{t.clear(),a.clear(),r=[],n=0,s=0,o.clear(),i&&(i.close(),i=null)}}}}}),l=i({"node_modules/.bun/react@19.2.0/node_modules/react/cjs/react.production.js"(e){var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),i=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),l=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;var p={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,y={};function g(e,t,r){this.props=e,this.context=t,this.refs=y,this.updater=r||p}function b(){}function v(e,t,r){this.props=e,this.context=t,this.refs=y,this.updater=r||p}g.prototype.isReactComponent={},g.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},g.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},b.prototype=g.prototype;var w=v.prototype=new b;w.constructor=v,m(w,g.prototype),w.isPureReactComponent=!0;var S=Array.isArray;function E(){}var _={H:null,A:null,T:null,S:null},k=Object.prototype.hasOwnProperty;function T(e,r,n){var s=n.ref;return{$$typeof:t,type:e,key:r,ref:void 0!==s?s:null,props:n}}function C(e){return"object"==typeof e&&null!==e&&e.$$typeof===t}var x=/\/+/g;function j(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(r=""+e.key,n={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,(function(e){return n[e]}))):t.toString(36);var r,n}function A(e,n,s,o,a){var i=typeof e;"undefined"!==i&&"boolean"!==i||(e=null);var c,u,l=!1;if(null===e)l=!0;else switch(i){case"bigint":case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case t:case r:l=!0;break;case d:return A((l=e._init)(e._payload),n,s,o,a)}}if(l)return a=a(e),l=""===o?"."+j(e,0):o,S(a)?(s="",null!=l&&(s=l.replace(x,"$&/")+"/"),A(a,n,s,"",(function(e){return e}))):null!=a&&(C(a)&&(c=a,u=s+(null==a.key||e&&e.key===a.key?"":(""+a.key).replace(x,"$&/")+"/")+l,a=T(c.type,u,c.props)),n.push(a)),1;l=0;var h,p=""===o?".":o+":";if(S(e))for(var m=0;m<e.length;m++)l+=A(o=e[m],n,s,i=p+j(o,m),a);else if("function"==typeof(m=null===(h=e)||"object"!=typeof h?null:"function"==typeof(h=f&&h[f]||h["@@iterator"])?h:null))for(e=m.call(e),m=0;!(o=e.next()).done;)l+=A(o=o.value,n,s,i=p+j(o,m++),a);else if("object"===i){if("function"==typeof e.then)return A(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(E,E):(e.status="pending",e.then((function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)}),(function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)}))),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(e),n,s,o,a);throw n=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===n?"object with keys {"+Object.keys(e).join(", ")+"}":n)+"). If you meant to render a collection of children, use an array instead.")}return l}function O(e,t,r){if(null==e)return e;var n=[],s=0;return A(e,n,"","",(function(e){return t.call(r,e,s++)})),n}function M(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var P="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},R={map:O,forEach:function(e,t,r){O(e,(function(){t.apply(this,arguments)}),r)},count:function(e){var t=0;return O(e,(function(){t++})),t},toArray:function(e){return O(e,(function(e){return e}))||[]},only:function(e){if(!C(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};e.Activity=h,e.Children=R,e.Component=g,e.Fragment=n,e.Profiler=o,e.PureComponent=v,e.StrictMode=s,e.Suspense=u,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return _.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var n=m({},e.props),s=e.key;if(null!=t)for(o in void 0!==t.key&&(s=""+t.key),t)!k.call(t,o)||"key"===o||"__self"===o||"__source"===o||"ref"===o&&void 0===t.ref||(n[o]=t[o]);var o=arguments.length-2;if(1===o)n.children=r;else if(1<o){for(var a=Array(o),i=0;i<o;i++)a[i]=arguments[i+2];n.children=a}return T(e.type,s,n)},e.createContext=function(e){return(e={$$typeof:i,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider=e,e.Consumer={$$typeof:a,_context:e},e},e.createElement=function(e,t,r){var n,s={},o=null;if(null!=t)for(n in void 0!==t.key&&(o=""+t.key),t)k.call(t,n)&&"key"!==n&&"__self"!==n&&"__source"!==n&&(s[n]=t[n]);var a=arguments.length-2;if(1===a)s.children=r;else if(1<a){for(var i=Array(a),c=0;c<a;c++)i[c]=arguments[c+2];s.children=i}if(e&&e.defaultProps)for(n in a=e.defaultProps)void 0===s[n]&&(s[n]=a[n]);return T(e,o,s)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=C,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:M}},e.memo=function(e,t){return{$$typeof:l,type:e,compare:void 0===t?null:t}},e.startTransition=function(e){var t=_.T,r={};_.T=r;try{var n=e(),s=_.S;null!==s&&s(r,n),"object"==typeof n&&null!==n&&"function"==typeof n.then&&n.then(E,P)}catch(e){P(e)}finally{null!==t&&null!==r.types&&(t.types=r.types),_.T=t}},e.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()},e.use=function(e){return _.H.use(e)},e.useActionState=function(e,t,r){return _.H.useActionState(e,t,r)},e.useCallback=function(e,t){return _.H.useCallback(e,t)},e.useContext=function(e){return _.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return _.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return _.H.useEffect(e,t)},e.useEffectEvent=function(e){return _.H.useEffectEvent(e)},e.useId=function(){return _.H.useId()},e.useImperativeHandle=function(e,t,r){return _.H.useImperativeHandle(e,t,r)},e.useInsertionEffect=function(e,t){return _.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return _.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return _.H.useMemo(e,t)},e.useOptimistic=function(e,t){return _.H.useOptimistic(e,t)},e.useReducer=function(e,t,r){return _.H.useReducer(e,t,r)},e.useRef=function(e){return _.H.useRef(e)},e.useState=function(e){return _.H.useState(e)},e.useSyncExternalStore=function(e,t,r){return _.H.useSyncExternalStore(e,t,r)},e.useTransition=function(){return _.H.useTransition()},e.version="19.2.0"}}),d=i({"node_modules/.bun/react@19.2.0/node_modules/react/cjs/react.development.js"(e,t){"production"!==process.env.NODE_ENV&&function(){function r(e,t){Object.defineProperty(s.prototype,e,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",t[0],t[1])}})}function n(e,t){var r=(e=(e=e.constructor)&&(e.displayName||e.name)||"ReactClass")+"."+t;F[r]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",t,e),F[r]=!0)}function s(e,t,r){this.props=e,this.context=t,this.refs=W,this.updater=r||q}function o(){}function a(e,t,r){this.props=e,this.context=t,this.refs=W,this.updater=r||q}function i(){}function c(e){return""+e}function u(e){try{c(e);var t=!1}catch(e){t=!0}if(t){var r=(t=console).error,n="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return r.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",n),c(e)}}function l(e){if(null==e)return null;if("function"==typeof e)return e.$$typeof===X?null:e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case P:return"Fragment";case $:return"Profiler";case R:return"StrictMode";case L:return"Suspense";case U:return"SuspenseList";case N:return"Activity"}if("object"==typeof e)switch("number"==typeof e.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case M:return"Portal";case D:return e.displayName||"Context";case H:return(e._context.displayName||"Context")+".Consumer";case I:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case B:return null!==(t=e.displayName||null)?t:l(e.type)||"Memo";case z:t=e._payload,e=e._init;try{return l(e(t))}catch(e){}}return null}function d(e){if(e===P)return"<>";if("object"==typeof e&&null!==e&&e.$$typeof===z)return"<...>";try{var t=l(e);return t?"<"+t+">":"<...>"}catch(e){return"<...>"}}function h(){var e=Z.A;return null===e?null:e.getOwner()}function f(){return Error("react-stack-top-frame")}function p(e){if(ee.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}function m(){var e=l(this.type);return re[e]||(re[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(e=this.props.ref)?e:null}function y(e,t,r,n,s,o){var a=r.ref;return e={$$typeof:O,type:e,key:t,props:r,_owner:n},null!==(void 0!==a?a:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:m}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:s}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:o}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function g(e){b(e)?e._store&&(e._store.validated=1):"object"==typeof e&&null!==e&&e.$$typeof===z&&("fulfilled"===e._payload.status?b(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function b(e){return"object"==typeof e&&null!==e&&e.$$typeof===O}function v(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(u(e.key),r=""+e.key,n={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,(function(e){return n[e]}))):t.toString(36);var r,n}function w(e,t,r,n,s){var o=typeof e;"undefined"!==o&&"boolean"!==o||(e=null);var a,c,l,d=!1;if(null===e)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(e.$$typeof){case O:case M:d=!0;break;case z:return w((d=e._init)(e._payload),t,r,n,s)}}if(d){s=s(d=e);var h=""===n?"."+v(d,0):n;return K(s)?(r="",null!=h&&(r=h.replace(ae,"$&/")+"/"),w(s,t,r,"",(function(e){return e}))):null!=s&&(b(s)&&(null!=s.key&&(d&&d.key===s.key||u(s.key)),a=s,c=r+(null==s.key||d&&d.key===s.key?"":(""+s.key).replace(ae,"$&/")+"/")+h,c=y(a.type,c,a.props,a._owner,a._debugStack,a._debugTask),a._store&&(c._store.validated=a._store.validated),r=c,""!==n&&null!=d&&b(d)&&null==d.key&&d._store&&!d._store.validated&&(r._store.validated=2),s=r),t.push(s)),1}if(d=0,h=""===n?".":n+":",K(e))for(var f=0;f<e.length;f++)d+=w(n=e[f],t,r,o=h+v(n,f),s);else if("function"==typeof(f=null===(l=e)||"object"!=typeof l?null:"function"==typeof(l=Q&&l[Q]||l["@@iterator"])?l:null))for(f===e.entries&&(oe||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),oe=!0),e=f.call(e),f=0;!(n=e.next()).done;)d+=w(n=n.value,t,r,o=h+v(n,f++),s);else if("object"===o){if("function"==typeof e.then)return w(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(i,i):(e.status="pending",e.then((function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)}),(function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)}))),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(e),t,r,n,s);throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.")}return d}function S(e,t,r){if(null==e)return e;var n=[],s=0;return w(e,n,"","",(function(e){return t.call(r,e,s++)})),n}function E(e){if(-1===e._status){var t=e._ioInfo;null!=t&&(t.start=t.end=performance.now());var r=(t=e._result)();if(r.then((function(t){if(0===e._status||-1===e._status){e._status=1,e._result=t;var n=e._ioInfo;null!=n&&(n.end=performance.now()),void 0===r.status&&(r.status="fulfilled",r.value=t)}}),(function(t){if(0===e._status||-1===e._status){e._status=2,e._result=t;var n=e._ioInfo;null!=n&&(n.end=performance.now()),void 0===r.status&&(r.status="rejected",r.reason=t)}})),null!=(t=e._ioInfo)){t.value=r;var n=r.displayName;"string"==typeof n&&(t.name=n)}-1===e._status&&(e._status=0,e._result=r)}if(1===e._status)return void 0===(t=e._result)&&console.error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",t),"default"in t||console.error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))",t),t.default;throw e._result}function _(){var e=Z.H;return null===e&&console.error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."),e}function k(){Z.asyncTransitions--}function T(e){if(null===ue)try{var r=("require"+Math.random()).slice(0,7);ue=(t&&t[r]).call(t,"timers").setImmediate}catch(e){ue=function(e){!1===ce&&(ce=!0,"undefined"==typeof MessageChannel&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var t=new MessageChannel;t.port1.onmessage=e,t.port2.postMessage(void 0)}}return ue(e)}function C(e){return 1<e.length&&"function"==typeof AggregateError?new AggregateError(e):e[0]}function x(e,t){t!==le-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),le=t}function j(e,t,r){var n=Z.actQueue;if(null!==n)if(0!==n.length)try{return A(n),void T((function(){return j(e,t,r)}))}catch(e){Z.thrownErrors.push(e)}else Z.actQueue=null;0<Z.thrownErrors.length?(n=C(Z.thrownErrors),Z.thrownErrors.length=0,r(n)):t(e)}function A(e){if(!he){he=!0;var t=0;try{for(;t<e.length;t++)for(var r=e[t];;){Z.didUsePromise=!1;var n=r(!1);if(null===n)break;if(Z.didUsePromise)return e[t]=r,void e.splice(0,t);r=n}e.length=0}catch(r){e.splice(0,t+1),Z.thrownErrors.push(r)}finally{he=!1}}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var O=Symbol.for("react.transitional.element"),M=Symbol.for("react.portal"),P=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),$=Symbol.for("react.profiler"),H=Symbol.for("react.consumer"),D=Symbol.for("react.context"),I=Symbol.for("react.forward_ref"),L=Symbol.for("react.suspense"),U=Symbol.for("react.suspense_list"),B=Symbol.for("react.memo"),z=Symbol.for("react.lazy"),N=Symbol.for("react.activity"),Q=Symbol.iterator,F={},q={isMounted:function(){return!1},enqueueForceUpdate:function(e){n(e,"forceUpdate")},enqueueReplaceState:function(e){n(e,"replaceState")},enqueueSetState:function(e){n(e,"setState")}},V=Object.assign,W={};Object.freeze(W),s.prototype.isReactComponent={},s.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},s.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};var Y={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(pe in Y)Y.hasOwnProperty(pe)&&r(pe,Y[pe]);o.prototype=s.prototype,(Y=a.prototype=new o).constructor=a,V(Y,s.prototype),Y.isPureReactComponent=!0;var G,J,K=Array.isArray,X=Symbol.for("react.client.reference"),Z={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},ee=Object.prototype.hasOwnProperty,te=console.createTask?console.createTask:function(){return null},re={},ne=(Y={react_stack_bottom_frame:function(e){return e()}}).react_stack_bottom_frame.bind(Y,f)(),se=te(d(f)),oe=!1,ae=/\/+/g,ie="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},ce=!1,ue=null,le=0,de=!1,he=!1,fe="function"==typeof queueMicrotask?function(e){queueMicrotask((function(){return queueMicrotask(e)}))}:T;Y=Object.freeze({__proto__:null,c:function(e){return _().useMemoCache(e)}});var pe={map:S,forEach:function(e,t,r){S(e,(function(){t.apply(this,arguments)}),r)},count:function(e){var t=0;return S(e,(function(){t++})),t},toArray:function(e){return S(e,(function(e){return e}))||[]},only:function(e){if(!b(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};e.Activity=N,e.Children=pe,e.Component=s,e.Fragment=P,e.Profiler=$,e.PureComponent=a,e.StrictMode=R,e.Suspense=L,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Z,e.__COMPILER_RUNTIME=Y,e.act=function(e){var t=Z.actQueue,r=le;le++;var n=Z.actQueue=null!==t?t:[],s=!1;try{var o=e()}catch(e){Z.thrownErrors.push(e)}if(0<Z.thrownErrors.length)throw x(0,r),e=C(Z.thrownErrors),Z.thrownErrors.length=0,e;if(null!==o&&"object"==typeof o&&"function"==typeof o.then){var a=o;return fe((function(){s||de||(de=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))})),{then:function(e,t){s=!0,a.then((function(s){if(x(0,r),0===r){try{A(n),T((function(){return j(s,e,t)}))}catch(e){Z.thrownErrors.push(e)}if(0<Z.thrownErrors.length){var o=C(Z.thrownErrors);Z.thrownErrors.length=0,t(o)}}else e(s)}),(function(e){x(0,r),0<Z.thrownErrors.length?(e=C(Z.thrownErrors),Z.thrownErrors.length=0,t(e)):t(e)}))}}}var i=o;if(x(0,r),0===r&&(A(n),0!==n.length&&fe((function(){s||de||(de=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))})),Z.actQueue=null),0<Z.thrownErrors.length)throw e=C(Z.thrownErrors),Z.thrownErrors.length=0,e;return{then:function(e,t){s=!0,0===r?(Z.actQueue=n,T((function(){return j(i,e,t)}))):e(i)}}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.captureOwnerStack=function(){var e=Z.getCurrentStack;return null===e?null:e()},e.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var n,s=V({},e.props),o=e.key,a=e._owner;if(null!=t)for(i in(n=!(ee.call(t,"ref")&&(n=Object.getOwnPropertyDescriptor(t,"ref").get)&&n.isReactWarning)&&void 0!==t.ref)&&(a=h()),p(t)&&(u(t.key),o=""+t.key),t)!ee.call(t,i)||"key"===i||"__self"===i||"__source"===i||"ref"===i&&void 0===t.ref||(s[i]=t[i]);var i=arguments.length-2;if(1===i)s.children=r;else if(1<i){n=Array(i);for(var c=0;c<i;c++)n[c]=arguments[c+2];s.children=n}for(s=y(e.type,o,s,a,e._debugStack,e._debugTask),o=2;o<arguments.length;o++)g(arguments[o]);return s},e.createContext=function(e){return(e={$$typeof:D,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider=e,e.Consumer={$$typeof:H,_context:e},e._currentRenderer=null,e._currentRenderer2=null,e},e.createElement=function(e,t,r){for(var n=2;n<arguments.length;n++)g(arguments[n]);n={};var s=null;if(null!=t)for(c in J||!("__self"in t)||"key"in t||(J=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),p(t)&&(u(t.key),s=""+t.key),t)ee.call(t,c)&&"key"!==c&&"__self"!==c&&"__source"!==c&&(n[c]=t[c]);var o=arguments.length-2;if(1===o)n.children=r;else if(1<o){for(var a=Array(o),i=0;i<o;i++)a[i]=arguments[i+2];Object.freeze&&Object.freeze(a),n.children=a}if(e&&e.defaultProps)for(c in o=e.defaultProps)void 0===n[c]&&(n[c]=o[c]);s&&function(e,t){function r(){G||(G=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(n,"function"==typeof e?e.displayName||e.name||"Unknown":e);var c=1e4>Z.recentlyCreatedOwnerStacks++;return y(e,s,n,h(),c?Error("react-stack-top-frame"):ne,c?te(d(e)):se)},e.createRef=function(){var e={current:null};return Object.seal(e),e},e.forwardRef=function(e){null!=e&&e.$$typeof===B?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):"function"!=typeof e?console.error("forwardRef requires a render function but was given %s.",null===e?"null":typeof e):0!==e.length&&2!==e.length&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",1===e.length?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),null!=e&&null!=e.defaultProps&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var t,r={$$typeof:I,render:e};return Object.defineProperty(r,"displayName",{enumerable:!1,configurable:!0,get:function(){return t},set:function(r){t=r,e.name||e.displayName||(Object.defineProperty(e,"name",{value:r}),e.displayName=r)}}),r},e.isValidElement=b,e.lazy=function(e){var t={$$typeof:z,_payload:e={_status:-1,_result:e},_init:E},r={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return e._ioInfo=r,t._debugInfo=[{awaited:r}],t},e.memo=function(e,t){var r;return null==e&&console.error("memo: The first argument must be a component. Instead received: %s",null===e?"null":typeof e),t={$$typeof:B,type:e,compare:void 0===t?null:t},Object.defineProperty(t,"displayName",{enumerable:!1,configurable:!0,get:function(){return r},set:function(t){r=t,e.name||e.displayName||(Object.defineProperty(e,"name",{value:t}),e.displayName=t)}}),t},e.startTransition=function(e){var t=Z.T,r={};r._updatedFibers=new Set,Z.T=r;try{var n=e(),s=Z.S;null!==s&&s(r,n),"object"==typeof n&&null!==n&&"function"==typeof n.then&&(Z.asyncTransitions++,n.then(k,k),n.then(i,ie))}catch(e){ie(e)}finally{null===t&&r._updatedFibers&&(e=r._updatedFibers.size,r._updatedFibers.clear(),10<e&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),null!==t&&null!==r.types&&(null!==t.types&&t.types!==r.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),t.types=r.types),Z.T=t}},e.unstable_useCacheRefresh=function(){return _().useCacheRefresh()},e.use=function(e){return _().use(e)},e.useActionState=function(e,t,r){return _().useActionState(e,t,r)},e.useCallback=function(e,t){return _().useCallback(e,t)},e.useContext=function(e){var t=_();return e.$$typeof===H&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),t.useContext(e)},e.useDebugValue=function(e,t){return _().useDebugValue(e,t)},e.useDeferredValue=function(e,t){return _().useDeferredValue(e,t)},e.useEffect=function(e,t){return null==e&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),_().useEffect(e,t)},e.useEffectEvent=function(e){return _().useEffectEvent(e)},e.useId=function(){return _().useId()},e.useImperativeHandle=function(e,t,r){return _().useImperativeHandle(e,t,r)},e.useInsertionEffect=function(e,t){return null==e&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),_().useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return null==e&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),_().useLayoutEffect(e,t)},e.useMemo=function(e,t){return _().useMemo(e,t)},e.useOptimistic=function(e,t){return _().useOptimistic(e,t)},e.useReducer=function(e,t,r){return _().useReducer(e,t,r)},e.useRef=function(e){return _().useRef(e)},e.useState=function(e){return _().useState(e)},e.useSyncExternalStore=function(e,t,r){return _().useSyncExternalStore(e,t,r)},e.useTransition=function(){return _().useTransition()},e.version="19.2.0","undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()}}),h=i({"node_modules/.bun/react@19.2.0/node_modules/react/index.js"(e,t){"production"===process.env.NODE_ENV?t.exports=l():t.exports=d()}}),f=c(u()),p=Symbol.for("delete"),m=e=>Array.isArray(e)?[...e]:{...e};function y(e){const t=e?.deleteMarker||p;return function(e,r){if("object"!=typeof e||null===e)return"object"==typeof r&&null!==r?o(r):r===t?{}:r;if("object"!=typeof r||null===r)return e;const n=m(e),s=[{target:n,source:r}];for(;s.length>0;){const{target:e,source:r}=s.pop();for(const n of Object.keys(r)){if(!Object.prototype.hasOwnProperty.call(r,n))continue;const a=r[n];if(a!==t)if(Array.isArray(a))e[n]=a.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:o(e)));else if("object"==typeof a&&null!==a){const t=n in e&&"object"==typeof e[n]&&null!==e[n]?e[n]:{};e[n]=m(t),s.push({target:e[n],source:a})}else e[n]=a;else delete e[n]}}return n;function o(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:o(e)));if("object"==typeof e){const r={};for(const[n,s]of Object.entries(e))if(s!==t)if("object"==typeof s&&null!==s){const e=o(s);void 0!==e&&(r[n]=e)}else r[n]=s;return r}return e===t?void 0:e}}}var g=y();c(u());var b=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const r=v(e);this.validateSimpleSelector(e,r);const n=r.sort().join("|"),s=this.pathBasedCache.get(n);if(s)return this.reactiveSelectorCache.set(e,s),s;const o=`selector-${Math.random().toString(36).substring(2,9)}`,a=e(this.getState()),i={id:o,selector:e,lastResult:a,accessedPaths:r,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>i.lastResult,subscribe:t=>(i.subscribers.add(t),()=>{i.subscribers.delete(t),queueMicrotask((()=>{0===i.subscribers.size&&(this.reactiveSelectors.delete(o),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(n))}))}),id:o};return i.reactiveSelectorInstance=c,this.reactiveSelectors.set(o,i),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(n,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:o,accessedPaths:r,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const r=e.toString(),n=r.match(/=>\s*(.+)$/),s=n?n[1].trim():r,o=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of o)if(new RegExp(`\\.${e}\\s*\\(`).test(s))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(s))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(s))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(s))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const a=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(s),i=/\[.*\]/.test(s);if(a&&!i)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=v(e);this.validateSimpleSelector(e,t);let r,n=null;return s=>{const o=this.extractStateSubset(s,t);return n===o||(n=o,r=e(s)),r}}extractStateSubset(e,t){const r=[];for(const n of t){const t=n.split(".");let s=e;for(const e of t){if(null==s){r.push(void 0);break}s=s[e]}r.push(s)}return r}};function v(e,t="."){const r=new Set,n=(e=[])=>new Proxy({},{get:(s,o)=>{if("symbol"==typeof o)return;const a=[...e,o],i=a.join(t);return r.add(i),n(a)}});try{e(n())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const s=Array.from(r);return s.filter((e=>!s.some((r=>r!==e&&r.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let r,n;if(Array.isArray(e)){if(r=e.length,r!=t.length)return!1;for(n=r;n-- >0;)if(!w(e[n],t[n]))return!1;return!0}const[s,o]=[Object.keys(e),Object.keys(t)];if(r=s.length,r!==o.length)return!1;for(n=r;n-- >0;){const r=s[n];if(!Object.prototype.hasOwnProperty.call(t,r)||!w(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function S(e){const t=e?.deleteMarker||p;return function(e,r){const n=[],s=[{pathArray:[],pathStr:"",orig:e||{},part:r||{}}];for(;s.length>0;){const{pathArray:e,pathStr:r,orig:o,part:a}=s.pop();if(null!=a&&!w(o,a))if("object"!=typeof a||Array.isArray(a))r&&n.push({path:r,oldValue:o,newValue:a});else for(const i of Object.keys(a)){const c=[...e,i],u=r?r+"."+i:i,l=a[i],d=o&&"object"==typeof o?o[i]:void 0;l!==t?"object"==typeof l&&null!==l?s.push({pathArray:c,pathStr:u,orig:d,part:l}):w(d,l)||n.push({path:u,oldValue:d,newValue:l}):void 0===d&&o&&"object"==typeof o||n.push({path:u,oldValue:d,newValue:void 0})}}return n}}function E(e){const t=e?.deleteMarker||p;return function(e){const r=new Set,n=[{obj:e,currentPath:""}];for(;n.length>0;){const{obj:e,currentPath:s}=n.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const o of Object.keys(e)){const a=s?`${s}.${o}`:o;r.add(a);const i=a.split(".");if(i.length>1)for(let e=i.length-1;e>0;e--){const t=i.slice(0,e).join(".");if(r.has(t))break;r.add(t)}const c=e[o];"object"==typeof c&&null!==c&&c!==t&&n.push({obj:c,currentPath:a})}}return Array.from(r)}}var _=S(),k=E(),T=class{constructor(e,t,r){this.updateBus=t,this.diff=r,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,r=!1,n=[]){if(t)return this.cache=r?structuredClone(e):e,this.notifyListeners([]),[];0===n.length&&(n=[e]);const s=this.get(!1),o=new Map;for(let e=0;e<n.length;e++){const t=n[e],r=this.diff(s,t);for(let e=0;e<r.length;e++){const t=r[e];o.set(t.path,t)}}const a=o.size?[...o.values()]:[];if(a.length>0){this.cache=r?structuredClone(e):e;const t=new Set;for(let e=0;e<a.length;e++){let r=a[e].path;for(;r&&!t.has(r);){t.add(r);const e=r.lastIndexOf(".");if(e<0)break;r=r.slice(0,e)}}this.notifyListeners(t)}return a}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};c(u());var C=class{constructor(e,t,r){this.eventBus=e,this.executionState=t,this.merge=r}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:r,name:n,id:s}of this.blockingMiddleware){const o={id:s,name:n,startTime:performance.now()};this.executionState.runningMiddleware={id:s,name:n,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:s,name:n,type:"blocking"});try{const a=await Promise.resolve(r(e,t));if(o.endTime=performance.now(),o.duration=o.endTime-o.startTime,!1===a)return o.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:s,name:n,duration:o.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:o}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:s,name:n,type:"blocking",duration:o.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...o,blocked:!1}})}catch(e){return o.endTime=performance.now(),o.duration=o.endTime-o.startTime,o.error=e instanceof Error?e:new Error(String(e)),o.blocked=!0,this.emitMiddlewareError(s,n,o.error,o.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:o}),{blocked:!0,error:o.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let r=e,n=t;for(const{fn:e,name:s,id:o}of this.middleware){const a={id:o,name:s,startTime:performance.now()};this.executionState.runningMiddleware={id:o,name:s,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:o,name:s,type:"transform"});try{const i=await Promise.resolve(e(r,t));a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.blocked=!1,i&&"object"==typeof i&&(r=this.merge(r,i),n=this.merge(n,i)),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),this.emitMiddlewareLifecycle("complete",{id:o,name:s,type:"transform",duration:a.duration})}catch(e){a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:a}),this.emitMiddlewareError(o,s,a.error,a.duration),console.error(`Middleware ${s} error:`,e)}finally{this.executionState.runningMiddleware=null}}return n}addMiddleware(e,t="unnamed-middleware"){const r=this.generateId();return this.middleware.push({fn:e,name:t,id:r}),this.updateExecutionState(),r}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const r=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:r}),this.updateExecutionState(),r}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,r,n){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:r,duration:n,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};c(u());var x=class{constructor(e,t,r,n){this.eventBus=e,this.coreState=t,this.instanceID=r,this.maxRetries=n?.maxRetries??3,this.retryDelay=n?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const r={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(r),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:r.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:r.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const r=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:r,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),r)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};c(u());var j=class{constructor(e,t,r){this.eventBus=e,this.coreState=t,this.executionState=r}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};c(u());var A=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=r=>(this.totalEventsFired++,t.call(e,r)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};c(u());var O=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},M=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(t){const r=t.debounce,n={name:t.name,id:e(),action:t.fn,debounce:r?{...r,condition:r.condition||(()=>!0)}:void 0};return this.actions.set(t.name,n),()=>{const e=this.actions.get(t.name);e?.debounce?.timer&&clearTimeout(e.debounce.timer),this.actions.delete(t.name)}}async dispatch(e,...t){const r=this.actions.get(e);if(!r)throw new Error(`unknown action ${e}`);const{id:n,action:s,debounce:o}=r;return!o||void 0===o.delay||o.delay<=0||o.condition&&!o.condition(o.args,t)?this.executeAction(e,n,s,t):(o.timer&&(clearTimeout(o.timer),o.reject?.(new O)),new Promise(((r,a)=>{o.resolve=r,o.reject=a,o.timer=setTimeout((async()=>{o.timer=void 0,o.resolve=void 0,o.reject=void 0;try{const o=await this.executeAction(e,n,s,t);r(o)}catch(e){a(e)}}),o.delay)})))}async executeAction(e,t,r,n){const s=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:n||[],timestamp:s}});try{const o=await this.set((e=>r(e,...n)),{actionId:t}),a=this.actions.get(e);a?.debounce&&(a.debounce.args=n);const i=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:n,startTime:s,endTime:i,duration:i-s,result:o}}),o}catch(r){const o=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:n,startTime:s,endTime:o,duration:o-s,error:r}}),r}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},P=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,f.createEventBus)();eventBus=(0,f.createEventBus)();executionState;instanceID=e();merge;diff;constructor(e,t,r=p,n){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=y({deleteMarker:r}),this.diff=S({deleteMarker:r}),this.coreState=new T(e,this.updateBus,this.diff),this.middlewareEngine=new C(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new x(this.eventBus,this.coreState,this.instanceID,{maxRetries:n?.persistenceMaxRetries,retryDelay:n?.persistenceRetryDelay}),this.transactionManager=new j(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new A(this.eventBus),this.actionManager=new M(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new b(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const r=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=r.catch((()=>{})),r}async _performUpdate(e,t){this.executionState.executing=!0;const r=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:r,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),r="function"==typeof e?e(t):e;return this.coreState.applyChanges(r,!0),r}let n;const s=this.get(!1);if("function"==typeof e){const t=e(s);n=t instanceof Promise?await t:t}else n=e;const o=await this.middlewareEngine.executeBlocking(s,n);if(o.blocked)throw o.error||new Error("Update blocked by middleware");const a=this.merge(s,n),i=await this.middlewareEngine.executeTransform(a,n),c=this.merge(a,i),u=this.coreState.applyChanges(c,!1,!1,[n,i]),l=performance.now(),d=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:u,duration:l-r,timestamp:Date.now(),actionId:t.actionId,newState:d}}),d}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const r=Array.isArray(e)?e:[e],n=""===e||0===r.length;return this.updateBus.subscribe("update",(e=>{(n||r.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},R=(e=>(e.Singleton="singleton",e.Transient="transient",e))(R||{}),$=class{artifacts=new Map;resolvingStack=[];listeners=new Map;getState;subscribe;constructor(e){this.getState=(...t)=>e.get(...t),this.subscribe=(...t)=>e.watch(...t)}subscribeToArtifact(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const r=this.listeners.get(e);return r.add(t),()=>r.delete(t)}get(e){return this.artifacts.get(e)?.instance}notifyListeners(e){const t=this.listeners.get(e);t&&t.forEach((e=>e()))}register(e){const{key:t,factory:r,scope:n="singleton",lazy:s=!0}=e;this.artifacts.has(t)&&(console.warn(`[ArtifactContainer] Warning: Overwriting existing artifact "${t}".`),this.disposeArtifact(t));const o={key:t,factory:r,scope:n,lazy:s,stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set};return this.artifacts.set(t,o),s||"singleton"!==n||this.resolve(t).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${t}":`,e)})),async()=>{await this.unregister(t)}}async unregister(e){this.artifacts.has(e)&&(await this.disposeArtifact(e),this.artifacts.delete(e))}async resolve(e){if(this.resolvingStack.includes(e))throw new Error(`[ArtifactContainer] Circular dependency: ${this.resolvingStack.join(" -> ")} -> ${e}`);this.resolvingStack.push(e);try{const t=this.artifacts.get(e);if(!t)throw new Error(`[ArtifactContainer] Artifact with key "${e}" not found.`);if("transient"===t.scope)return this.createArtifactInstance(t,new Set,new Set);if(void 0!==t.instance)return t.instance;if(t.initializationPromise)return t.initializationPromise;const r=(async()=>{try{const e=new Set,r=new Set,n=await this.createArtifactInstance(t,e,r);return this.updateGraph(t,e,r),n}catch(e){throw t.initializationPromise=void 0,e}})();return t.initializationPromise=r,await r}finally{this.resolvingStack.pop()}}async createArtifactInstance(e,t,r){const n={state:this.getState,current:e.instance,use:async n=>n({resolve:async r=>{if(r===e.key)throw new Error(`[ArtifactContainer] Self-dependency detected in "${e.key}"`);return t.add(r),this.resolve(r)},select:e=>(v(e).forEach((e=>r.add(e))),e(this.getState()))})},s=await e.factory(n);let o,a;return Array.isArray(s)?[o,a]=s:o=s,"singleton"===e.scope?(e.instance=o,e.instanceCleanup=a):a&&console.warn(`[ArtifactContainer] Cleanup function returned for Transient artifact "${e.key}" will be ignored.`),o}updateGraph(e,t,r){e.artifactDependencies.forEach((t=>{const r=this.artifacts.get(t);r&&r.dependents.delete(e.key)})),e.artifactDependencies=t,t.forEach((t=>{const r=this.artifacts.get(t);r&&r.dependents.add(e.key)})),e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.stateDependencies=r,r.size>0&&(e.stateSubscriptionCleanup=this.subscribe(Array.from(r),(()=>this.invalidate(e.key)))),this.detectCycles(e.key),this.notifyListeners(e.key)}async invalidate(e){const t=this.artifacts.get(e);if(!t||void 0===t.instance)return;await this.disposeInstance(t);const r=Array.from(t.dependents);for(const e of r)await this.invalidate(e);t.lazy||this.resolve(e).catch((t=>{console.error(`[ArtifactContainer] Eager rebuild failed for "${e}":`,t)}))}async disposeInstance(e){if(e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.instanceCleanup){const t=e.instanceCleanup;await Promise.resolve().then((()=>t())).catch((t=>console.error(`[ArtifactContainer] Cleanup error for "${e.key}":`,t)))}e.instance=void 0,e.instanceCleanup=void 0,e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{const r=this.artifacts.get(t);r&&r.dependents.delete(e)})))}detectCycles(e){const t=new Set,r=new Set,n=e=>{if(r.has(e))throw new Error(`[ArtifactContainer] Circular dependency: ${Array.from(r).join(" -> ")} -> ${e}`);if(t.has(e))return;t.add(e),r.add(e);const s=this.artifacts.get(e);s&&s.artifactDependencies.forEach((e=>n(e))),r.delete(e)};n(e)}dispose(){this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear()}isLoading(e){return this.resolvingStack.includes(e)||void 0!==this.artifacts.get(e)?.initializationPromise}},H=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(r=>{"update:complete"!==t||r.blocked||this.isTimeTraveling||this.recordStateSnapshot(r.deltas),"middleware:executed"===t?this.middlewareExecutions.push(r):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),r.batchId&&(t.endsWith("start")?this.activeBatches.add(r.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(r.batchId)),this.recordEvent(t,r),this.enableConsoleLogging&&e&&this._log(t,r),this._checkPerformance(t,r)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const r={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(r),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:r=!0}=e;return(e,n)=>{if(r){(console[t]||console.log)("State Update:",n)}return n}}createValidationMiddleware(e){return(t,r)=>{const n=e(t,r);return"boolean"==typeof n?n:(!n.valid&&n.reason&&this._consoleLog("warn","Validation failed:",n.reason),n.valid)}}getRecentChanges(e=5){const t=[],r=Math.min(e,this.stateHistory.length);for(let e=0;e<r;e++){const r=this.stateHistory[e];if(!r.deltas||0===r.deltas.length)continue;const n={},s={},o=(e,t,r)=>{t.reduce(((e,n,s)=>(s===t.length-1?e[n]=r:e[n]=e[n]??{},e[n])),e)};for(const e of r.deltas){const t=e.path.split(".");o(n,t,e.oldValue),o(s,t,e.newValue)}t.push({timestamp:r.timestamp,changedPaths:r.deltas.map((e=>e.path)),from:n,to:s})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const r=this.store.onStoreEvent("update:complete",(r=>{this.isTimeTraveling||r.blocked||(t=[],e=0)}));this.unsubscribers.push(r);const n=()=>this.stateHistory.length,s=()=>e<n()-1,o=()=>t.length>0;return{canUndo:s,canRedo:o,undo:async()=>{if(!s())return;t.unshift(this.stateHistory[e]),e++;const r=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...r},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!o())return;const r=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...r.state},{force:!0}),this.isTimeTraveling=!1},length:n,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),r={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,r))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=`store-observer-session-${(new Date).toISOString()}.json`,n.click(),URL.revokeObjectURL(r)}importSession(e){return new Promise(((t,r)=>{const n=new FileReader;n.onload=async e=>{try{const r=JSON.parse(e.target?.result);this.eventHistory=r.eventHistory||[],this.stateHistory=r.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){r(e)}},n.onerror=e=>r(e),n.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const r=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${r}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${r}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${r}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${r}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${r}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${r}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${r}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${r}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${r}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${r}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${r}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${r}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${r}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${r}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}},D=c(h()),I=class{executions=[];maxHistory=100;listeners=new Set;track(e){this.executions.unshift(e),this.executions.length>this.maxHistory&&this.executions.pop(),this.notify()}getExecutions(){return[...this.executions]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){this.listeners.forEach((e=>e()))}};function L(e,{enableMetrics:t,...r}={}){const n=new P(e.state,r.persistence),s=Object.keys(e.actions).reduce(((e,t)=>(e[t]=!1,e)),{}),o=new P(s),a=t?new H(n,r):void 0,i=t?new I:void 0;t&&i&&(n.on("action:start",(({name:e})=>{o.set((()=>({[e]:!0})))})),n.on("action:complete",(e=>{o.set((()=>({[e.name]:!1}))),i.track({id:e.actionId,name:e.name,params:e.params,startTime:e.startTime,endTime:e.endTime,duration:e.duration,status:"success",result:e.result})})),n.on("action:error",(e=>{o.set((()=>({[e.name]:!1}))),i.track({id:e.actionId,name:e.name,params:e.params,startTime:e.startTime,endTime:e.endTime,duration:e.duration,status:"error",error:e.error})}))),e.middleware&&Object.entries(e.middleware).forEach((([e,t])=>n.use({name:e,action:t}))),e.blockingMiddleware&&Object.entries(e.blockingMiddleware).forEach((([e,t])=>n.use({block:!0,name:e,action:t})));const c=e=>(n.isReady()&&e(),n.on("persistence:ready",e)),u=()=>n.isReady(),l=new $(n);e.artifacts&&Object.entries(e.artifacts).forEach((([e,t])=>{l.register({key:e,factory:t.factory,scope:t.scope,lazy:t.lazy})}));const d=Object.entries(e.actions).reduce(((e,[t,r])=>(n.register({name:t,fn:(e,...t)=>{const n={state:e,resolve:l.resolve.bind(l)};return r(n,...t)}}),e[t]=(...e)=>n.dispatch(t,...e),e)),{});return function(){const e=()=>(0,D.useSyncExternalStore)((e=>n.watch("",e)),(()=>n.get()),(()=>n.get())),t=(0,D.useSyncExternalStore)(c,u,u);return{store:n,observer:a,select:e=>{const t=n.select(e);return(0,D.useSyncExternalStore)((e=>t.subscribe(e)),(()=>t.get()),(()=>t.get()))},actions:d,isReady:t,actionTracker:i,watch:e=>(0,D.useSyncExternalStore)((t=>o.watch(e,t)),(()=>!!o.get()[e]),(()=>!!o.get()[e])),resolve:e=>{const t=(0,D.useSyncExternalStore)((t=>l.subscribeToArtifact(e,t)),(()=>l.get(e)),(()=>l.get(e)));(0,D.useEffect)((()=>{void 0!==t||l.isLoading(e)||l.resolve(e).catch(console.error)}),[e,t]);return[t,null!=t]},get state(){return e}}}}
2
- /*! Bundled license information:
3
-
4
- react/cjs/react.production.js:
5
- (**
6
- * @license React
7
- * react.production.js
8
- *
9
- * Copyright (c) Meta Platforms, Inc. and affiliates.
10
- *
11
- * This source code is licensed under the MIT license found in the
12
- * LICENSE file in the root directory of this source tree.
13
- *)
14
-
15
- react/cjs/react.development.js:
16
- (**
17
- * @license React
18
- * react.development.js
19
- *
20
- * Copyright (c) Meta Platforms, Inc. and affiliates.
21
- *
22
- * This source code is licensed under the MIT license found in the
23
- * LICENSE file in the root directory of this source tree.
24
- *)
25
- */export{M as ActionManager,$ as ArtifactContainer,R as ArtifactScope,p as DELETE_SYMBOL,P as ReactiveDataStore,H as StoreObserver,E as createDerivePaths,S as createDiff,y as createMerge,L as createStore,k as derivePaths,_ as diff,g as merge,m as shallowClone};
1
+ import{v4 as e}from"uuid";var t,s,i=Object.create,r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,s)=>(s=null!=e?i(o(e)):{},((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of n(t))c.call(e,o)||o===s||r(e,o,{get:()=>t[o],enumerable:!(i=a(t,o))||i.enumerable});return e})(e&&e.__esModule?s:r(s,"default",{value:e,enumerable:!0}),e)),d=(t={"src/store/node_modules/@asaidimu/events/index.js"(e,t){var s,i=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||i(e,c,{get:()=>t[c],enumerable:!(o=r(t,c))||o.enumerable});return e})(i({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],i=0,r=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{i++,r+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(i){e.errorHandler({...i,eventName:t,payload:s})}c(t,performance.now()-i)}))},d=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),h=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const i=t.get(e);return i.add(s),h(e),()=>{i.delete(s),0===i.size?(t.delete(e),n.delete(e)):h(e)}},emit:({name:t,payload:i})=>{if(e.async)return s.push({name:t,payload:i}),s.length>=e.batchSize?l():d(),void(o&&o.postMessage({name:t,payload:i}));const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(i))),o&&o.postMessage({name:t,payload:i})}catch(s){e.errorHandler({...s,eventName:t,payload:i})}c(t,performance.now()-r)},getMetrics:()=>({totalEvents:i,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:i>0?r/i:0}),clear:()=>{t.clear(),n.clear(),s=[],i=0,r=0,a.clear(),o&&(o.close(),o=null)}}}}},function(){return s||(0,t[n(t)[0]])((s={exports:{}}).exports,s),s.exports}),h=l(d()),u=Symbol.for("delete"),p=e=>Array.isArray(e)?[...e]:{...e};function m(e){const t=e?.deleteMarker||u;return function(e,s){if("object"!=typeof e||null===e)return"object"==typeof s&&null!==s?a(s):s===t?{}:s;if("object"!=typeof s||null===s)return e;const i=p(e),r=[{target:i,source:s}];for(;r.length>0;){const{target:e,source:s}=r.pop();for(const i of Object.keys(s)){if(!Object.prototype.hasOwnProperty.call(s,i))continue;const n=s[i];if(n!==t)if(Array.isArray(n))e[i]=n.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));else if("object"==typeof n&&null!==n){const t=i in e&&"object"==typeof e[i]&&null!==e[i]?e[i]:{};e[i]=p(t),r.push({target:e[i],source:n})}else e[i]=n;else delete e[i]}}return i;function a(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));if("object"==typeof e){const s={};for(const[i,r]of Object.entries(e))if(r!==t)if("object"==typeof r&&null!==r){const e=a(r);void 0!==e&&(s[i]=e)}else s[i]=r;return s}return e===t?void 0:e}}}var f=m();l(d());var g=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const s=y(e);this.validateSimpleSelector(e,s);const i=s.sort().join("|"),r=this.pathBasedCache.get(i);if(r)return this.reactiveSelectorCache.set(e,r),r;const a=`selector-${Math.random().toString(36).substring(2,9)}`,n=e(this.getState()),o={id:a,selector:e,lastResult:n,accessedPaths:s,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>o.lastResult,subscribe:t=>(o.subscribers.add(t),()=>{o.subscribers.delete(t),queueMicrotask((()=>{0===o.subscribers.size&&(this.reactiveSelectors.delete(a),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(i))}))}),id:a};return o.reactiveSelectorInstance=c,this.reactiveSelectors.set(a,o),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(i,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:a,accessedPaths:s,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const s=e.toString(),i=s.match(/=>\s*(.+)$/),r=i?i[1].trim():s,a=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of a)if(new RegExp(`\\.${e}\\s*\\(`).test(r))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(r))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(r))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(r))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const n=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(r),o=/\[.*\]/.test(r);if(n&&!o)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=y(e);this.validateSimpleSelector(e,t);let s,i=null;return r=>{const a=this.extractStateSubset(r,t);return i===a||(i=a,s=e(r)),s}}extractStateSubset(e,t){const s=[];for(const i of t){const t=i.split(".");let r=e;for(const e of t){if(null==r){s.push(void 0);break}r=r[e]}s.push(r)}return s}};function y(e,t="."){const s=new Set,i=(e=[])=>new Proxy({},{get:(r,a)=>{if("symbol"==typeof a)return;const n=[...e,a],o=n.join(t);return s.add(o),i(n)}});try{e(i())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const r=Array.from(s);return r.filter((e=>!r.some((s=>s!==e&&s.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let s,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(i=s;i-- >0;)if(!w(e[i],t[i]))return!1;return!0}const[r,a]=[Object.keys(e),Object.keys(t)];if(s=r.length,s!==a.length)return!1;for(i=s;i-- >0;){const s=r[i];if(!Object.prototype.hasOwnProperty.call(t,s)||!w(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}function v(e){const t=e?.deleteMarker||u;return function(e,s){const i=[],r=[{pathArray:[],pathStr:"",orig:e||{},part:s||{}}];for(;r.length>0;){const{pathArray:e,pathStr:s,orig:a,part:n}=r.pop();if(null!=n&&!w(a,n))if("object"!=typeof n||Array.isArray(n))s&&i.push({path:s,oldValue:a,newValue:n});else for(const o of Object.keys(n)){const c=[...e,o],l=s?s+"."+o:o,d=n[o],h=a&&"object"==typeof a?a[o]:void 0;d!==t?"object"==typeof d&&null!==d?r.push({pathArray:c,pathStr:l,orig:h,part:d}):w(h,d)||i.push({path:l,oldValue:h,newValue:d}):void 0===h&&a&&"object"==typeof a||i.push({path:l,oldValue:h,newValue:void 0})}}return i}}function b(e){const t=e?.deleteMarker||u;return function(e){const s=new Set,i=[{obj:e,currentPath:""}];for(;i.length>0;){const{obj:e,currentPath:r}=i.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const a of Object.keys(e)){const n=r?`${r}.${a}`:a;s.add(n);const o=n.split(".");if(o.length>1)for(let e=o.length-1;e>0;e--){const t=o.slice(0,e).join(".");if(s.has(t))break;s.add(t)}const c=e[a];"object"==typeof c&&null!==c&&c!==t&&i.push({obj:c,currentPath:n})}}return Array.from(s)}}var S=v(),E=b(),k=class{constructor(e,t,s){this.updateBus=t,this.diff=s,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,s=!1,i=[]){if(t)return this.cache=s?structuredClone(e):e,this.notifyListeners([]),[];0===i.length&&(i=[e]);const r=this.get(!1),a=new Map;for(let e=0;e<i.length;e++){const t=i[e],s=this.diff(r,t);for(let e=0;e<s.length;e++){const t=s[e];a.set(t.path,t)}}const n=a.size?[...a.values()]:[];if(n.length>0){this.cache=s?structuredClone(e):e;const t=new Set;for(let e=0;e<n.length;e++){let s=n[e].path;for(;s&&!t.has(s);){t.add(s);const e=s.lastIndexOf(".");if(e<0)break;s=s.slice(0,e)}}this.notifyListeners(t)}return n}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};l(d());var x=class{constructor(e,t,s){this.eventBus=e,this.executionState=t,this.merge=s}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:s,name:i,id:r}of this.blockingMiddleware){const a={id:r,name:i,startTime:performance.now()};this.executionState.runningMiddleware={id:r,name:i,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:r,name:i,type:"blocking"});try{const n=await Promise.resolve(s(e,t));if(a.endTime=performance.now(),a.duration=a.endTime-a.startTime,!1===n)return a.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:r,name:i,duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:r,name:i,type:"blocking",duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...a,blocked:!1}})}catch(e){return a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!0,this.emitMiddlewareError(r,i,a.error,a.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0,error:a.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let s=e,i=t;for(const{fn:e,name:r,id:a}of this.middleware){const n={id:a,name:r,startTime:performance.now()};this.executionState.runningMiddleware={id:a,name:r,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:a,name:r,type:"transform"});try{const o=await Promise.resolve(e(s,t));n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.blocked=!1,o&&"object"==typeof o&&(s=this.merge(s,o),i=this.merge(i,o)),this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareLifecycle("complete",{id:a,name:r,type:"transform",duration:n.duration})}catch(e){n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.error=e instanceof Error?e:new Error(String(e)),n.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareError(a,r,n.error,n.duration),console.error(`Middleware ${r} error:`,e)}finally{this.executionState.runningMiddleware=null}}return i}addMiddleware(e,t="unnamed-middleware"){const s=this.generateId();return this.middleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const s=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,s,i){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:s,duration:i,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var T=class{constructor(e,t,s,i){this.eventBus=e,this.coreState=t,this.instanceID=s,this.maxRetries=i?.maxRetries??3,this.retryDelay=i?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const s={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(s),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:s.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:s.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const s=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:s,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),s)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var C=class{constructor(e,t,s){this.eventBus=e,this.coreState=t,this.executionState=s}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var A=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=s=>(this.totalEventsFired++,t.call(e,s)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};l(d());var P=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},M=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(t){const s=t.debounce,i={name:t.name,id:e(),action:t.fn,debounce:s?{...s,condition:s.condition||(()=>!0)}:void 0};return this.actions.set(t.name,i),()=>{const e=this.actions.get(t.name);e?.debounce?.timer&&clearTimeout(e.debounce.timer),this.actions.delete(t.name)}}async dispatch(e,...t){const s=this.actions.get(e);if(!s)throw new Error(`unknown action ${e}`);const{id:i,action:r,debounce:a}=s;return!a||void 0===a.delay||a.delay<=0||a.condition&&!a.condition(a.args,t)?this.executeAction(e,i,r,t):(a.timer&&(clearTimeout(a.timer),a.reject?.(new P)),new Promise(((s,n)=>{a.resolve=s,a.reject=n,a.timer=setTimeout((async()=>{a.timer=void 0,a.resolve=void 0,a.reject=void 0;try{const a=await this.executeAction(e,i,r,t);s(a)}catch(e){n(e)}}),a.delay)})))}async executeAction(e,t,s,i){const r=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:i||[],timestamp:r}});try{const a=await this.set((e=>s(e,...i)),{actionId:t}),n=this.actions.get(e);n?.debounce&&(n.debounce.args=i);const o=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:i,startTime:r,endTime:o,duration:o-r,result:a}}),a}catch(s){const a=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:i,startTime:r,endTime:a,duration:a-r,error:s}}),s}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},B=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,h.createEventBus)();eventBus=(0,h.createEventBus)();executionState;instanceID=e();merge;diff;constructor(e,t,s=u,i){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=m({deleteMarker:s}),this.diff=v({deleteMarker:s}),this.coreState=new k(e,this.updateBus,this.diff),this.middlewareEngine=new x(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new T(this.eventBus,this.coreState,this.instanceID,{maxRetries:i?.persistenceMaxRetries,retryDelay:i?.persistenceRetryDelay}),this.transactionManager=new C(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new A(this.eventBus),this.actionManager=new M(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new g(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const s=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=s.catch((()=>{})),s}async _performUpdate(e,t){this.executionState.executing=!0;const s=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:s,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),s="function"==typeof e?e(t):e;return this.coreState.applyChanges(s,!0),s}let i;const r=this.get(!1);if("function"==typeof e){const t=e(r);i=t instanceof Promise?await t:t}else i=e;const a=await this.middlewareEngine.executeBlocking(r,i);if(a.blocked)throw a.error||new Error("Update blocked by middleware");const n=this.merge(r,i),o=await this.middlewareEngine.executeTransform(n,i),c=this.merge(n,o),l=this.coreState.applyChanges(c,!1,!1,[i,o]),d=performance.now(),h=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:l,duration:d-s,timestamp:Date.now(),actionId:t.actionId,newState:h}}),h}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const s=Array.isArray(e)?e:[e],i=""===e||0===s.length;return this.updateBus.subscribe("update",(e=>{(i||s.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},D=(e=>(e.Singleton="singleton",e.Transient="transient",e))(D||{}),H=class{artifacts=new Map;resolvingStack=[];listeners=new Map;getState;subscribe;constructor(e){this.getState=(...t)=>e.get(...t),this.subscribe=(...t)=>e.watch(...t)}watch(e){return{id:e,get:()=>{const t=this.artifacts.get(e);return t&&(void 0!==t.instance||t.error)?this.packageArtifact(t):null},subscribe:t=>{this.listeners.has(e)||this.listeners.set(e,new Set);const s=this.listeners.get(e);return s.add(t),()=>s.delete(t)}}}get(e){return this.artifacts.get(e)?.instance}register(e){const{key:t,factory:s,scope:i="singleton",lazy:r=!0}=e;this.artifacts.has(t)&&(console.warn(`[ArtifactContainer] Warning: Overwriting existing artifact "${t}".`),this.disposeArtifact(t));const a={key:t,factory:s,scope:i,lazy:r,cleanupFunctions:[],stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set};return this.artifacts.set(t,a),r||"singleton"!==i||this.resolve(t).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${t}":`,e)})),async()=>{await this.unregister(t)}}async unregister(e){this.artifacts.has(e)&&(await this.disposeArtifact(e),this.artifacts.delete(e))}async resolve(e){if(this.resolvingStack.includes(e))throw new Error(`[ArtifactContainer] Circular dependency: ${this.resolvingStack.join(" -> ")} -> ${e}`);this.resolvingStack.push(e);try{const t=this.artifacts.get(e);if(!t)throw new Error(`[ArtifactContainer] Artifact with key "${e}" not found.`);if("transient"===t.scope){const e=await this.createArtifactInstance(t,new Set,new Set);return{instance:e.instance,cleanup:e.cleanup,error:e.error,invalidate:async()=>{}}}if(void 0!==t.instance||void 0!==t.error)return this.packageArtifact(t);if(t.initializationPromise)try{return await t.initializationPromise,this.packageArtifact(t)}catch(e){return this.packageArtifact(t)}const s=(async()=>{try{const e=new Set,s=new Set,i=await this.createArtifactInstance(t,e,s);return this.updateGraph(t,e,s),i.error&&(t.error=i.error),i.instance}catch(e){throw t.error=e,t.initializationPromise=void 0,e}})();t.initializationPromise=s;try{await s}catch(e){}return this.packageArtifact(t)}finally{this.resolvingStack.pop()}}packageArtifact(e){return{instance:e.instance,cleanup:this.createCompositeCleanup(e.cleanupFunctions),error:e.error,invalidate:async t=>this.invalidate(e.key,t)}}async createArtifactInstance(e,t,s){const i=[];let r=!0;i.push((()=>{r=!1}));const a={state:this.getState,current:e.instance,use:async i=>i({resolve:async s=>{if(s===e.key)throw new Error(`[ArtifactContainer] Self-dependency detected in "${e.key}"`);return t.add(s),this.resolve(s)},select:e=>(y(e).forEach((e=>s.add(e))),e(this.getState()))}),onCleanup:e=>{i.push(e)},yield:t=>{r?"transient"!==e.scope?(e.instance=t,e.error=void 0,this.processYieldPropagation(e.key)):console.warn(`[ArtifactContainer] Yield ignored on transient artifact "${e.key}"`):console.warn(`[ArtifactContainer] Ignored yield on disposed artifact "${e.key}"`)}};let n,o;try{n=await e.factory(a)}catch(e){o=e,n=void 0}"singleton"===e.scope&&(void 0!==n&&(e.instance=n),e.cleanupFunctions=i);return{instance:"singleton"===e.scope?e.instance:n,cleanup:this.createCompositeCleanup(i),error:o}}async processYieldPropagation(e){const t=this.artifacts.get(e);if(t&&(void 0!==t.instance||t.error))try{const s=Array.from(t.dependents);await Promise.all(s.map((e=>this.invalidate(e,!1)))),this.notifyListeners(e)}catch(t){console.error(`[ArtifactContainer] Yield propagation failed for "${e}":`,t)}}updateGraph(e,t,s){e.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e.key)})),e.artifactDependencies=t,t.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.add(e.key)}));const i=e.stateSubscriptionCleanup;e.stateDependencies=s,s.size>0?e.stateSubscriptionCleanup=this.subscribe(Array.from(s),(()=>this.invalidate(e.key))):e.stateSubscriptionCleanup=void 0,i&&i(),this.detectCycles(e.key),this.notifyListeners(e.key)}async invalidate(e,t=!1){const s=this.artifacts.get(e);if(!s)return;if(s.initializationPromise)try{await s.initializationPromise}catch(e){}if(s.rebuildPromise)return s.rebuildPromise;const i=(async()=>{try{const i=Array.from(s.dependents);await Promise.all(i.map((e=>this.invalidate(e,t)))),await this.disposeInstance(s),!t&&s.lazy||await this.resolve(e).catch((t=>{console.error(`[ArtifactContainer] Rebuild failed for "${e}":`,t)}))}finally{s.rebuildPromise=void 0}})();return s.rebuildPromise=i,i}async disposeInstance(e){if(e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.cleanupFunctions.length>0)for(let t=e.cleanupFunctions.length-1;t>=0;t--)try{await e.cleanupFunctions[t]()}catch(t){console.error(`[ArtifactContainer] Cleanup error for "${e.key}":`,t)}e.instance=void 0,e.error=void 0,e.cleanupFunctions=[],e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(t.rebuildPromise&&await t.rebuildPromise,await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e)})))}createCompositeCleanup(e){if(0!==e.length)return async()=>{for(let t=e.length-1;t>=0;t--)try{await e[t]()}catch(e){}}}notifyListeners(e){const t=this.listeners.get(e);t&&t.forEach((e=>e()))}detectCycles(e){const t=new Set,s=new Set,i=e=>{if(s.has(e))throw new Error(`[ArtifactContainer] Circular dependency: ${Array.from(s).join(" -> ")} -> ${e}`);if(t.has(e))return;t.add(e),s.add(e);const r=this.artifacts.get(e);r&&r.artifactDependencies.forEach((e=>i(e))),s.delete(e)};i(e)}dispose(){this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear()}isLoading(e){return this.resolvingStack.includes(e)||void 0!==this.artifacts.get(e)?.initializationPromise}},L=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(s=>{"update:complete"!==t||s.blocked||this.isTimeTraveling||this.recordStateSnapshot(s.deltas),"middleware:executed"===t?this.middlewareExecutions.push(s):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),s.batchId&&(t.endsWith("start")?this.activeBatches.add(s.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(s.batchId)),this.recordEvent(t,s),this.enableConsoleLogging&&e&&this._log(t,s),this._checkPerformance(t,s)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const s={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(s),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:s=!0}=e;return(e,i)=>{if(s){(console[t]||console.log)("State Update:",i)}return i}}createValidationMiddleware(e){return(t,s)=>{const i=e(t,s);return"boolean"==typeof i?i:(!i.valid&&i.reason&&this._consoleLog("warn","Validation failed:",i.reason),i.valid)}}getRecentChanges(e=5){const t=[],s=Math.min(e,this.stateHistory.length);for(let e=0;e<s;e++){const s=this.stateHistory[e];if(!s.deltas||0===s.deltas.length)continue;const i={},r={},a=(e,t,s)=>{t.reduce(((e,i,r)=>(r===t.length-1?e[i]=s:e[i]=e[i]??{},e[i])),e)};for(const e of s.deltas){const t=e.path.split(".");a(i,t,e.oldValue),a(r,t,e.newValue)}t.push({timestamp:s.timestamp,changedPaths:s.deltas.map((e=>e.path)),from:i,to:r})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const s=this.store.onStoreEvent("update:complete",(s=>{this.isTimeTraveling||s.blocked||(t=[],e=0)}));this.unsubscribers.push(s);const i=()=>this.stateHistory.length,r=()=>e<i()-1,a=()=>t.length>0;return{canUndo:r,canRedo:a,undo:async()=>{if(!r())return;t.unshift(this.stateHistory[e]),e++;const s=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...s},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!a())return;const s=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...s.state},{force:!0}),this.isTimeTraveling=!1},length:i,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),s={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,s))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(t),i=document.createElement("a");i.href=s,i.download=`store-observer-session-${(new Date).toISOString()}.json`,i.click(),URL.revokeObjectURL(s)}importSession(e){return new Promise(((t,s)=>{const i=new FileReader;i.onload=async e=>{try{const s=JSON.parse(e.target?.result);this.eventHistory=s.eventHistory||[],this.stateHistory=s.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){s(e)}},i.onerror=e=>s(e),i.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const s=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${s}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${s}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${s}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${s}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${s}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${s}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${s}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${s}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${s}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${s}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${s}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}};export{M as ActionManager,H as ArtifactContainer,D as ArtifactScope,u as DELETE_SYMBOL,B as ReactiveDataStore,L as StoreObserver,b as createDerivePaths,v as createDiff,m as createMerge,E as derivePaths,S as diff,f as merge,p as shallowClone};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/utils-store",
3
- "version": "4.0.0",
3
+ "version": "5.0.0",
4
4
  "description": "A reactive data store",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",