UNPKG

ngx-runtime-initializer

Version:

Angular package for loading runtime configuration, managing app settings, and injecting services with post-initialization callbacks, compatible with standalone Angular 19+ applications.

210 lines (201 loc) 7.58 kB
import * as i0 from '@angular/core'; import { WritableSignal, Type } from '@angular/core'; import { CanActivateFn } from '@angular/router'; interface CoreConfig { apiURL: string; debug: boolean; requestTimeout: number; } interface RuntimeConfig { coreConfig: CoreConfig; [key: string]: any; } /** * Implementation of the runtime application configuration. * * Holds core configuration values (API URL, debug mode, request timeout) * and the current status of the application. * * Can be initialized partially using a `Partial<RuntimeConfig>` object, * with optional override for the `status` flag. * * @example * // Default initialization * const config = new AppConfig(); * * // Initialize with custom API URL and enable debug * const config = new AppConfig({ * coreConfig: { apiURL: 'https://api.example.com', debug: true, requestTimeout: 20000 } * }, true); */ declare class AppConfig implements RuntimeConfig { /** * Core configuration object containing API URL, debug flag, and request timeout. */ coreConfig: { apiURL: string; debug: boolean; requestTimeout: number; }; /** * Status of the application (true = up/active, false = down/maintenance). */ status: boolean; /** * Creates a new AppConfig instance. * * @param init - Partial configuration to override default values. * @param status - Optional status override (default is `false`). */ constructor(init?: Partial<RuntimeConfig>, status?: boolean); } /** * Service for managing the application's runtime configuration. * * Provides reactive access to the configuration using Angular signals, * allows updating configuration at runtime, and exposes convenience * methods to retrieve configuration values or application status. * * Additionally, it sets global variables `$CORE_API` and `$DEBUG` * when the configuration is updated. */ declare class AppConfigService { /** * Internal writable signal holding the current application configuration. */ private readonly config; /** * Updates the application configuration. * * This will also update the global variables: * - `$CORE_API` with `config.coreConfig.apiURL` * - `$DEBUG` with `config.coreConfig.debug` * * @param config - The new configuration to set. */ setConfig(config: AppConfig): void; /** * Returns the current status of the application. * * @returns `true` if the app is up/active, `false` if it is down/maintenance. */ getStatus(): boolean; /** * Returns the reactive `WritableSignal` holding the configuration. * * Consumers can subscribe to this signal for reactive updates. * * @returns The `WritableSignal<AppConfig>` instance. */ getConfigSignal(): WritableSignal<AppConfig>; /** * Returns the current configuration snapshot. * * @returns The current `AppConfig` object. */ getConfig(): AppConfig; /** * Retrieves a specific property from the current configuration. * * @typeParam T - Expected type of the property. * @param key - The key of the property in `AppConfig`. * @returns The value of the property if it exists, otherwise `undefined`. * * @example * const apiUrl = service.getConfigProperty<string>('coreConfig').apiURL; */ getConfigProperty<T>(key: keyof AppConfig): T | undefined; static ɵfac: i0.ɵɵFactoryDeclaration<AppConfigService, never>; static ɵprov: i0.ɵɵInjectableDeclaration<AppConfigService>; } /** * Factory function to create a route guard that checks the application status. * * The guard compares the current application status from {@link AppConfigService} * with the expected `shouldBeOk` value. If the actual status does not match, * the user is redirected to the provided `redirectUrl`. * * @param shouldBeOk - Expected status: * - `true`: route is accessible only if the app is up/active * - `false`: route is accessible only if the app is down/maintenance * @param redirectUrl - URL to redirect to when the status does not match `shouldBeOk` * @returns A `CanActivateFn` that enforces the status check. * * @example * // Only allow access when the app is up * const guard = createStatusGuard(true, '/maintenance'); * * // Only allow access when the app is down * const guard = createStatusGuard(false, '/'); */ declare function createStatusGuard(shouldBeOk: boolean, redirectUrl: string): CanActivateFn; /** * Predefined guard that only allows access when the application is UP. * Redirects to `/maintenance` if the application is down. */ declare const InMaintenanceGuard: CanActivateFn; /** * Predefined guard that only allows access when the application is DOWN. * Redirects to `/` if the application is up. */ declare const MaintenanceGuard: CanActivateFn; /** * Options for configuring the runtime initializer. */ declare class RuntimeInitializerOptions { /** URL of the runtime configuration JSON */ configUrl: string; /** Array of Angular service classes to inject and pass to callbacks */ servicesToInject: Type<any>[]; /** * Optional async callback executed after successful configuration load. * Receives the loaded `AppConfig` and an object mapping injected services by class name. */ postInit: (config: AppConfig, services: Record<string, any>) => Promise<void>; /** * Optional callback executed if initialization fails. * Receives the error and injected services object. */ handleInitializationFailure: (error: any, services: Record<string, any>) => void; /** * Constructor for fast initialization or custom values. * @param configUrl - URL of the config JSON * @param servicesToInject - Array of Angular services to inject * @param postInit - Callback after successful initialization * @param handleInitializationFailure - Callback on initialization failure */ constructor(configUrl?: string, servicesToInject?: Type<any>[], postInit?: (config: AppConfig, services: Record<string, any>) => Promise<void>, handleInitializationFailure?: (error: any, services: Record<string, any>) => void); } /** * Provides an Angular application initializer that loads runtime configuration from a JSON file * and optionally injects additional services. * * @param options - Configuration options for the runtime initializer. * * @returns A provider for Angular's `APP_INITIALIZER`. * * @example * // Basic usage: load config from default 'config.json' * provideRuntimeInitializer({}); * * @example * // With custom services and post-init callback * provideRuntimeInitializer({ * configUrl: '/assets/runtime-config.json', * servicesToInject: [MyService1, MyService2], * postInit: async (config, services) => { * console.log('Config loaded:', config); * services.MyService1?.initialize(); * }, * handleInitializationFailure: (error, services) => { * console.warn('Failed to initialize runtime config:', error); * } * }); */ declare function provideRuntimeInitializer({ configUrl, servicesToInject, postInit, handleInitializationFailure, }: RuntimeInitializerOptions): i0.EnvironmentProviders; declare global { const $CORE_API: string; const $DEBUG: boolean; } export { AppConfig, AppConfigService, InMaintenanceGuard, MaintenanceGuard, RuntimeInitializerOptions, createStatusGuard, provideRuntimeInitializer }; export type { CoreConfig, RuntimeConfig };