/** * Function type for checking if a module needs to be updated * * @remarks * This function is called during {@link checkFreshScripts} to determine if a module * should be reloaded from the remote source. Return `true` if the module is fresh * (no update needed), or `false` if it should be reloaded. * * @param data - Module data object containing at minimum: * - `digest`: Version hash or identifier * - `[keyField]`: Module identifier (default: `code`) * @returns `true` if the module is up-to-date, `false` if it needs to be reloaded * * @example * ```typescript * const moduleCheck: ModuleCheck = (data) => { * const localDigest = localStorage.getItem(`module:${data.code}`); * return localDigest === data.digest; * }; * ``` */ export type ModuleCheck = (data: any) => boolean; /** * Function type for loading a module from remote source * * @remarks * This function is called when a module needs to be updated or loaded for the first time. * It should fetch the module data from your API/backend and return a complete module object. * * @param data - Module metadata object containing at minimum: * - `[keyField]`: Module identifier (e.g., `code`, `id`) * - Other fields needed for your API request * @returns Promise resolving to module data with required fields: * - `[keyField]`: Module identifier (must match input) * - `digest`: Version hash for cache invalidation * - `scriptText`: The JavaScript code to execute * - `uiLayout` (optional): UI layout configuration as JSON string * * @example * ```typescript * const loadModule: LoadModule = async (info) => { * const response = await fetch(`/api/modules/${info.code}`); * if (!response.ok) throw new Error(`Failed to load module: ${info.code}`); * return response.json(); * }; * ``` */ export type LoadModule = (data: any) => Promise; /** * Configuration options for ModuleLoader initialization * * @remarks * Pass these options to {@link ModuleLoader.initialize} to customize the loader behavior. * * @example * ```typescript * ModuleLoader.initialize(loadModule, { * keyField: 'id', // Use 'id' instead of 'code' * prefix: 'MyApp', // Custom storage prefix * moduleCheck: customCheck // Custom freshness check * }); * ``` */ export interface ModuleLoaderOptions { /** * Optional custom module check function * * @remarks * If not provided, uses the default implementation which compares * the digest stored in localStorage with the provided digest. * * @example * ```typescript * moduleCheck: (data) => { * // Custom logic: check timestamp instead of digest * const stored = StorageManager.loadModule('MyApp', data.code); * const age = Date.now() - stored.metadata.timestamp; * return age < 3600000; // Fresh if less than 1 hour old * } * ``` */ moduleCheck?: ModuleCheck; /** * Field name containing the module identifier * * @defaultValue `'code'` * * @remarks * This field is used to extract the module key from the data objects * passed to {@link checkFreshScripts} and returned by {@link LoadModule}. * * @example * ```typescript * // Default: uses 'code' field * checkFreshScripts([{ code: 'my-module', digest: 'abc' }]); * * // Custom: uses 'id' field * ModuleLoader.initialize(loadFn, { keyField: 'id' }); * checkFreshScripts([{ id: 'my-module', digest: 'abc' }]); * ``` */ keyField?: string; /** * Storage prefix for localStorage keys * * @defaultValue `'DynaJS'` * * @remarks * Used to namespace module storage in localStorage. Different prefixes * allow multiple applications or environments to share the same browser * storage without conflicts. * * @example * ```typescript * // Default storage key: 'DynaJS:module:my-module' * // Custom storage key: 'MyApp:module:my-module' * ModuleLoader.initialize(loadFn, { prefix: 'MyApp' }); * ``` */ prefix?: string; } /** * Singleton class for managing dynamic JavaScript module loading with intelligent caching * * @remarks * `ModuleLoader` provides a complete solution for loading, caching, and managing dynamic * JavaScript modules in browser environments. It offers: * * - **Version Control**: Automatic module freshness checking using content digests * - **Parallel Loading**: Concurrent updates for optimal performance * - **Local Storage Caching**: Persistent module storage with version tracking * - **Singleton Pattern**: Single instance manages all modules in your application * - **Type Safety**: Full TypeScript support with generic type parameters * * @example * ```typescript * // 1. Initialize at application startup * const loader = ModuleLoader.initialize(async (info) => { * const response = await fetch(`/api/modules/${info.code}`); * return response.json(); * }, { * keyField: 'code', * prefix: 'MyApp' * }); * * // 2. Check for and load updates (on app start or periodically) * await loader.checkFreshScripts([ * { code: 'user-form', digest: 'abc123' }, * { code: 'data-grid', digest: 'def456' } * ]); * * // 3. Create module instances * const UserForm = loader.createModule('user-form', { React, Dialog }); * const form = new UserForm({ title: 'User Profile' }); * ``` * * @public */ export default class ModuleLoader { private static instance; private readonly loadModule; private readonly moduleCheck; private readonly prefix; private readonly keyField; private modulesMap; /** * Private constructor for singleton pattern * @param loadModule - Function to load module from remote * @param moduleCheck - Function to check module freshness * @param prefix - Storage prefix * @param keyField - Field name for module key */ private constructor(); /** * Initialize or get the ModuleLoader singleton instance * * @remarks * This method creates the singleton instance on first call and returns the same * instance on subsequent calls. It must be called before any other ModuleLoader methods. * * @param loadModule - Function to load module from remote source * @param options - Optional configuration options * @returns The singleton ModuleLoader instance * * @example * ```typescript * const loader = ModuleLoader.initialize( * async (info) => { * const response = await fetch(`/api/modules/${info.code}`); * return response.json(); * }, * { prefix: 'MyApp', keyField: 'code' } * ); * ``` */ static initialize(loadModule: LoadModule, options?: ModuleLoaderOptions): ModuleLoader; /** * Get the existing ModuleLoader singleton instance * * @remarks * Use this method to retrieve the instance after it has been initialized. * Throws an error if {@link initialize} has not been called yet. * * @returns The ModuleLoader instance * @throws {Error} If instance has not been initialized * * @example * ```typescript * // In main file * ModuleLoader.initialize(loadFn, options); * * // In another file * const loader = ModuleLoader.getInstance(); * await loader.checkFreshScripts(modules); * ``` */ static getInstance(): ModuleLoader; /** * Reset the singleton instance * * @remarks * Primarily useful for testing purposes. Clears the singleton instance * and allows re-initialization with different parameters. * * @example * ```typescript * afterEach(() => { * ModuleLoader.reset(); * }); * ``` */ static reset(): void; /** * Check and update modules that are not fresh * * @remarks * This method performs the following operations: * 1. Checks all modules in parallel using the {@link ModuleCheck} function * 2. Identifies stale modules (those that fail the freshness check) * 3. Removes stale modules from the in-memory cache * 4. Loads all stale modules concurrently in parallel * 5. Saves updated modules to localStorage * 6. Clears the entire in-memory cache to force fresh module creation * * Performance: If N modules need updating and each takes T ms on average: * - Serial loading: N × T ms * - Parallel loading: ~T ms (N× faster) * * @param list - Array of module data objects to check * @returns Promise that resolves when all modules are checked and updated * * @example * ```typescript * // Check and update all modules on app startup * const modules = [ * { code: 'user-form', digest: 'abc123' }, * { code: 'data-grid', digest: 'def456' }, * { code: 'chart-widget', digest: 'ghi789' } * ]; * await loader.checkFreshScripts(modules); * * // Now all modules are up-to-date and can be used * const UserForm = loader.createModule('user-form', { React }); * ``` */ checkFreshScripts(list: Array): Promise; /** * Create or retrieve a cached module instance * * @remarks * This method: * 1. Checks if the module is already cached in memory * 2. If not cached, loads the module script from localStorage * 3. Executes the script with the provided imports * 4. Caches the result for subsequent calls * * The module must have been previously loaded via {@link checkFreshScripts}. * * @typeParam T - Type of the module (e.g., a class constructor) * @param key - The module key/code to load * @param imports - Object containing dependencies to inject into the module scope * @returns The instantiated module or cached instance * @throws {Error} If module not found in storage * * @example * ```typescript * // Create a React component class * const UserForm = loader.createModule('user-form', { * React, * ReactDOM, * Dialog * }); * * // Create a plain class * const UserForm = loader.createModule<{ new(config: any): any }>('user-form', { * FlexiForm, * Dialog * }); * * const form = new UserForm({ title: 'User Registration' }); * ``` */ createModule(key: string, imports: any): T; /** * Get the UI layout configuration for a module * * @remarks * Retrieves the optional `uiLayout` field that was stored with the module. * Useful for components that include layout metadata with their code. * * @typeParam T - Type of the layout object (e.g., interface for form layout structure) * @param key - Module identifier * @returns Parsed layout object or null if not found * * @example * ```typescript * interface FormLayout { * fields: Array<{ name: string; type: string }>; * structure: Record; * } * * const layout = loader.getLayout('user-form'); * if (layout) { * console.log('Form fields:', layout.fields); * console.log('Form layout:', layout.structure); * } * ``` */ getLayout(key: string): T; /** * Get the current digest (version hash) for a module * * @remarks * Useful for comparing versions or displaying version information. * * @param key - Module identifier * @returns Digest string or null if module not found * * @example * ```typescript * const digest = loader.getDigest('user-form'); * console.log(`Current version: ${digest?.substring(0, 8)}`); * ``` */ getDigest(key: string): string | null; /** * Remove a specific module from localStorage and memory cache * * @remarks * Use this for cleanup when a module is no longer needed. * * @param key - Module identifier * * @example * ```typescript * // Remove a deprecated module * loader.removeModule('old-user-form'); * ``` */ removeModule(key: string): void; /** * Clear all modules from localStorage and memory cache * * @remarks * Useful for cleanup operations, testing, or when resetting application state. * * @returns Number of modules cleared * * @example * ```typescript * const count = loader.clearAll(); * console.log(`Cleared ${count} modules from storage`); * ``` */ clearAll(): number; /** * Get all module keys currently stored in localStorage * * @remarks * Useful for debugging, listing available modules, or batch operations. * * @returns Array of module keys * * @example * ```typescript * const keys = loader.getAllModuleKeys(); * console.log('Available modules:', keys); * // ['user-form', 'data-grid', 'chart-widget', ...] * ``` */ getAllModuleKeys(): string[]; /** * Get storage usage statistics for all modules * * @remarks * Returns detailed information about storage usage, useful for: * - Monitoring storage quota * - Implementing cleanup strategies * - Debugging storage issues * * @returns Object containing module count, total size, and per-module details * * @example * ```typescript * const stats = loader.getStorageStats(); * console.log(`Modules: ${stats.moduleCount}`); * console.log(`Total size: ${(stats.totalSize / 1024).toFixed(2)} KB`); * * // Find old modules * const oldModules = stats.modules.filter( * m => Date.now() - m.timestamp > 30 * 24 * 60 * 60 * 1000 * ); * ``` */ getStorageStats(): { moduleCount: number; totalSize: number; modules: Array<{ key: string; size: number; timestamp: number; }>; }; }