fortifyjs-react
Version:
React integration for Nehonix FortifyJS - Secure state management with enhanced object operations
1 lines • 84.5 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","sources":["../src/context/security-context.ts","../src/hooks/state/useSecureState.ts","../src/hooks/object/useSecureObject.ts","../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/cjs/react-jsx-runtime.development.js","../node_modules/react/jsx-runtime.js","../src/components/providers/SecureProvider.tsx","../src/index.ts"],"sourcesContent":["/**\r\n * Nehonix FortifyJS React Security Context\r\n * Modular security context for React applications\r\n */\r\n\r\nimport React, { createContext, useContext } from \"react\";\r\nimport type { SecurityConfig, SecurityContextValue } from \"../types\";\r\n\r\n/**\r\n * Default security configuration\r\n */\r\nexport const DEFAULT_SECURITY_CONFIG: SecurityConfig = {\r\n encryptionLevel: \"enhanced\",\r\n defaultSensitiveKeys: [\r\n \"password\",\r\n \"secret\",\r\n \"token\",\r\n \"key\",\r\n \"auth\",\r\n \"credential\",\r\n \"private\",\r\n \"confidential\",\r\n \"ssn\",\r\n \"credit\",\r\n \"card\",\r\n \"cvv\",\r\n \"pin\",\r\n ],\r\n enableMonitoring: true,\r\n performance: {\r\n enableCaching: true,\r\n cacheSize: 100,\r\n enableLazyLoading: true,\r\n },\r\n memory: {\r\n autoCleanup: true,\r\n cleanupInterval: 30000, // 30 seconds\r\n maxMemoryUsage: 50 * 1024 * 1024, // 50MB\r\n },\r\n development: {\r\n enableDebugMode: process.env.NODE_ENV === \"development\",\r\n logLevel: process.env.NODE_ENV === \"development\" ? \"debug\" : \"error\",\r\n enablePerformanceMetrics: true,\r\n },\r\n};\r\n\r\n/**\r\n * Security context for managing global security settings\r\n */\r\nexport const SecurityContext = createContext<SecurityContextValue | null>(null);\r\n \r\n/**\r\n * Hook to access security context\r\n * @returns Security context value\r\n * @throws Error if used outside SecurityProvider\r\n */\r\nexport function useSecurityContext(): SecurityContextValue {\r\n const context = useContext(SecurityContext);\r\n\r\n if (!context) {\r\n throw new Error(\r\n \"useSecurityContext must be used within a SecurityProvider. \" +\r\n \"Make sure to wrap your component tree with <SecureProvider>.\"\r\n );\r\n }\r\n\r\n return context;\r\n}\r\n\r\n/**\r\n * Hook to access security configuration\r\n * @returns Current security configuration\r\n */\r\nexport function useSecurityConfig(): SecurityConfig {\r\n const { config } = useSecurityContext();\r\n return config;\r\n}\r\n\r\n/**\r\n * Hook to check if a key should be treated as sensitive\r\n * @param key - The key to check\r\n * @returns Whether the key is sensitive\r\n */\r\nexport function useIsSensitiveKey(key: string): boolean {\r\n const { config } = useSecurityContext();\r\n const sensitiveKeys = config.defaultSensitiveKeys || [];\r\n\r\n // Check exact match\r\n if (sensitiveKeys.includes(key.toLowerCase())) {\r\n return true;\r\n }\r\n\r\n // Check if key contains sensitive patterns\r\n return sensitiveKeys.some((pattern) =>\r\n key.toLowerCase().includes(pattern.toLowerCase())\r\n );\r\n}\r\n\r\n/**\r\n * Hook to access security metrics\r\n * @returns Current security metrics\r\n */\r\nexport function useSecurityMetrics() {\r\n const { getMetrics } = useSecurityContext();\r\n return getMetrics();\r\n}\r\n\r\n/**\r\n * Hook to control debug mode\r\n * @returns Debug mode controls\r\n */\r\nexport function useDebugMode() {\r\n const { debugMode, setDebugMode } = useSecurityContext();\r\n\r\n return {\r\n enabled: debugMode,\r\n enable: () => setDebugMode(true),\r\n disable: () => setDebugMode(false),\r\n toggle: () => setDebugMode(!debugMode),\r\n };\r\n}\r\n\r\n/**\r\n * Hook to register/unregister components for monitoring\r\n * @param componentId - Unique component identifier\r\n * @param metadata - Component metadata\r\n */\r\nexport function useComponentRegistration(\r\n componentId: string,\r\n metadata: any = {}\r\n) {\r\n const { registerComponent, unregisterComponent } = useSecurityContext();\r\n\r\n // Register component on mount\r\n React.useEffect(() => {\r\n registerComponent(componentId, {\r\n ...metadata,\r\n registeredAt: new Date(),\r\n componentType: \"react-component\",\r\n });\r\n\r\n // Unregister on unmount\r\n return () => {\r\n unregisterComponent(componentId);\r\n };\r\n }, [componentId, registerComponent, unregisterComponent]);\r\n}\r\n\r\n/**\r\n * Hook to get performance metrics for the current component\r\n * @param componentId - Component identifier\r\n * @returns Performance metrics\r\n */\r\nexport function useComponentMetrics(componentId: string) {\r\n const { getRegisteredComponents } = useSecurityContext();\r\n const [metrics, setMetrics] = React.useState({\r\n renderCount: 0,\r\n averageRenderTime: 0,\r\n lastRenderTime: 0,\r\n });\r\n\r\n // Track render performance\r\n React.useEffect(() => {\r\n const startTime = performance.now();\r\n\r\n return () => {\r\n const endTime = performance.now();\r\n const renderTime = endTime - startTime;\r\n\r\n setMetrics((prev) => ({\r\n renderCount: prev.renderCount + 1,\r\n averageRenderTime:\r\n (prev.averageRenderTime * prev.renderCount + renderTime) /\r\n (prev.renderCount + 1),\r\n lastRenderTime: renderTime,\r\n }));\r\n };\r\n });\r\n\r\n return metrics;\r\n}\r\n\r\n/**\r\n * Utility function to merge security configurations\r\n * @param base - Base configuration\r\n * @param override - Override configuration\r\n * @returns Merged configuration\r\n */\r\nexport function mergeSecurityConfig(\r\n base: SecurityConfig,\r\n override: Partial<SecurityConfig>\r\n): SecurityConfig {\r\n return {\r\n ...base,\r\n ...override,\r\n defaultSensitiveKeys: [\r\n ...(base.defaultSensitiveKeys || []),\r\n ...(override.defaultSensitiveKeys || []),\r\n ],\r\n performance: {\r\n ...base.performance,\r\n ...override.performance,\r\n },\r\n memory: {\r\n ...base.memory,\r\n ...override.memory,\r\n },\r\n development: {\r\n ...base.development,\r\n ...override.development,\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Utility function to validate security configuration\r\n * @param config - Configuration to validate\r\n * @throws Error if configuration is invalid\r\n */\r\nexport function validateSecurityConfig(config: SecurityConfig): void {\r\n if (config.memory?.maxMemoryUsage && config.memory.maxMemoryUsage < 0) {\r\n throw new Error(\"maxMemoryUsage must be a positive number\");\r\n }\r\n\r\n if (\r\n config.memory?.cleanupInterval &&\r\n config.memory.cleanupInterval < 1000\r\n ) {\r\n throw new Error(\"cleanupInterval must be at least 1000ms\");\r\n }\r\n\r\n if (config.performance?.cacheSize && config.performance.cacheSize < 1) {\r\n throw new Error(\"cacheSize must be at least 1\");\r\n }\r\n\r\n const validEncryptionLevels = [\"basic\", \"enhanced\", \"military\"];\r\n if (\r\n config.encryptionLevel &&\r\n !validEncryptionLevels.includes(config.encryptionLevel)\r\n ) {\r\n throw new Error(\r\n `encryptionLevel must be one of: ${validEncryptionLevels.join(\r\n \", \"\r\n )}`\r\n );\r\n }\r\n\r\n const validLogLevels = [\"none\", \"error\", \"warn\", \"info\", \"debug\"];\r\n if (\r\n config.development?.logLevel &&\r\n !validLogLevels.includes(config.development.logLevel)\r\n ) {\r\n throw new Error(\r\n `logLevel must be one of: ${validLogLevels.join(\", \")}`\r\n );\r\n }\r\n}\r\n\r\n","/**\r\n * FortifyJS React useSecureState Hook\r\n * Secure state management with automatic encryption and enhanced operations\r\n */\r\n\r\nimport React, { useState, useCallback, useRef, useEffect } from \"react\";\r\nimport { createSecureObject, SecureObject } from \"fortify2-js\";\r\nimport type { UseSecureStateOptions, UseSecureStateReturn } from \"../../types\";\r\nimport { useSecurityContext, useIsSensitiveKey } from \"../../context\";\r\n\r\n/**\r\n * Hook for secure state management with enhanced object operations\r\n *\r\n * @param initialValue - Initial state value\r\n * @param options - Configuration options\r\n * @returns Secure state management object\r\n *\r\n * @example\r\n * ```tsx\r\n * function UserProfile() {\r\n * const [user, setUser] = useSecureState({\r\n * name: \"John\",\r\n * email: \"john@example.com\",\r\n * password: \"secret123\"\r\n * }, {\r\n * sensitiveKeys: [\"password\"],\r\n * autoEncrypt: true\r\n * });\r\n *\r\n * return (\r\n * <div>\r\n * <p>Name: {user.get(\"name\")}</p>\r\n * <p>Email: {user.get(\"email\")}</p>\r\n * // Password is automatically encrypted\r\n * </div>\r\n * );\r\n * }\r\n * ```\r\n */\r\nexport function useSecureState<T extends Record<string, any>>(\r\n initialValue: T,\r\n options: UseSecureStateOptions = {}\r\n): UseSecureStateReturn<T> {\r\n const securityContext = useSecurityContext();\r\n const isSensitiveKey = useIsSensitiveKey;\r\n\r\n // Configuration with defaults\r\n const config = {\r\n sensitiveKeys: options.sensitiveKeys || [],\r\n autoEncrypt: options.autoEncrypt ?? true,\r\n encryptionAlgorithm: options.encryptionAlgorithm || \"AES-256-GCM\",\r\n enableMonitoring:\r\n options.enableMonitoring ?? securityContext.config.enableMonitoring,\r\n debounceMs: options.debounceMs || 0,\r\n ...options,\r\n };\r\n\r\n // Create secure object with initial value\r\n const [secureObject] = useState(() => {\r\n const obj = createSecureObject(initialValue);\r\n\r\n // Set sensitive keys\r\n const allSensitiveKeys = [\r\n ...config.sensitiveKeys,\r\n ...Object.keys(initialValue).filter((key) => isSensitiveKey(key)),\r\n ];\r\n\r\n if (allSensitiveKeys.length > 0) {\r\n obj.setSensitiveKeys(allSensitiveKeys);\r\n }\r\n\r\n return obj;\r\n });\r\n\r\n // Performance metrics\r\n const metricsRef = useRef({\r\n updateCount: 0,\r\n lastUpdateTime: 0,\r\n totalUpdateTime: 0,\r\n });\r\n\r\n // Force re-render when secure object changes\r\n const [, forceUpdate] = useState<object>({});\r\n const triggerUpdate = useCallback(() => {\r\n forceUpdate({});\r\n }, []);\r\n\r\n // Debounced update function\r\n const debounceRef = useRef<NodeJS.Timeout | null>(null);\r\n const debouncedUpdate = useCallback(() => {\r\n if (config.debounceMs > 0) {\r\n if (debounceRef.current) {\r\n clearTimeout(debounceRef.current);\r\n }\r\n debounceRef.current = setTimeout(triggerUpdate, config.debounceMs);\r\n } else {\r\n triggerUpdate();\r\n }\r\n }, [config.debounceMs, triggerUpdate]);\r\n\r\n // Set up event listeners for secure object changes\r\n useEffect(() => {\r\n const handleChange = () => {\r\n const startTime = performance.now();\r\n\r\n // Update metrics\r\n metricsRef.current.updateCount++;\r\n metricsRef.current.lastUpdateTime = startTime;\r\n\r\n // Trigger re-render\r\n debouncedUpdate();\r\n\r\n // Complete metrics\r\n const endTime = performance.now();\r\n const duration = endTime - startTime;\r\n metricsRef.current.totalUpdateTime += duration;\r\n\r\n // Call user event handler\r\n if (config.validator) {\r\n const currentValue = secureObject.toObject();\r\n if (!config.validator(currentValue)) {\r\n console.warn(\r\n \"useSecureState: Validation failed for current state\"\r\n );\r\n }\r\n }\r\n };\r\n\r\n // Listen to secure object events\r\n secureObject.addEventListener(\"set\", handleChange);\r\n secureObject.addEventListener(\"delete\", handleChange);\r\n secureObject.addEventListener(\"clear\", handleChange);\r\n\r\n return () => {\r\n secureObject.removeEventListener(\"set\", handleChange);\r\n secureObject.removeEventListener(\"delete\", handleChange);\r\n secureObject.removeEventListener(\"clear\", handleChange);\r\n\r\n if (debounceRef.current) {\r\n clearTimeout(debounceRef.current);\r\n }\r\n };\r\n }, [secureObject, debouncedUpdate, config.validator]);\r\n\r\n // Cleanup on unmount\r\n useEffect(() => {\r\n return () => {\r\n secureObject.destroy();\r\n };\r\n }, [secureObject]);\r\n\r\n // setState function\r\n const setState = useCallback(\r\n (value: T | ((prev: T) => T)) => {\r\n const startTime = performance.now();\r\n\r\n try {\r\n if (typeof value === \"function\") {\r\n const currentValue = secureObject.toObject() as T;\r\n const newValue = value(currentValue);\r\n\r\n // Clear and set new values\r\n secureObject.clear();\r\n Object.entries(newValue).forEach(([key, val]) => {\r\n secureObject.set(key, val);\r\n });\r\n } else {\r\n // Clear and set new values\r\n secureObject.clear();\r\n Object.entries(value).forEach(([key, val]) => {\r\n secureObject.set(key, val);\r\n });\r\n }\r\n\r\n // Update sensitive keys if auto-detection is enabled\r\n if (config.autoEncrypt) {\r\n const newSensitiveKeys = Object.keys(\r\n secureObject.toObject()\r\n ).filter((key) => isSensitiveKey(key));\r\n\r\n if (newSensitiveKeys.length > 0) {\r\n const existingSensitive =\r\n secureObject.getSensitiveKeys();\r\n const allSensitive = [\r\n ...new Set([\r\n ...existingSensitive,\r\n ...newSensitiveKeys,\r\n ]),\r\n ];\r\n secureObject.setSensitiveKeys(allSensitive);\r\n }\r\n }\r\n } catch (error) {\r\n console.error(\"useSecureState: Error updating state:\", error);\r\n throw error;\r\n }\r\n },\r\n [secureObject, config.autoEncrypt, isSensitiveKey]\r\n );\r\n\r\n // getValue function\r\n const getValue = useCallback(\r\n <K extends keyof T>(key: K): T[K] => {\r\n return secureObject.get(key as string) as T[K];\r\n },\r\n [secureObject]\r\n );\r\n\r\n // setValue function\r\n const setValue = useCallback(\r\n <K extends keyof T>(key: K, value: T[K]) => {\r\n secureObject.set(key as string, value);\r\n\r\n // Auto-detect sensitive keys\r\n if (config.autoEncrypt && isSensitiveKey(key as string)) {\r\n const existingSensitive = secureObject.getSensitiveKeys();\r\n if (!existingSensitive.includes(key as string)) {\r\n secureObject.setSensitiveKeys([\r\n ...existingSensitive,\r\n key as string,\r\n ]);\r\n }\r\n }\r\n },\r\n [secureObject, config.autoEncrypt, isSensitiveKey]\r\n );\r\n\r\n // Calculate metrics\r\n const metrics = {\r\n updateCount: metricsRef.current.updateCount,\r\n lastUpdateTime: metricsRef.current.lastUpdateTime,\r\n averageUpdateTime:\r\n metricsRef.current.updateCount > 0\r\n ? metricsRef.current.totalUpdateTime /\r\n metricsRef.current.updateCount\r\n : 0,\r\n };\r\n\r\n return {\r\n state: secureObject as unknown as SecureObject<T>,\r\n setState,\r\n getValue,\r\n setValue,\r\n isEncrypted: secureObject.getSensitiveKeys().length > 0,\r\n metrics,\r\n };\r\n}\r\n\r\n ","/**\r\n * FortifyJS React useSecureObject Hook\r\n * Enhanced object operations with React integration\r\n */\r\n\r\nimport React, { useState, useCallback, useRef, useEffect } from \"react\";\r\nimport { createSecureObject } from \"fortify2-js\";\r\nimport type {\r\n UseSecureObjectOptions,\r\n UseSecureObjectReturn,\r\n} from \"../../types\";\r\nimport { useSecurityContext } from \"../../context\";\r\n\r\n/**\r\n * Hook for enhanced object operations with React integration\r\n *\r\n * @param initialData - Initial object data or data source\r\n * @param options - Configuration options\r\n * @returns Enhanced object management\r\n *\r\n * @example\r\n * ```tsx\r\n * function DataProcessor() {\r\n * const data = useSecureObject(rawData, {\r\n * autoCleanup: true,\r\n * enableEvents: true\r\n * });\r\n *\r\n * const processedData = data.object\r\n * .filterNonSensitive()\r\n * .transform(value => value.toUpperCase())\r\n * .compact();\r\n *\r\n * return (\r\n * <div>\r\n * <p>Processed {processedData.size} items</p>\r\n * <p>Ready: {data.isReady ? \"Yes\" : \"No\"}</p>\r\n * </div>\r\n * );\r\n * }\r\n * ```\r\n */\r\nexport function useSecureObject<T extends Record<string, any>>(\r\n initialData: T | (() => T) | (() => Promise<T>),\r\n options: UseSecureObjectOptions = {}\r\n): UseSecureObjectReturn<T> {\r\n const securityContext = useSecurityContext();\r\n\r\n // Configuration with defaults\r\n const config = {\r\n autoCleanup: options.autoCleanup ?? true,\r\n enableEvents: options.enableEvents ?? true,\r\n optimizationLevel: options.optimizationLevel || \"balanced\",\r\n memoryStrategy: options.memoryStrategy || \"balanced\",\r\n ...options,\r\n };\r\n\r\n // State management\r\n const [secureObject, setSecureObject] = useState<any>(null);\r\n const [isReady, setIsReady] = useState(false);\r\n const [isLoading, setIsLoading] = useState(true);\r\n const [error, setError] = useState<Error | null>(null);\r\n\r\n // Metadata tracking\r\n const metadataRef = useRef({\r\n size: 0,\r\n sensitiveKeyCount: 0,\r\n lastModified: new Date(),\r\n });\r\n\r\n // Performance optimization based on level\r\n const _performanceConfig = {\r\n basic: { cacheSize: 10, enableLazyLoading: false },\r\n enhanced: { cacheSize: 50, enableLazyLoading: true },\r\n maximum: { cacheSize: 100, enableLazyLoading: true },\r\n }[config.optimizationLevel];\r\n\r\n // Memory management based on strategy\r\n const memoryConfig = {\r\n conservative: { maxSize: 1000, cleanupThreshold: 0.8 },\r\n balanced: { maxSize: 5000, cleanupThreshold: 0.9 },\r\n aggressive: { maxSize: 10000, cleanupThreshold: 0.95 },\r\n }[config.memoryStrategy];\r\n\r\n // Initialize secure object\r\n const initializeObject = useCallback(async () => {\r\n setIsLoading(true);\r\n setError(null);\r\n\r\n try {\r\n let data: T;\r\n\r\n if (typeof initialData === \"function\") {\r\n const result = initialData();\r\n data = result instanceof Promise ? await result : result;\r\n } else {\r\n data = initialData;\r\n }\r\n\r\n const obj = createSecureObject(data);\r\n\r\n // Set up event listeners if enabled\r\n if (config.enableEvents) {\r\n const updateMetadata = () => {\r\n metadataRef.current = {\r\n size: obj.size,\r\n sensitiveKeyCount: obj.getSensitiveKeys().length,\r\n lastModified: new Date(),\r\n };\r\n };\r\n\r\n obj.addEventListener(\"set\", updateMetadata);\r\n obj.addEventListener(\"delete\", updateMetadata);\r\n obj.addEventListener(\"clear\", updateMetadata);\r\n obj.addEventListener(\"filtered\", updateMetadata);\r\n }\r\n\r\n // Apply memory management\r\n if (obj.size > memoryConfig.maxSize) {\r\n console.warn(\r\n `useSecureObject: Object size (${obj.size}) exceeds recommended maximum (${memoryConfig.maxSize}). ` +\r\n \"Consider using streaming operations for large datasets.\"\r\n );\r\n }\r\n\r\n setSecureObject(obj);\r\n setIsReady(true);\r\n\r\n // Initial metadata update\r\n metadataRef.current = {\r\n size: obj.size,\r\n sensitiveKeyCount: obj.getSensitiveKeys().length,\r\n lastModified: new Date(),\r\n };\r\n } catch (err) {\r\n const error = err instanceof Error ? err : new Error(String(err));\r\n setError(error);\r\n console.error(\r\n \"useSecureObject: Failed to initialize object:\",\r\n error\r\n );\r\n } finally {\r\n setIsLoading(false);\r\n }\r\n }, [initialData, config.enableEvents, memoryConfig.maxSize]);\r\n\r\n // Initialize on mount\r\n useEffect(() => {\r\n initializeObject();\r\n }, [initializeObject]);\r\n\r\n // Cleanup on unmount\r\n useEffect(() => {\r\n return () => {\r\n if (config.autoCleanup && secureObject) {\r\n secureObject.destroy();\r\n }\r\n };\r\n }, [config.autoCleanup, secureObject]);\r\n\r\n // Memory monitoring\r\n useEffect(() => {\r\n if (!secureObject || !config.enableEvents) return;\r\n\r\n const checkMemoryUsage = () => {\r\n const currentSize = secureObject.size;\r\n const threshold =\r\n memoryConfig.maxSize * memoryConfig.cleanupThreshold;\r\n\r\n if (currentSize > threshold) {\r\n console.warn(\r\n `useSecureObject: Memory usage approaching limit. ` +\r\n `Current: ${currentSize}, Threshold: ${threshold}`\r\n );\r\n\r\n // Trigger garbage collection hint if available\r\n if (typeof global !== \"undefined\" && global.gc) {\r\n global.gc();\r\n }\r\n }\r\n };\r\n\r\n const interval = setInterval(checkMemoryUsage, 10000); // Check every 10 seconds\r\n\r\n return () => clearInterval(interval);\r\n }, [secureObject, config.enableEvents, memoryConfig]);\r\n\r\n // Refresh function\r\n const refresh = useCallback(() => {\r\n initializeObject();\r\n }, [initializeObject]);\r\n\r\n // Performance monitoring\r\n useEffect(() => {\r\n if (!securityContext.config.development?.enablePerformanceMetrics)\r\n return;\r\n\r\n const startTime = performance.now();\r\n\r\n return () => {\r\n const endTime = performance.now();\r\n const duration = endTime - startTime;\r\n\r\n if (duration > 100) {\r\n // Log slow operations\r\n console.debug(\r\n `useSecureObject: Component lifecycle took ${duration.toFixed(\r\n 2\r\n )}ms`\r\n );\r\n }\r\n };\r\n }, [securityContext.config.development?.enablePerformanceMetrics]);\r\n\r\n return {\r\n object: secureObject,\r\n refresh,\r\n isReady,\r\n isLoading,\r\n error,\r\n metadata: metadataRef.current,\r\n };\r\n}\r\n\r\n/**\r\n * Hook for creating a secure object from static data\r\n * Simplified version of useSecureObject for static data\r\n *\r\n * @param data - Static object data\r\n * @param options - Configuration options\r\n * @returns Secure object\r\n */\r\nexport function useStaticSecureObject<T extends Record<string, any>>(\r\n data: T,\r\n options: Omit<UseSecureObjectOptions, \"autoCleanup\"> = {}\r\n) {\r\n return useSecureObject(data, { ...options, autoCleanup: true });\r\n}\r\n\r\n/**\r\n * Hook for creating a secure object from async data source\r\n * Specialized version for async data loading\r\n *\r\n * @param dataLoader - Async function that returns data\r\n * @param dependencies - Dependencies that trigger reload\r\n * @param options - Configuration options\r\n * @returns Secure object with loading states\r\n */\r\nexport function useAsyncSecureObject<T extends Record<string, any>>(\r\n dataLoader: () => Promise<T>,\r\n dependencies: React.DependencyList = [],\r\n options: UseSecureObjectOptions = {}\r\n) {\r\n const memoizedLoader = useCallback(dataLoader, dependencies);\r\n return useSecureObject(memoizedLoader, options);\r\n}\r\n\r\n","/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return (type.displayName || \"Context\") + \".Provider\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%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)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"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.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(\n type,\n key,\n self,\n source,\n owner,\n props,\n debugStack,\n debugTask\n ) {\n self = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== self ? self : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n source,\n self,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n self,\n source,\n getOwner(),\n maybeKey,\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_ELEMENT_TYPE &&\n node._store &&\n (node._store.validated = 1);\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\");\n Symbol.for(\"react.provider\");\n var REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n \"react-stack-bottom-frame\": function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React[\"react-stack-bottom-frame\"].bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey, source, self) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n source,\n self,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey, source, self) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n source,\n self,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","/**\r\n * FortifyJS React SecureProvider Component\r\n * Global security context provider for React applications\r\n */\r\n\r\nimport React, { useState, useCallback, useRef, useEffect } from \"react\";\r\nimport {\r\n SecurityContext,\r\n DEFAULT_SECURITY_CONFIG,\r\n mergeSecurityConfig,\r\n validateSecurityConfig,\r\n} from \"../../context\";\r\nimport type {\r\n SecureProviderProps,\r\n SecurityConfig,\r\n SecurityContextValue,\r\n PerformanceMetrics,\r\n} from \"../../types\";\r\n\r\n/**\r\n * Global security provider component\r\n * Provides security context to all child components\r\n *\r\n * @example\r\n * ```tsx\r\n * function App() {\r\n * return (\r\n * <SecureProvider\r\n * config={{\r\n * encryptionLevel: \"military\",\r\n * enableMonitoring: true\r\n * }}\r\n * >\r\n * <UserProfile />\r\n * <DataProcessor />\r\n * </SecureProvider>\r\n * );\r\n * }\r\n * ```\r\n */\r\nexport const SecureProvider: React.FC<SecureProviderProps> = ({\r\n config: userConfig,\r\n children,\r\n fallback = null,\r\n onError, \r\n}) => {\r\n // Merge user config with defaults\r\n const [config, setConfig] = useState<SecurityConfig>(() => {\r\n try {\r\n const mergedConfig = mergeSecurityConfig(\r\n DEFAULT_SECURITY_CONFIG,\r\n userConfig\r\n );\r\n validateSecurityConfig(mergedConfig);\r\n return mergedConfig;\r\n } catch (error) {\r\n console.error(\"SecureProvider: Invalid configuration:\", error);\r\n if (onError) {\r\n onError(error as Error, { phase: \"initialization\" });\r\n }\r\n return DEFAULT_SECURITY_CONFIG;\r\n }\r\n });\r\n\r\n // Debug mode state\r\n const [debugMode, setDebugMode] = useState(\r\n config.development?.enableDebugMode ?? false\r\n );\r\n\r\n // Component registry for monitoring\r\n const registeredComponents = useRef<Record<string, any>>({});\r\n\r\n // Performance metrics\r\n const metricsRef = useRef<PerformanceMetrics>({\r\n componentRenders: 0,\r\n averageRenderTime: 0,\r\n memoryUsage: 0,\r\n operationCounts: {},\r\n lastUpdate: new Date(),\r\n });\r\n\r\n // Security metrics\r\n const securityMetricsRef = useRef({\r\n totalOperations: 0,\r\n encryptedOperations: 0,\r\n totalOperationTime: 0,\r\n memoryUsage: 0,\r\n });\r\n\r\n // Update configuration\r\n const updateConfig = useCallback(\r\n (newConfig: Partial<SecurityConfig>) => {\r\n try {\r\n const mergedConfig = mergeSecurityConfig(config, newConfig);\r\n validateSecurityConfig(mergedConfig);\r\n setConfig(mergedConfig);\r\n\r\n if (debugMode) {\r\n console.debug(\r\n \"SecureProvider: Configuration updated\",\r\n mergedConfig\r\n );\r\n }\r\n } catch (error) {\r\n console.error(\r\n \"SecureProvider: Failed to update configuration:\",\r\n error\r\n );\r\n if (onError) {\r\n onError(error as Error, { phase: \"configuration-update\" });\r\n }\r\n }\r\n },\r\n [config, debugMode, onError]\r\n );\r\n\r\n // Get security metrics\r\n const getMetrics = useCallback(() => {\r\n const metrics = securityMetricsRef.current;\r\n return {\r\n totalOperations: metrics.totalOperations,\r\n encryptedOperations: metrics.encryptedOperations,\r\n averageOperationTime:\r\n metrics.totalOperations > 0\r\n ? metrics.totalOperationTime / metrics.totalOperations\r\n : 0,\r\n memoryUsage: metrics.memoryUsage,\r\n };\r\n }, []);\r\n\r\n // Register component\r\n const registerComponent = useCallback(\r\n (componentId: string, metadata: any) => {\r\n registeredComponents.current[componentId] = {\r\n ...metadata,\r\n registeredAt: new Date(),\r\n };\r\n\r\n if (debugMode) {\r\n console.debug(\r\n `SecureProvider: Registered component ${componentId}`,\r\n metadata\r\n );\r\n }\r\n },\r\n [debugMode]\r\n );\r\n\r\n // Unregister component\r\n const unregisterComponent = useCallback(\r\n (componentId: string) => {\r\n delete registeredComponents.current[componentId];\r\n\r\n if (debugMode) {\r\n console.debug(\r\n `SecureProvider: Unregistered component ${componentId}`\r\n );\r\n }\r\n },\r\n [debugMode]\r\n );\r\n\r\n // Get registered components\r\n const getRegisteredComponents = useCallback(() => {\r\n return { ...registeredComponents.current };\r\n }, []);\r\n\r\n // Memory monitoring\r\n useEffect(() => {\r\n if (!config.memory?.autoCleanup) return;\r\n\r\n const interval = setInterval(() => {\r\n // Update memory usage metrics\r\n if (\r\n typeof performance !== \"undefined\" &&\r\n (performance as any).memory\r\n ) {\r\n const memInfo = (performance as any).memory;\r\n securityMetricsRef.current.memoryUsage = memInfo.usedJSHeapSize;\r\n\r\n // Check memory threshold\r\n const maxMemory =\r\n config.memory?.maxMemoryUsage || 50 * 1024 * 1024;\r\n if (memInfo.usedJSHeapSize > maxMemory * 0.9) {\r\n console.warn(\r\n \"SecureProvider: High memory usage detected. \" +\r\n \"Consider optimizing your secure objects.\"\r\n );\r\n }\r\n }\r\n\r\n // Clean up old component registrations\r\n const now = new Date();\r\n const maxAge = 5 * 60 * 1000; // 5 minutes\r\n\r\n Object.entries(registeredComponents.current).forEach(\r\n ([id, metadata]) => {\r\n if (\r\n now.getTime() - metadata.registeredAt.getTime() >\r\n maxAge\r\n ) {\r\n delete registeredComponents.current[id];\r\n }\r\n }\r\n );\r\n }, config.memory?.cleanupInterval || 30000);\r\n\r\n return () => clearInterval(interval);\r\n }, [config.memory]);\r\n\r\n // Performance monitoring\r\n useEffect(() => {\r\n if (!config.development?.enablePerformanceMetrics) return;\r\n\r\n const startTime = performance.now();\r\n metricsRef.current.componentRenders++;\r\n\r\n return () => {\r\n const endTime = performance.now();\r\n const renderTime = endTime - startTime;\r\n\r\n // Update average render time\r\n const currentAvg = metricsRef.current.averageRenderTime;\r\n const renderCount = metricsRef.current.componentRenders;\r\n metricsRef.current.averageRenderTime =\r\n (currentAvg * (renderCount - 1) + renderTime) / renderCount;\r\n\r\n metricsRef.current.lastUpdate = new Date();\r\n\r\n if (debugMode && renderTime > 16) {\r\n // Slower than 60fps\r\n console.debug(\r\n `SecureProvider: Slow render detected (${renderTime.toFixed(\r\n 2\r\n )}ms)`\r\n );\r\n }\r\n };\r\n });\r\n\r\n // Error boundary effect\r\n useEffect(() => {\r\n const handleError = (event: ErrorEvent) => {\r\n if (onError) {\r\n onError(event.error, { phase: \"runtime\", event });\r\n }\r\n };\r\n\r\n const handleUnhandledRejection = (event: PromiseRejectionEvent) => {\r\n if (onError) {\r\n onError(\r\n new Error(`Unhandled promise rejection: ${event.reason}`),\r\n { phase: \"promise-rejection\", event }\r\n );\r\n }\r\n };\r\n\r\n window.addEventListener(\"error\", handleError);\r\n window.addEventListener(\"unhandledrejection\", handleUnhandledRejection);\r\n\r\n return () => {\r\n window.removeEventListener(\"error\", handleError);\r\n window.removeEventListener(\r\n \"unhandledrejection\",\r\n handleUnhandledRejection\r\n );\r\n };\r\n }, [onError]);\r\n\r\n // Context value\r\n const contextValue: SecurityContextValue = {\r\n config,\r\n updateConfig,\r\n getMetrics,\r\n setDebugMode,\r\n debugMode,\r\n registerComponent,\r\n unregisterComponent,\r\n getRegisteredComponents,\r\n };\r\n\r\n // Show fallback while initializing\r\n if (!config) {\r\n return <>{fallback}</>;\r\n }\r\n\r\n return (\r\n <SecurityContext.Provider value={contextValue}>\r\n {children}\r\n </SecurityContext.Provider>\r\n );\r\n};\r\n\r\n","/**\r\n * FortifyJS React Integration - Main Exports\r\n * Complete React integration for FortifyJS\r\n */\r\n\r\n// Hooks\r\nexport {\r\n useSecureState,\r\n useSecureObject,\r\n useStaticSecureObject,\r\n useAs