@blac/react 2.0.0-rc-6 → 2.0.0-rc-8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -14
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.es.js +348 -124
- package/dist/index.es.js.map +1 -1
- package/package.json +2 -2
- package/src/DependencyTracker.ts +350 -0
- package/src/useBloc.tsx +76 -43
- package/src/useExternalBlocStore.ts +145 -45
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/useExternalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["import { Blac, BlacObserver, BlocBase, BlocBaseAbstract, BlocConstructor, BlocHookDependencyArrayFn, BlocState, generateUUID } from '@blac/core';\nimport { useCallback, useMemo, useRef } from 'react';\nimport { BlocHookOptions } from './useBloc';\n\nexport interface ExternalStore<\n B extends BlocConstructor<BlocBase<any>>\n> {\n /**\n * Subscribes to changes in the store and returns an unsubscribe function.\n * @param onStoreChange - Callback function that will be called whenever the store changes\n * @returns A function that can be called to unsubscribe from store changes\n */\n subscribe: (onStoreChange: (state: BlocState<InstanceType<B>>) => void) => () => void;\n\n /**\n * Gets the current snapshot of the store state.\n * @returns The current state of the store\n */\n getSnapshot: () => BlocState<InstanceType<B>> | undefined;\n\n /**\n * Gets the server snapshot of the store state.\n * This is optional and defaults to the same value as getSnapshot.\n * @returns The server state of the store\n */\n getServerSnapshot?: () => BlocState<InstanceType<B>> | undefined;\n}\n\nexport interface ExternalBlacStore<\n B extends BlocConstructor<BlocBase<any>>\n> {\n usedKeys: React.RefObject<Set<string>>;\n usedClassPropKeys: React.RefObject<Set<string>>;\n externalStore: ExternalStore<B>;\n instance: React.RefObject<InstanceType<B>>;\n rid: string;\n}\n\n/**\n * Creates an external store that wraps a Bloc instance, providing a React-compatible interface\n * for subscribing to and accessing bloc state.\n */\nconst useExternalBlocStore = <\n B extends BlocConstructor<BlocBase<any>>\n>(\n bloc: B,\n options: BlocHookOptions<InstanceType<B>> | undefined,\n): ExternalBlacStore<B> => {\n const { id: blocId, props, selector } = options ?? {};\n\n const rid = useMemo(() => {\n return generateUUID();\n }, []);\n\n const base = bloc as unknown as BlocBaseAbstract;\n\n const isIsolated = base.isolated;\n const effectiveBlocId = isIsolated ? rid : blocId;\n\n const usedKeys = useRef<Set<string>>(new Set());\n const usedClassPropKeys = useRef<Set<string>>(new Set());\n\n const getBloc = useCallback(() => {\n return Blac.getBloc(bloc, {\n id: effectiveBlocId,\n props,\n instanceRef: rid\n });\n }, [bloc, effectiveBlocId, props, rid]);\n\n const blocInstance = useRef<InstanceType<B>>(getBloc());\n\n // Update the instance when dependencies change\n useMemo(() => {\n blocInstance.current = getBloc();\n }, [getBloc]);\n\n const dependencyArray: BlocHookDependencyArrayFn<BlocState<InstanceType<B>>> =\n useMemo(\n () =>\n (newState): ReturnType<BlocHookDependencyArrayFn<BlocState<InstanceType<B>>>> => {\n const instance = blocInstance.current;\n\n if (!instance) {\n return [];\n }\n\n // Use custom dependency selector if provided\n if (selector) {\n return selector(newState);\n }\n\n // Fall back to bloc's default dependency selector if available\n if (instance.defaultDependencySelector) {\n return instance.defaultDependencySelector(newState);\n }\n\n // For primitive states, use default selector\n if (typeof newState !== 'object') {\n // Default behavior for primitive states: re-render if the state itself changes.\n return [[newState]];\n }\n\n // For object states, track which properties were actually used\n const usedStateValues: unknown[] = [];\n for (const key of usedKeys.current) {\n if (key in newState) {\n usedStateValues.push(newState[key as keyof typeof newState]);\n }\n }\n\n // Track used class properties for dependency tracking, this enables rerenders when class getters change\n const usedClassValues: unknown[] = [];\n for (const key of usedClassPropKeys.current) {\n if (key in instance) {\n try {\n const value = instance[key as keyof InstanceType<B>];\n switch (typeof value) {\n case 'function':\n continue;\n default:\n usedClassValues.push(value);\n continue;\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n }\n }\n\n // If no state properties have been accessed, return empty dependencies to prevent re-renders\n // Class properties can change independently of state\n if (usedKeys.current.size === 0) {\n return usedClassPropKeys.current.size > 0 ? [usedClassValues] : [[]];\n }\n\n return [usedStateValues, usedClassValues];\n },\n [],\n );\n\n const state: ExternalStore<B> = useMemo(() => {\n return {\n subscribe: (listener: (state: BlocState<InstanceType<B>>) => void) => {\n const currentInstance = blocInstance.current;\n if (!currentInstance) {\n return () => {}; // Return no-op if no instance\n }\n\n const observer: BlacObserver<BlocState<InstanceType<B>>> = {\n fn: () => {\n try {\n // Reset dependency tracking before listener is called \n // This ensures we only track properties accessed during the current render\n usedKeys.current = new Set();\n usedClassPropKeys.current = new Set();\n\n // Only trigger listener if there are actual subscriptions\n listener(currentInstance.state);\n } catch (e) {\n // Log any errors that occur during the listener callback\n // This ensures errors in listeners don't break the entire application\n console.error({\n e,\n blocInstance: currentInstance,\n dependencyArray,\n });\n }\n },\n // Pass the dependency array to control when the subscription is updated\n dependencyArray,\n // Use the provided id to identify this subscription\n id: rid,\n }\n\n Blac.activateBloc(currentInstance);\n\n // Subscribe to the bloc's observer with the provided listener function\n // This will trigger the callback whenever the bloc's state changes\n const unSub = currentInstance._observer.subscribe(observer);\n\n // Return an unsubscribe function that can be called to clean up the subscription\n return () => {\n unSub();\n };\n },\n // Return an immutable snapshot of the current bloc state\n getSnapshot: (): BlocState<InstanceType<B>> | undefined => {\n const instance = blocInstance.current;\n if (!instance) {\n return {} as BlocState<InstanceType<B>>;\n }\n return instance.state;\n },\n // Server snapshot mirrors the client snapshot in this implementation\n getServerSnapshot: (): BlocState<InstanceType<B>> | undefined => {\n const instance = blocInstance.current;\n if (!instance) {\n return {} as BlocState<InstanceType<B>>;\n }\n return instance.state;\n },\n }\n }, [blocInstance.current?.uid]); // Re-create store when instance changes\n\n return {\n usedKeys,\n usedClassPropKeys,\n externalStore: state,\n instance: blocInstance,\n rid,\n };\n};\n\nexport default useExternalBlocStore;\n","import {\n BlocBase,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport {\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore\n} from 'react';\nimport useExternalBlocStore from './useExternalBlocStore';\n\n/**\n * Type definition for the return type of the useBloc hook\n * @template B - Bloc constructor type\n */\ntype HookTypes<B extends BlocConstructor<BlocBase<any>>> = [\n BlocState<InstanceType<B>> | undefined,\n InstanceType<B> | null,\n];\n\n/**\n * Configuration options for the useBloc hook\n */\nexport interface BlocHookOptions<B extends BlocBase<any>> {\n id?: string;\n selector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n onUnmount?: (bloc: B) => void;\n}\n\n/**\n * Default dependency selector that wraps the entire state in an array\n * @template T - State type\n * @returns {Array<Array<T>>} Dependency array containing the entire state\n */\n\n/**\n * React hook for integrating with Blac state management\n *\n * This hook connects a React component to a Bloc state container, providing\n * automatic re-rendering when relevant state changes, dependency tracking,\n * and proper lifecycle management.\n *\n * @template B - Bloc constructor type\n * @template O - BlocHookOptions type\n * @param {B} bloc - Bloc constructor class\n * @param {O} [options] - Configuration options for the hook\n * @returns {HookTypes<B>} Tuple containing [state, bloc instance]\n *\n * @example\n * const [state, counterBloc] = useBloc(CounterBloc);\n * // Access state\n * console.log(state.count);\n * // Call bloc methods\n * counterBloc.increment();\n */\nexport default function useBloc<B extends BlocConstructor<BlocBase<any>>>(\n bloc: B,\n options?: BlocHookOptions<InstanceType<B>>,\n): HookTypes<B> {\n // Determine ID for isolated or shared blocs\n // const base = bloc as unknown as BlocBaseAbstract;\n // const isIsolated = base.isolated;\n // const effectiveBlocId = isIsolated ? rid : blocId;\n const {\n externalStore,\n usedKeys,\n usedClassPropKeys,\n instance,\n rid,\n } = useExternalBlocStore(bloc, options);\n\n // Subscribe to state changes using React's external store API\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n externalStore.subscribe,\n () => {\n const snapshot = externalStore.getSnapshot();\n if (snapshot === undefined) {\n throw new Error(`[useBloc] State snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`);\n }\n return snapshot;\n },\n externalStore.getServerSnapshot ? () => {\n const serverSnapshot = externalStore.getServerSnapshot!();\n if (serverSnapshot === undefined) {\n throw new Error(`[useBloc] Server state snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`);\n }\n return serverSnapshot;\n } : undefined,\n );\n\n // Cache proxies to avoid recreation on every render\n const stateProxyCache = useRef<WeakMap<object, object>>(new WeakMap());\n const classProxyCache = useRef<WeakMap<object, object>>(new WeakMap());\n\n const returnState = useMemo(() => {\n if (typeof state !== 'object' || state === null) {\n return state;\n }\n\n // Check cache first\n let proxy = stateProxyCache.current.get(state);\n if (!proxy) {\n proxy = new Proxy(state, {\n get(target, prop) {\n // Use setTimeout to defer dependency tracking until after render\n setTimeout(() => {\n usedKeys.current.add(prop as string);\n }, 0);\n const value = target[prop as keyof typeof target];\n return value;\n },\n // Handle symbols and non-enumerable properties\n has(target, prop) {\n return prop in target;\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n }\n });\n stateProxyCache.current.set(state as object, proxy as object);\n }\n return proxy;\n }, [state]);\n\n const returnClass = useMemo(() => {\n if (!instance.current) {\n return null;\n }\n\n // Check cache first\n let proxy = classProxyCache.current.get(instance.current);\n if (!proxy) {\n proxy = new Proxy(instance.current, {\n get(target, prop) {\n if (!target) {\n return null;\n }\n const value = target[prop as keyof InstanceType<B>];\n if (typeof value !== 'function') {\n usedClassPropKeys.current.add(prop as string);\n }\n return value;\n },\n });\n classProxyCache.current.set(instance.current, proxy);\n }\n return proxy;\n }, [instance.current?.uid]);\n\n // Create a stable reference object for this component\n const componentRef = useRef({});\n\n // Set up bloc lifecycle management\n useEffect(() => {\n const currentInstance = instance.current;\n if (!currentInstance) return;\n \n // Pass component reference for proper memory management\n currentInstance._addConsumer(rid, componentRef.current);\n\n // Call onMount callback if provided\n options?.onMount?.(currentInstance);\n\n // Cleanup: remove this component as a consumer using the captured instance\n return () => {\n if (!currentInstance) {\n return;\n }\n options?.onUnmount?.(currentInstance);\n currentInstance._removeConsumer(rid);\n };\n }, [instance.current?.uid, rid]); // Use UID to ensure we re-run when instance changes\n\n // Safe return with proper typing\n return [returnState, returnClass] as [BlocState<InstanceType<B>>, InstanceType<B>];\n}\n"],"names":["useExternalBlocStore","bloc","options","blocId","props","selector","rid","useMemo","generateUUID","effectiveBlocId","usedKeys","useRef","usedClassPropKeys","getBloc","useCallback","Blac","blocInstance","dependencyArray","newState","instance","usedStateValues","key","usedClassValues","value","error","state","listener","currentInstance","observer","e","unSub","_a","useBloc","externalStore","useSyncExternalStore","snapshot","serverSnapshot","stateProxyCache","classProxyCache","returnState","proxy","target","prop","returnClass","componentRef","useEffect","_b"],"mappings":";;AA0CM,MAAAA,IAAuB,CAG3BC,GACAC,MACyB;;AACzB,QAAM,EAAE,IAAIC,GAAQ,OAAAC,GAAO,UAAAC,EAAS,IAAIH,KAAW,CAAC,GAE9CI,IAAMC,EAAQ,MACXC,EAAa,GACnB,EAAE,GAKCC,IAHOR,EAEW,WACaK,IAAMH,GAErCO,IAAWC,EAAwB,oBAAA,KAAK,GACxCC,IAAoBD,EAAwB,oBAAA,KAAK,GAEjDE,IAAUC,EAAY,MACnBC,EAAK,QAAQd,GAAM;AAAA,IACxB,IAAIQ;AAAA,IACJ,OAAAL;AAAA,IACA,aAAaE;AAAA,EAAA,CACd,GACA,CAACL,GAAMQ,GAAiBL,GAAOE,CAAG,CAAC,GAEhCU,IAAeL,EAAwBE,GAAS;AAGtD,EAAAN,EAAQ,MAAM;AACZ,IAAAS,EAAa,UAAUH,EAAQ;AAAA,EAAA,GAC9B,CAACA,CAAO,CAAC;AAEZ,QAAMI,IACJV;AAAA,IACE,MACE,CAACW,MAAgF;AAC/E,YAAMC,IAAWH,EAAa;AAE9B,UAA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KQ;AAGW,aAAAA,EAAA,aAAarB,GAAKsC,EAAa,OAAO,IAGtDb,IAAA7B,KAAA,gBAAAA,EAAS,YAAT,QAAA6B,EAAA,KAAA7B,GAAmByB,IAGZ,MAAM;;AACX,QAAKA,OAGLI,IAAA7B,KAAA,gBAAAA,EAAS,cAAT,QAAA6B,EAAA,KAAA7B,GAAqByB,IACrBA,EAAgB,gBAAgBrB,CAAG;AAAA,MACrC;AAAA,KACC,EAACwC,IAAA3B,EAAS,YAAT,gBAAA2B,EAAkB,KAAKxC,CAAG,CAAC,GAGxB,CAACiC,GAAaI,CAAW;AAClC;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/useExternalBlocStore.ts","../src/DependencyTracker.ts","../src/useBloc.tsx"],"sourcesContent":["import { Blac, BlacObserver, BlocBase, BlocBaseAbstract, BlocConstructor, BlocHookDependencyArrayFn, BlocState, generateUUID } from '@blac/core';\nimport { useCallback, useMemo, useRef } from 'react';\nimport { BlocHookOptions } from './useBloc';\n\nexport interface ExternalStore<\n B extends BlocConstructor<BlocBase<any>>\n> {\n /**\n * Subscribes to changes in the store and returns an unsubscribe function.\n * @param onStoreChange - Callback function that will be called whenever the store changes\n * @returns A function that can be called to unsubscribe from store changes\n */\n subscribe: (onStoreChange: (state: BlocState<InstanceType<B>>) => void) => () => void;\n\n /**\n * Gets the current snapshot of the store state.\n * @returns The current state of the store\n */\n getSnapshot: () => BlocState<InstanceType<B>> | undefined;\n\n /**\n * Gets the server snapshot of the store state.\n * This is optional and defaults to the same value as getSnapshot.\n * @returns The server state of the store\n */\n getServerSnapshot?: () => BlocState<InstanceType<B>> | undefined;\n}\n\nexport interface ExternalBlacStore<\n B extends BlocConstructor<BlocBase<any>>\n> {\n usedKeys: React.RefObject<Set<string>>;\n usedClassPropKeys: React.RefObject<Set<string>>;\n externalStore: ExternalStore<B>;\n instance: React.RefObject<InstanceType<B>>;\n rid: string;\n hasProxyTracking: React.RefObject<boolean>;\n}\n\n/**\n * Creates an external store that wraps a Bloc instance, providing a React-compatible interface\n * for subscribing to and accessing bloc state.\n */\nconst useExternalBlocStore = <\n B extends BlocConstructor<BlocBase<any>>\n>(\n bloc: B,\n options: BlocHookOptions<InstanceType<B>> | undefined,\n): ExternalBlacStore<B> => {\n const { id: blocId, props, selector } = options ?? {};\n\n const rid = useMemo(() => {\n return generateUUID();\n }, []);\n\n const base = bloc as unknown as BlocBaseAbstract;\n\n const isIsolated = base.isolated;\n const effectiveBlocId = isIsolated ? rid : blocId;\n\n const usedKeys = useRef<Set<string>>(new Set());\n const usedClassPropKeys = useRef<Set<string>>(new Set());\n \n // Track whether proxy-based dependency tracking has been initialized\n // This helps distinguish between direct external store usage and useBloc proxy usage\n const hasProxyTracking = useRef<boolean>(false);\n\n const getBloc = useCallback(() => {\n return Blac.getBloc(bloc, {\n id: effectiveBlocId,\n props,\n instanceRef: rid\n });\n }, [bloc, effectiveBlocId, props, rid]);\n\n const blocInstance = useRef<InstanceType<B>>(getBloc());\n\n // Update the instance when dependencies change\n useMemo(() => {\n blocInstance.current = getBloc();\n }, [getBloc]);\n\n // Track previous state and dependencies for selector\n const previousStateRef = useRef<BlocState<InstanceType<B>> | undefined>(undefined);\n const lastDependenciesRef = useRef<unknown[][] | undefined>(undefined);\n const lastStableSnapshot = useRef<BlocState<InstanceType<B>> | undefined>(undefined);\n \n // Track bloc instance uid to prevent unnecessary store recreation\n const blocUidRef = useRef<string | undefined>(undefined);\n if (blocUidRef.current !== blocInstance.current?.uid) {\n blocUidRef.current = blocInstance.current?.uid;\n }\n\n const dependencyArray = useMemo(\n () =>\n (newState: BlocState<InstanceType<B>>, oldState?: BlocState<InstanceType<B>>): unknown[][] => {\n const instance = blocInstance.current;\n\n if (!instance) {\n return [[], []]; // [stateArray, classArray]\n }\n\n // Use the provided oldState or fall back to our tracked previous state\n const previousState = oldState ?? previousStateRef.current;\n \n let currentDependencies: unknown[][];\n\n // Use custom dependency selector if provided\n if (selector) {\n const flatDeps = selector(newState, previousState, instance);\n // Wrap flat custom selector result in the two-array structure for consistency\n currentDependencies = [flatDeps, []]; // [customSelectorDeps, classArray]\n }\n // Fall back to bloc's default dependency selector if available\n else if (instance.defaultDependencySelector) {\n const flatDeps = instance.defaultDependencySelector(newState, previousState, instance);\n // Wrap flat default selector result in the two-array structure for consistency\n currentDependencies = [flatDeps, []]; // [defaultSelectorDeps, classArray]\n }\n // For primitive states, use default selector\n else if (typeof newState !== 'object') {\n // Default behavior for primitive states: re-render if the state itself changes.\n currentDependencies = [[newState], []]; // [primitiveStateArray, classArray]\n }\n else {\n // For object states, track which properties were actually used\n const stateDependencies: unknown[] = [];\n const classDependencies: unknown[] = [];\n \n // Add state property values that were accessed\n for (const key of usedKeys.current) {\n if (key in newState) {\n stateDependencies.push(newState[key as keyof typeof newState]);\n }\n }\n\n // Add class property values that were accessed\n for (const key of usedClassPropKeys.current) {\n if (key in instance) {\n try {\n const value = instance[key as keyof InstanceType<B>];\n if (typeof value !== 'function') {\n classDependencies.push(value);\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n }\n }\n\n // If no properties have been accessed through proxy\n if (usedKeys.current.size === 0 && usedClassPropKeys.current.size === 0) {\n // If proxy tracking has never been initialized, this is direct external store usage\n // In this case, always track the entire state to ensure notifications\n if (!hasProxyTracking.current) {\n stateDependencies.push(newState);\n }\n // If proxy tracking was initialized but no properties accessed, \n // return empty dependencies to prevent unnecessary re-renders\n }\n\n currentDependencies = [stateDependencies, classDependencies];\n }\n\n // Update tracked state\n previousStateRef.current = newState;\n\n\n // Return the dependencies for BlacObserver to compare\n return currentDependencies;\n },\n [],\n );\n\n // Store active subscriptions to reuse observers\n const activeObservers = useRef<Map<Function, { observer: BlacObserver<BlocState<InstanceType<B>>>, unsubscribe: () => void }>>(new Map());\n\n const state: ExternalStore<B> = useMemo(() => {\n return {\n subscribe: (listener: (state: BlocState<InstanceType<B>>) => void) => {\n \n const currentInstance = blocInstance.current;\n if (!currentInstance) {\n return () => {}; // Return no-op if no instance\n }\n\n // Check if we already have an observer for this listener\n const existing = activeObservers.current.get(listener);\n if (existing) {\n return existing.unsubscribe;\n }\n const observer: BlacObserver<BlocState<InstanceType<B>>> = {\n fn: () => {\n try {\n \n // Only reset dependency tracking if we're not using a custom selector\n // Custom selectors override proxy-based tracking entirely\n if (!selector && !currentInstance.defaultDependencySelector) {\n usedKeys.current = new Set();\n usedClassPropKeys.current = new Set();\n }\n\n // Only trigger listener if there are actual subscriptions\n listener(currentInstance.state);\n } catch (e) {\n // Log any errors that occur during the listener callback\n // This ensures errors in listeners don't break the entire application\n console.error({\n e,\n blocInstance: currentInstance,\n dependencyArray,\n });\n }\n },\n // Pass the dependency array to control when the subscription is updated\n dependencyArray,\n // Use the provided id to identify this subscription\n id: rid,\n }\n\n Blac.activateBloc(currentInstance);\n\n // Subscribe to the bloc's observer with the provided listener function\n // This will trigger the callback whenever the bloc's state changes\n const unSub = currentInstance._observer.subscribe(observer);\n\n const unsubscribe = () => {\n activeObservers.current.delete(listener);\n unSub();\n };\n\n // Store the observer and unsubscribe function\n activeObservers.current.set(listener, { observer, unsubscribe });\n\n // Return an unsubscribe function that can be called to clean up the subscription\n return unsubscribe;\n },\n // Return an immutable snapshot of the current bloc state\n getSnapshot: (): BlocState<InstanceType<B>> | undefined => {\n const instance = blocInstance.current;\n if (!instance) {\n return {} as BlocState<InstanceType<B>>;\n }\n\n const currentState = instance.state;\n const currentDependencies = dependencyArray(currentState, previousStateRef.current);\n \n // Check if dependencies have changed using the two-array comparison logic\n const lastDeps = lastDependenciesRef.current;\n let dependenciesChanged = false;\n \n if (!lastDeps) {\n // First time - dependencies changed\n dependenciesChanged = true;\n } else if (lastDeps.length !== currentDependencies.length) {\n // Array structure changed\n dependenciesChanged = true;\n } else {\n // Compare each array (state and class dependencies)\n for (let arrayIndex = 0; arrayIndex < currentDependencies.length; arrayIndex++) {\n const lastArray = lastDeps[arrayIndex] || [];\n const newArray = currentDependencies[arrayIndex] || [];\n \n if (lastArray.length !== newArray.length) {\n dependenciesChanged = true;\n break;\n }\n \n // Compare each dependency value using Object.is\n for (let i = 0; i < newArray.length; i++) {\n if (!Object.is(lastArray[i], newArray[i])) {\n dependenciesChanged = true;\n break;\n }\n }\n \n if (dependenciesChanged) break;\n }\n }\n \n // Update dependency tracking\n lastDependenciesRef.current = currentDependencies;\n \n // If dependencies haven't changed, return the same snapshot reference\n // This prevents React from re-rendering when dependencies are stable\n if (!dependenciesChanged && lastStableSnapshot.current) {\n return lastStableSnapshot.current;\n }\n \n // Dependencies changed - update and return new snapshot\n lastStableSnapshot.current = currentState;\n return currentState;\n },\n // Server snapshot mirrors the client snapshot in this implementation\n getServerSnapshot: (): BlocState<InstanceType<B>> | undefined => {\n const instance = blocInstance.current;\n if (!instance) {\n return {} as BlocState<InstanceType<B>>;\n }\n return instance.state;\n },\n }\n }, []); // Store is stable - individual methods handle instance changes\n\n return {\n usedKeys,\n usedClassPropKeys,\n externalStore: state,\n instance: blocInstance,\n rid,\n hasProxyTracking,\n };\n};\n\nexport default useExternalBlocStore;\n","\nexport interface DependencyMetrics {\n stateAccessCount: number;\n classAccessCount: number;\n proxyCreationCount: number;\n batchFlushCount: number;\n averageResolutionTime: number;\n memoryUsageKB: number;\n}\n\nexport interface DependencyTrackerConfig {\n enableBatching: boolean;\n batchTimeout: number;\n enableMetrics: boolean;\n maxCacheSize: number;\n enableDeepTracking: boolean;\n}\n\nexport type DependencyChangeCallback = (changedKeys: Set<string>) => void;\n\nexport class DependencyTracker {\n private stateKeys = new Set<string>();\n private classKeys = new Set<string>();\n private batchedCallbacks = new Set<DependencyChangeCallback>();\n private flushScheduled = false;\n private flushTimeoutId: ReturnType<typeof setTimeout> | undefined;\n \n private metrics: DependencyMetrics = {\n stateAccessCount: 0,\n classAccessCount: 0,\n proxyCreationCount: 0,\n batchFlushCount: 0,\n averageResolutionTime: 0,\n memoryUsageKB: 0,\n };\n \n private resolutionTimes: number[] = [];\n \n private config: DependencyTrackerConfig;\n \n private stateProxyCache = new WeakMap<object, object>();\n private classProxyCache = new WeakMap<object, object>();\n \n private lastStateSnapshot: unknown = null;\n private lastClassSnapshot: unknown = null;\n \n constructor(config: Partial<DependencyTrackerConfig> = {}) {\n this.config = {\n enableBatching: true,\n batchTimeout: 0, // Use React's scheduler\n enableMetrics: process.env.NODE_ENV === 'development',\n maxCacheSize: 1000,\n enableDeepTracking: false,\n ...config,\n };\n }\n\n public trackStateAccess(key: string): void {\n if (this.config.enableMetrics) {\n this.metrics.stateAccessCount++;\n }\n \n this.stateKeys.add(key);\n \n if (this.config.enableBatching) {\n this.scheduleFlush();\n }\n }\n\n public trackClassAccess(key: string): void {\n if (this.config.enableMetrics) {\n this.metrics.classAccessCount++;\n }\n \n this.classKeys.add(key);\n \n if (this.config.enableBatching) {\n this.scheduleFlush();\n }\n }\n\n public createStateProxy<T extends object>(target: T, onAccess?: (prop: string) => void): T {\n const cachedProxy = this.stateProxyCache.get(target);\n if (cachedProxy) {\n return cachedProxy as T;\n }\n\n const startTime = this.config.enableMetrics ? performance.now() : 0;\n\n const proxy = new Proxy(target, {\n get: (obj: T, prop: string | symbol) => {\n if (typeof prop === 'string') {\n this.trackStateAccess(prop);\n onAccess?.(prop);\n }\n \n const value = obj[prop as keyof T];\n \n if (\n this.config.enableDeepTracking &&\n value &&\n typeof value === 'object' &&\n !Array.isArray(value)\n ) {\n return this.createStateProxy(value as object);\n }\n \n return value;\n },\n \n has: (obj: T, prop: string | symbol) => {\n return prop in obj;\n },\n \n ownKeys: (obj: T) => {\n return Reflect.ownKeys(obj);\n },\n \n getOwnPropertyDescriptor: (obj: T, prop: string | symbol) => {\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n });\n\n this.stateProxyCache.set(target, proxy);\n \n if (this.config.enableMetrics) {\n this.metrics.proxyCreationCount++;\n const endTime = performance.now();\n this.resolutionTimes.push(endTime - startTime);\n this.updateAverageResolutionTime();\n }\n\n return proxy;\n }\n\n public createClassProxy<T extends object>(target: T, onAccess?: (prop: string) => void): T {\n const cachedProxy = this.classProxyCache.get(target);\n if (cachedProxy) {\n return cachedProxy as T;\n }\n\n const startTime = this.config.enableMetrics ? performance.now() : 0;\n\n const proxy = new Proxy(target, {\n get: (obj: T, prop: string | symbol) => {\n const value = obj[prop as keyof T];\n \n if (typeof prop === 'string' && typeof value !== 'function') {\n this.trackClassAccess(prop);\n onAccess?.(prop);\n }\n \n return value;\n },\n });\n\n this.classProxyCache.set(target, proxy);\n \n if (this.config.enableMetrics) {\n this.metrics.proxyCreationCount++;\n const endTime = performance.now();\n this.resolutionTimes.push(endTime - startTime);\n this.updateAverageResolutionTime();\n }\n\n return proxy;\n }\n\n public getStateKeys(): Set<string> {\n return new Set(this.stateKeys);\n }\n\n public getClassKeys(): Set<string> {\n return new Set(this.classKeys);\n }\n\n public reset(): void {\n this.stateKeys.clear();\n this.classKeys.clear();\n this.cancelScheduledFlush();\n }\n\n public subscribe(callback: DependencyChangeCallback): () => void {\n this.batchedCallbacks.add(callback);\n \n return () => {\n this.batchedCallbacks.delete(callback);\n };\n }\n\n public computeDependencyArray<TState, TClass>(\n state: TState,\n classInstance: TClass,\n ): unknown[] {\n const startTime = this.config.enableMetrics ? performance.now() : 0;\n \n if (typeof state !== 'object' || state === null) {\n return [[state]];\n }\n\n const stateValues: unknown[] = [];\n for (const key of this.stateKeys) {\n if (key in (state as object)) {\n stateValues.push((state as any)[key]);\n }\n }\n\n const classValues: unknown[] = [];\n for (const key of this.classKeys) {\n if (key in (classInstance as object)) {\n try {\n const value = (classInstance as any)[key];\n if (typeof value !== 'function') {\n classValues.push(value);\n }\n } catch (error) {\n }\n }\n }\n\n if (this.config.enableMetrics) {\n const endTime = performance.now();\n this.resolutionTimes.push(endTime - startTime);\n this.updateAverageResolutionTime();\n }\n\n if (stateValues.length === 0 && classValues.length === 0) {\n return [[]];\n }\n \n if (classValues.length === 0) {\n return [stateValues];\n }\n \n if (stateValues.length === 0) {\n return [classValues];\n }\n \n return [stateValues, classValues];\n }\n\n public getMetrics(): DependencyMetrics {\n if (!this.config.enableMetrics) {\n return {\n stateAccessCount: 0,\n classAccessCount: 0,\n proxyCreationCount: 0,\n batchFlushCount: 0,\n averageResolutionTime: 0,\n memoryUsageKB: 0,\n };\n }\n\n const estimatedMemory = \n (this.stateKeys.size * 50) +\n (this.classKeys.size * 50) +\n (this.stateProxyCache instanceof WeakMap ? 100 : 0) +\n (this.classProxyCache instanceof WeakMap ? 100 : 0);\n\n return {\n ...this.metrics,\n memoryUsageKB: Math.round(estimatedMemory / 1024),\n };\n }\n\n public clearCaches(): void {\n this.stateProxyCache = new WeakMap();\n this.classProxyCache = new WeakMap();\n this.resolutionTimes = [];\n \n if (this.config.enableMetrics) {\n this.metrics = {\n stateAccessCount: 0,\n classAccessCount: 0,\n proxyCreationCount: 0,\n batchFlushCount: 0,\n averageResolutionTime: 0,\n memoryUsageKB: 0,\n };\n }\n }\n\n private scheduleFlush(): void {\n if (this.flushScheduled) {\n return;\n }\n\n this.flushScheduled = true;\n\n if (this.config.batchTimeout > 0) {\n this.flushTimeoutId = setTimeout(() => {\n this.flushBatchedChanges();\n }, this.config.batchTimeout);\n } else {\n Promise.resolve().then(() => this.flushBatchedChanges());\n }\n }\n\n private cancelScheduledFlush(): void {\n if (this.flushTimeoutId) {\n clearTimeout(this.flushTimeoutId);\n this.flushTimeoutId = undefined;\n }\n this.flushScheduled = false;\n }\n\n private flushBatchedChanges(): void {\n if (!this.flushScheduled) {\n return;\n }\n\n this.flushScheduled = false;\n this.flushTimeoutId = undefined;\n\n if (this.config.enableMetrics) {\n this.metrics.batchFlushCount++;\n }\n\n const allChangedKeys = new Set([...this.stateKeys, ...this.classKeys]);\n \n for (const callback of this.batchedCallbacks) {\n try {\n callback(allChangedKeys);\n } catch (error) {\n console.error('Error in dependency change callback:', error);\n }\n }\n }\n\n private updateAverageResolutionTime(): void {\n if (this.resolutionTimes.length === 0) {\n return;\n }\n\n if (this.resolutionTimes.length > 100) {\n this.resolutionTimes = this.resolutionTimes.slice(-100);\n }\n\n const sum = this.resolutionTimes.reduce((a, b) => a + b, 0);\n this.metrics.averageResolutionTime = sum / this.resolutionTimes.length;\n }\n}\n\nexport function createDependencyTracker(\n config?: Partial<DependencyTrackerConfig>,\n): DependencyTracker {\n return new DependencyTracker(config);\n}\n\nexport const defaultDependencyTracker = createDependencyTracker();","import {\n BlocBase,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport useExternalBlocStore from './useExternalBlocStore';\nimport { DependencyTracker } from './DependencyTracker';\n\n/**\n * Type definition for the return type of the useBloc hook\n * @template B - Bloc constructor type\n */\ntype HookTypes<B extends BlocConstructor<BlocBase<any>>> = [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n];\n\n/**\n * Configuration options for the useBloc hook\n */\nexport interface BlocHookOptions<B extends BlocBase<any>> {\n id?: string;\n selector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n onUnmount?: (bloc: B) => void;\n}\n\n/**\n * Default dependency selector that wraps the entire state in an array\n * @template T - State type\n * @returns {Array<Array<T>>} Dependency array containing the entire state\n */\n\n/**\n * React hook for integrating with Blac state management\n *\n * This hook connects a React component to a Bloc state container, providing\n * automatic re-rendering when relevant state changes, dependency tracking,\n * and proper lifecycle management.\n *\n * @template B - Bloc constructor type\n * @template O - BlocHookOptions type\n * @param {B} bloc - Bloc constructor class\n * @param {O} [options] - Configuration options for the hook\n * @returns {HookTypes<B>} Tuple containing [state, bloc instance]\n *\n * @example\n * const [state, counterBloc] = useBloc(CounterBloc);\n * // Access state\n * console.log(state.count);\n * // Call bloc methods\n * counterBloc.increment();\n */\nexport default function useBloc<B extends BlocConstructor<BlocBase<any>>>(\n bloc: B,\n options?: BlocHookOptions<InstanceType<B>>,\n): HookTypes<B> {\n const {\n externalStore,\n usedKeys,\n usedClassPropKeys,\n instance,\n rid,\n hasProxyTracking,\n } = useExternalBlocStore(bloc, options);\n\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n externalStore.subscribe,\n () => {\n const snapshot = externalStore.getSnapshot();\n if (snapshot === undefined) {\n throw new Error(\n `[useBloc] State snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`,\n );\n }\n return snapshot;\n },\n externalStore.getServerSnapshot\n ? () => {\n const serverSnapshot = externalStore.getServerSnapshot!();\n if (serverSnapshot === undefined) {\n throw new Error(\n `[useBloc] Server state snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`,\n );\n }\n return serverSnapshot;\n }\n : undefined,\n );\n\n const dependencyTracker = useRef<DependencyTracker | null>(null);\n if (!dependencyTracker.current) {\n dependencyTracker.current = new DependencyTracker({\n enableBatching: true,\n enableMetrics: process.env.NODE_ENV === 'development',\n enableDeepTracking: false,\n });\n }\n\n const stateProxyCache = useRef<WeakMap<object, object>>(new WeakMap());\n const classProxyCache = useRef<WeakMap<object, object>>(new WeakMap());\n\n const returnState = useMemo(() => {\n // If a custom selector is provided, don't use proxy tracking\n if (options?.selector) {\n return state;\n }\n\n hasProxyTracking.current = true;\n\n if (typeof state !== 'object' || state === null) {\n return state;\n }\n\n let proxy = stateProxyCache.current.get(state);\n if (!proxy) {\n proxy = new Proxy(state, {\n get(target, prop) {\n if (typeof prop === 'string') {\n usedKeys.current.add(prop);\n dependencyTracker.current?.trackStateAccess(prop);\n }\n const value = target[prop as keyof typeof target];\n return value;\n },\n has(target, prop) {\n return prop in target;\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n });\n stateProxyCache.current.set(state as object, proxy as object);\n }\n return proxy;\n }, [state]);\n\n const returnClass = useMemo(() => {\n if (!instance.current) {\n throw new Error(\n `[useBloc] Bloc instance is null for ${bloc.name}. This should never happen - bloc instance must be defined.`,\n );\n }\n\n let proxy = classProxyCache.current.get(instance.current);\n if (!proxy) {\n proxy = new Proxy(instance.current, {\n get(target, prop) {\n if (!target) {\n throw new Error(\n `[useBloc] Bloc target is null for ${bloc.name}. This should never happen - bloc target must be defined.`,\n );\n }\n const value = target[prop as keyof InstanceType<B>];\n if (typeof value !== 'function' && typeof prop === 'string') {\n usedClassPropKeys.current.add(prop);\n dependencyTracker.current?.trackClassAccess(prop);\n }\n return value;\n },\n });\n classProxyCache.current.set(instance.current, proxy);\n }\n return proxy;\n }, [instance.current?.uid]);\n\n const componentRef = useRef({});\n\n useEffect(() => {\n const currentInstance = instance.current;\n if (!currentInstance) return;\n\n currentInstance._addConsumer(rid, componentRef.current);\n\n options?.onMount?.(currentInstance);\n\n return () => {\n if (!currentInstance) {\n return;\n }\n options?.onUnmount?.(currentInstance);\n currentInstance._removeConsumer(rid);\n\n dependencyTracker.current?.reset();\n };\n }, [instance.current?.uid, rid]);\n useEffect(() => {\n if (process.env.NODE_ENV === 'development' && dependencyTracker.current) {\n const metrics = dependencyTracker.current.getMetrics();\n if (metrics.stateAccessCount > 0 || metrics.classAccessCount > 0) {\n console.debug(`[useBloc] ${bloc.name} Performance Metrics:`, metrics);\n }\n }\n });\n\n if (returnState === undefined) {\n throw new Error(\n `[useBloc] State is undefined for ${bloc.name}. This should never happen - state must be defined.`,\n );\n }\n if (!returnClass) {\n throw new Error(\n `[useBloc] Instance is null for ${bloc.name}. This should never happen - instance must be defined.`,\n );\n }\n\n return [returnState, returnClass] as [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n ];\n}\n"],"names":["useExternalBlocStore","bloc","options","blocId","props","selector","rid","useMemo","generateUUID","effectiveBlocId","usedKeys","useRef","usedClassPropKeys","hasProxyTracking","getBloc","useCallback","Blac","blocInstance","previousStateRef","lastDependenciesRef","lastStableSnapshot","blocUidRef","_a","_b","dependencyArray","newState","oldState","instance","previousState","currentDependencies","stateDependencies","classDependencies","key","value","error","activeObservers","state","listener","currentInstance","existing","observer","e","unSub","unsubscribe","currentState","lastDeps","dependenciesChanged","arrayIndex","lastArray","newArray","i","DependencyTracker","config","__publicField","target","onAccess","cachedProxy","startTime","proxy","obj","prop","endTime","callback","classInstance","stateValues","classValues","estimatedMemory","allChangedKeys","sum","a","b","createDependencyTracker","useBloc","externalStore","useSyncExternalStore","snapshot","serverSnapshot","dependencyTracker","stateProxyCache","classProxyCache","returnState","returnClass","componentRef","useEffect","metrics"],"mappings":";;;;;AA2CM,MAAAA,IAAuB,CAG3BC,GACAC,MACyB;;AACzB,QAAM,EAAE,IAAIC,GAAQ,OAAAC,GAAO,UAAAC,EAAS,IAAIH,KAAW,CAAC,GAE9CI,IAAMC,EAAQ,MACXC,EAAa,GACnB,EAAE,GAKCC,IAHOR,EAEW,WACaK,IAAMH,GAErCO,IAAWC,EAAwB,oBAAA,KAAK,GACxCC,IAAoBD,EAAwB,oBAAA,KAAK,GAIjDE,IAAmBF,EAAgB,EAAK,GAExCG,IAAUC,EAAY,MACnBC,EAAK,QAAQf,GAAM;AAAA,IACxB,IAAIQ;AAAA,IACJ,OAAAL;AAAA,IACA,aAAaE;AAAA,EAAA,CACd,GACA,CAACL,GAAMQ,GAAiBL,GAAOE,CAAG,CAAC,GAEhCW,IAAeN,EAAwBG,GAAS;AAGtD,EAAAP,EAAQ,MAAM;AACZ,IAAAU,EAAa,UAAUH,EAAQ;AAAA,EAAA,GAC9B,CAACA,CAAO,CAAC;AAGN,QAAAI,IAAmBP,EAA+C,MAAS,GAC3EQ,IAAsBR,EAAgC,MAAS,GAC/DS,IAAqBT,EAA+C,MAAS,GAG7EU,IAAaV,EAA2B,MAAS;AACvD,EAAIU,EAAW,cAAYC,IAAAL,EAAa,YAAb,gBAAAK,EAAsB,SACpCD,EAAA,WAAUE,IAAAN,EAAa,YAAb,gBAAAM,EAAsB;AAG7C,QAAMC,IAAkBjB;AAAA,IACtB,MACE,CAACkB,GAAsCC,MAAuD;AAC5F,YAAMC,IAAWV,EAAa;AAE9B,UAAI,CAACU;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AGLhB,IAAApB,KAAA,gBAAAA,EAAS,cAAT,QAAAoB,EAAA,KAAApB,GAAqBoC,IACrBA,EAAgB,gBAAgBhC,CAAG,IAEnCiB,IAAAsD,EAAkB,YAAlB,QAAAtD,EAA2B;AAAA,MAC7B;AAAA,KACC,EAACA,IAAAI,EAAS,YAAT,gBAAAJ,EAAkB,KAAKjB,CAAG,CAAC,GAC/B6E,EAAU,MAAM;AACd,QAAI,QAAQ,IAAI,aAAa,iBAAiBN,EAAkB,SAAS;AACjE,YAAAO,IAAUP,EAAkB,QAAQ,WAAW;AACrD,OAAIO,EAAQ,mBAAmB,KAAKA,EAAQ,mBAAmB,MAC7D,QAAQ,MAAM,aAAanF,EAAK,IAAI,yBAAyBmF,CAAO;AAAA,IACtE;AAAA,EACF,CACD,GAEGJ,MAAgB;AAClB,UAAM,IAAI;AAAA,MACR,oCAAoC/E,EAAK,IAAI;AAAA,IAC/C;AAEF,MAAI,CAACgF;AACH,UAAM,IAAI;AAAA,MACR,kCAAkChF,EAAK,IAAI;AAAA,IAC7C;AAGK,SAAA,CAAC+E,GAAaC,CAAW;AAIlC;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blac/react",
|
|
3
|
-
"version": "2.0.0-rc-
|
|
3
|
+
"version": "2.0.0-rc-8",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": "Brendan Mullins <jsnanigans@gmail.com>",
|
|
6
6
|
"main": "dist/index.cjs.js",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"@types/react-dom": "^18.0.0 || ^19.0.0",
|
|
31
31
|
"react": "^18.0.0 || ^19.0.0",
|
|
32
32
|
"react-dom": "^18.0.0 || ^19.0.0",
|
|
33
|
-
"@blac/core": "2.0.0-rc-
|
|
33
|
+
"@blac/core": "2.0.0-rc-8"
|
|
34
34
|
},
|
|
35
35
|
"peerDependenciesMeta": {
|
|
36
36
|
"@types/react": {
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
|
|
2
|
+
export interface DependencyMetrics {
|
|
3
|
+
stateAccessCount: number;
|
|
4
|
+
classAccessCount: number;
|
|
5
|
+
proxyCreationCount: number;
|
|
6
|
+
batchFlushCount: number;
|
|
7
|
+
averageResolutionTime: number;
|
|
8
|
+
memoryUsageKB: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface DependencyTrackerConfig {
|
|
12
|
+
enableBatching: boolean;
|
|
13
|
+
batchTimeout: number;
|
|
14
|
+
enableMetrics: boolean;
|
|
15
|
+
maxCacheSize: number;
|
|
16
|
+
enableDeepTracking: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type DependencyChangeCallback = (changedKeys: Set<string>) => void;
|
|
20
|
+
|
|
21
|
+
export class DependencyTracker {
|
|
22
|
+
private stateKeys = new Set<string>();
|
|
23
|
+
private classKeys = new Set<string>();
|
|
24
|
+
private batchedCallbacks = new Set<DependencyChangeCallback>();
|
|
25
|
+
private flushScheduled = false;
|
|
26
|
+
private flushTimeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
27
|
+
|
|
28
|
+
private metrics: DependencyMetrics = {
|
|
29
|
+
stateAccessCount: 0,
|
|
30
|
+
classAccessCount: 0,
|
|
31
|
+
proxyCreationCount: 0,
|
|
32
|
+
batchFlushCount: 0,
|
|
33
|
+
averageResolutionTime: 0,
|
|
34
|
+
memoryUsageKB: 0,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
private resolutionTimes: number[] = [];
|
|
38
|
+
|
|
39
|
+
private config: DependencyTrackerConfig;
|
|
40
|
+
|
|
41
|
+
private stateProxyCache = new WeakMap<object, object>();
|
|
42
|
+
private classProxyCache = new WeakMap<object, object>();
|
|
43
|
+
|
|
44
|
+
private lastStateSnapshot: unknown = null;
|
|
45
|
+
private lastClassSnapshot: unknown = null;
|
|
46
|
+
|
|
47
|
+
constructor(config: Partial<DependencyTrackerConfig> = {}) {
|
|
48
|
+
this.config = {
|
|
49
|
+
enableBatching: true,
|
|
50
|
+
batchTimeout: 0, // Use React's scheduler
|
|
51
|
+
enableMetrics: process.env.NODE_ENV === 'development',
|
|
52
|
+
maxCacheSize: 1000,
|
|
53
|
+
enableDeepTracking: false,
|
|
54
|
+
...config,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
public trackStateAccess(key: string): void {
|
|
59
|
+
if (this.config.enableMetrics) {
|
|
60
|
+
this.metrics.stateAccessCount++;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
this.stateKeys.add(key);
|
|
64
|
+
|
|
65
|
+
if (this.config.enableBatching) {
|
|
66
|
+
this.scheduleFlush();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
public trackClassAccess(key: string): void {
|
|
71
|
+
if (this.config.enableMetrics) {
|
|
72
|
+
this.metrics.classAccessCount++;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
this.classKeys.add(key);
|
|
76
|
+
|
|
77
|
+
if (this.config.enableBatching) {
|
|
78
|
+
this.scheduleFlush();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
public createStateProxy<T extends object>(target: T, onAccess?: (prop: string) => void): T {
|
|
83
|
+
const cachedProxy = this.stateProxyCache.get(target);
|
|
84
|
+
if (cachedProxy) {
|
|
85
|
+
return cachedProxy as T;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const startTime = this.config.enableMetrics ? performance.now() : 0;
|
|
89
|
+
|
|
90
|
+
const proxy = new Proxy(target, {
|
|
91
|
+
get: (obj: T, prop: string | symbol) => {
|
|
92
|
+
if (typeof prop === 'string') {
|
|
93
|
+
this.trackStateAccess(prop);
|
|
94
|
+
onAccess?.(prop);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const value = obj[prop as keyof T];
|
|
98
|
+
|
|
99
|
+
if (
|
|
100
|
+
this.config.enableDeepTracking &&
|
|
101
|
+
value &&
|
|
102
|
+
typeof value === 'object' &&
|
|
103
|
+
!Array.isArray(value)
|
|
104
|
+
) {
|
|
105
|
+
return this.createStateProxy(value as object);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return value;
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
has: (obj: T, prop: string | symbol) => {
|
|
112
|
+
return prop in obj;
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
ownKeys: (obj: T) => {
|
|
116
|
+
return Reflect.ownKeys(obj);
|
|
117
|
+
},
|
|
118
|
+
|
|
119
|
+
getOwnPropertyDescriptor: (obj: T, prop: string | symbol) => {
|
|
120
|
+
return Reflect.getOwnPropertyDescriptor(obj, prop);
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
this.stateProxyCache.set(target, proxy);
|
|
125
|
+
|
|
126
|
+
if (this.config.enableMetrics) {
|
|
127
|
+
this.metrics.proxyCreationCount++;
|
|
128
|
+
const endTime = performance.now();
|
|
129
|
+
this.resolutionTimes.push(endTime - startTime);
|
|
130
|
+
this.updateAverageResolutionTime();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return proxy;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
public createClassProxy<T extends object>(target: T, onAccess?: (prop: string) => void): T {
|
|
137
|
+
const cachedProxy = this.classProxyCache.get(target);
|
|
138
|
+
if (cachedProxy) {
|
|
139
|
+
return cachedProxy as T;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const startTime = this.config.enableMetrics ? performance.now() : 0;
|
|
143
|
+
|
|
144
|
+
const proxy = new Proxy(target, {
|
|
145
|
+
get: (obj: T, prop: string | symbol) => {
|
|
146
|
+
const value = obj[prop as keyof T];
|
|
147
|
+
|
|
148
|
+
if (typeof prop === 'string' && typeof value !== 'function') {
|
|
149
|
+
this.trackClassAccess(prop);
|
|
150
|
+
onAccess?.(prop);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return value;
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
this.classProxyCache.set(target, proxy);
|
|
158
|
+
|
|
159
|
+
if (this.config.enableMetrics) {
|
|
160
|
+
this.metrics.proxyCreationCount++;
|
|
161
|
+
const endTime = performance.now();
|
|
162
|
+
this.resolutionTimes.push(endTime - startTime);
|
|
163
|
+
this.updateAverageResolutionTime();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return proxy;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
public getStateKeys(): Set<string> {
|
|
170
|
+
return new Set(this.stateKeys);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
public getClassKeys(): Set<string> {
|
|
174
|
+
return new Set(this.classKeys);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
public reset(): void {
|
|
178
|
+
this.stateKeys.clear();
|
|
179
|
+
this.classKeys.clear();
|
|
180
|
+
this.cancelScheduledFlush();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
public subscribe(callback: DependencyChangeCallback): () => void {
|
|
184
|
+
this.batchedCallbacks.add(callback);
|
|
185
|
+
|
|
186
|
+
return () => {
|
|
187
|
+
this.batchedCallbacks.delete(callback);
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
public computeDependencyArray<TState, TClass>(
|
|
192
|
+
state: TState,
|
|
193
|
+
classInstance: TClass,
|
|
194
|
+
): unknown[] {
|
|
195
|
+
const startTime = this.config.enableMetrics ? performance.now() : 0;
|
|
196
|
+
|
|
197
|
+
if (typeof state !== 'object' || state === null) {
|
|
198
|
+
return [[state]];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const stateValues: unknown[] = [];
|
|
202
|
+
for (const key of this.stateKeys) {
|
|
203
|
+
if (key in (state as object)) {
|
|
204
|
+
stateValues.push((state as any)[key]);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const classValues: unknown[] = [];
|
|
209
|
+
for (const key of this.classKeys) {
|
|
210
|
+
if (key in (classInstance as object)) {
|
|
211
|
+
try {
|
|
212
|
+
const value = (classInstance as any)[key];
|
|
213
|
+
if (typeof value !== 'function') {
|
|
214
|
+
classValues.push(value);
|
|
215
|
+
}
|
|
216
|
+
} catch (error) {
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (this.config.enableMetrics) {
|
|
222
|
+
const endTime = performance.now();
|
|
223
|
+
this.resolutionTimes.push(endTime - startTime);
|
|
224
|
+
this.updateAverageResolutionTime();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (stateValues.length === 0 && classValues.length === 0) {
|
|
228
|
+
return [[]];
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (classValues.length === 0) {
|
|
232
|
+
return [stateValues];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (stateValues.length === 0) {
|
|
236
|
+
return [classValues];
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return [stateValues, classValues];
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
public getMetrics(): DependencyMetrics {
|
|
243
|
+
if (!this.config.enableMetrics) {
|
|
244
|
+
return {
|
|
245
|
+
stateAccessCount: 0,
|
|
246
|
+
classAccessCount: 0,
|
|
247
|
+
proxyCreationCount: 0,
|
|
248
|
+
batchFlushCount: 0,
|
|
249
|
+
averageResolutionTime: 0,
|
|
250
|
+
memoryUsageKB: 0,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const estimatedMemory =
|
|
255
|
+
(this.stateKeys.size * 50) +
|
|
256
|
+
(this.classKeys.size * 50) +
|
|
257
|
+
(this.stateProxyCache instanceof WeakMap ? 100 : 0) +
|
|
258
|
+
(this.classProxyCache instanceof WeakMap ? 100 : 0);
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
...this.metrics,
|
|
262
|
+
memoryUsageKB: Math.round(estimatedMemory / 1024),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
public clearCaches(): void {
|
|
267
|
+
this.stateProxyCache = new WeakMap();
|
|
268
|
+
this.classProxyCache = new WeakMap();
|
|
269
|
+
this.resolutionTimes = [];
|
|
270
|
+
|
|
271
|
+
if (this.config.enableMetrics) {
|
|
272
|
+
this.metrics = {
|
|
273
|
+
stateAccessCount: 0,
|
|
274
|
+
classAccessCount: 0,
|
|
275
|
+
proxyCreationCount: 0,
|
|
276
|
+
batchFlushCount: 0,
|
|
277
|
+
averageResolutionTime: 0,
|
|
278
|
+
memoryUsageKB: 0,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private scheduleFlush(): void {
|
|
284
|
+
if (this.flushScheduled) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
this.flushScheduled = true;
|
|
289
|
+
|
|
290
|
+
if (this.config.batchTimeout > 0) {
|
|
291
|
+
this.flushTimeoutId = setTimeout(() => {
|
|
292
|
+
this.flushBatchedChanges();
|
|
293
|
+
}, this.config.batchTimeout);
|
|
294
|
+
} else {
|
|
295
|
+
Promise.resolve().then(() => this.flushBatchedChanges());
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private cancelScheduledFlush(): void {
|
|
300
|
+
if (this.flushTimeoutId) {
|
|
301
|
+
clearTimeout(this.flushTimeoutId);
|
|
302
|
+
this.flushTimeoutId = undefined;
|
|
303
|
+
}
|
|
304
|
+
this.flushScheduled = false;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
private flushBatchedChanges(): void {
|
|
308
|
+
if (!this.flushScheduled) {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
this.flushScheduled = false;
|
|
313
|
+
this.flushTimeoutId = undefined;
|
|
314
|
+
|
|
315
|
+
if (this.config.enableMetrics) {
|
|
316
|
+
this.metrics.batchFlushCount++;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const allChangedKeys = new Set([...this.stateKeys, ...this.classKeys]);
|
|
320
|
+
|
|
321
|
+
for (const callback of this.batchedCallbacks) {
|
|
322
|
+
try {
|
|
323
|
+
callback(allChangedKeys);
|
|
324
|
+
} catch (error) {
|
|
325
|
+
console.error('Error in dependency change callback:', error);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private updateAverageResolutionTime(): void {
|
|
331
|
+
if (this.resolutionTimes.length === 0) {
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (this.resolutionTimes.length > 100) {
|
|
336
|
+
this.resolutionTimes = this.resolutionTimes.slice(-100);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const sum = this.resolutionTimes.reduce((a, b) => a + b, 0);
|
|
340
|
+
this.metrics.averageResolutionTime = sum / this.resolutionTimes.length;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function createDependencyTracker(
|
|
345
|
+
config?: Partial<DependencyTrackerConfig>,
|
|
346
|
+
): DependencyTracker {
|
|
347
|
+
return new DependencyTracker(config);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export const defaultDependencyTracker = createDependencyTracker();
|