@opensourcekd/ng-common-libs 1.2.4 → 1.2.6

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/dist/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  import { Observable, ReplaySubject } from 'rxjs';
2
- import { HttpClient, HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
3
2
  import { EventType } from 'mitt';
4
- import { CanActivateFn } from '@angular/router';
5
3
 
6
4
  /**
7
5
  * Event payload interface
@@ -57,443 +55,25 @@ declare class EventBus {
57
55
  }
58
56
 
59
57
  /**
60
- * Token configuration interface
61
- */
62
- interface TokenConfig {
63
- tokenKey?: string;
64
- refreshTokenKey?: string;
65
- useSessionStorage?: boolean;
66
- }
67
- /**
68
- * TokenManager - Manages authentication tokens
69
- * Framework-agnostic implementation using browser storage APIs
70
- * Handles storage, retrieval, and validation of JWT tokens
71
- *
72
- * @example
73
- * ```typescript
74
- * const tokenManager = new TokenManager();
58
+ * Framework-agnostic Configuration
59
+ * Centralized configuration for all consuming applications
75
60
  *
76
- * // Store a token
77
- * tokenManager.setToken('your-jwt-token');
61
+ * This configuration can be used across different frameworks (Angular, React, Vue, etc.)
62
+ * and by various Micro-Frontends (MFEs) and shell applications.
78
63
  *
79
- * // Check if authenticated
80
- * if (tokenManager.isAuthenticated()) {
81
- * const userData = tokenManager.getUserFromToken();
82
- * }
83
- * ```
64
+ * Values are statically configured during build time from GitHub repository variables.
84
65
  */
85
- declare class TokenManager {
86
- private TOKEN_KEY;
87
- private REFRESH_TOKEN_KEY;
88
- private useSessionStorage;
89
- /**
90
- * Configure token manager
91
- */
92
- configure(config: TokenConfig): void;
93
- /**
94
- * Get the storage mechanism based on configuration
95
- */
96
- private getStorage;
97
- /**
98
- * Set authentication token
99
- */
100
- setToken(token: string): void;
101
- /**
102
- * Get authentication token
103
- */
104
- getToken(): string | null;
105
- /**
106
- * Remove authentication token
107
- */
108
- removeToken(): void;
109
- /**
110
- * Set refresh token
111
- */
112
- setRefreshToken(token: string): void;
113
- /**
114
- * Get refresh token
115
- */
116
- getRefreshToken(): string | null;
117
- /**
118
- * Remove refresh token
119
- */
120
- removeRefreshToken(): void;
121
- /**
122
- * Clear all tokens
123
- */
124
- clearTokens(): void;
125
- /**
126
- * Check if token exists
127
- */
128
- hasToken(): boolean;
129
- /**
130
- * Decode JWT token (without verification)
131
- * @param token - JWT token to decode
132
- * @returns Decoded token payload or null if invalid
133
- */
134
- decodeToken(token?: string): any;
135
- /**
136
- * Check if token is expired
137
- * @param token - Optional token to check (defaults to stored token)
138
- * @returns true if token is expired or invalid
139
- */
140
- isTokenExpired(token?: string): boolean;
141
- /**
142
- * Check if user is authenticated (has valid, non-expired token)
143
- */
144
- isAuthenticated(): boolean;
145
- /**
146
- * Get token expiration date
147
- */
148
- getTokenExpirationDate(token?: string): Date | null;
149
- /**
150
- * Get user data from token
151
- */
152
- getUserFromToken(token?: string): any;
153
- }
154
-
155
66
  /**
156
- * StorageManager - Type-safe wrapper for browser storage
157
- * Framework-agnostic implementation using browser storage APIs
158
- * Provides JSON serialization/deserialization and error handling
159
- *
160
- * @example
161
- * ```typescript
162
- * const storage = new StorageManager();
67
+ * Application configuration object
68
+ * Contains all environment-specific variables
163
69
  *
164
- * // Store data
165
- * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
166
- *
167
- * // Retrieve data
168
- * const prefs = storage.getLocal('user-prefs');
169
- *
170
- * // With expiration
171
- * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
172
- * ```
70
+ * These values are replaced during build time with actual values from GitHub repository variables.
173
71
  */
174
- declare class StorageManager {
175
- /**
176
- * Set item in localStorage with JSON serialization
177
- */
178
- setLocal<T>(key: string, value: T): boolean;
179
- /**
180
- * Get item from localStorage with JSON deserialization
181
- */
182
- getLocal<T>(key: string, defaultValue?: T): T | null;
183
- /**
184
- * Remove item from localStorage
185
- */
186
- removeLocal(key: string): void;
187
- /**
188
- * Clear all localStorage items
189
- */
190
- clearLocal(): void;
191
- /**
192
- * Check if key exists in localStorage
193
- */
194
- hasLocal(key: string): boolean;
195
- /**
196
- * Get all localStorage keys
197
- */
198
- getLocalKeys(): string[];
199
- /**
200
- * Set item in sessionStorage with JSON serialization
201
- */
202
- setSession<T>(key: string, value: T): boolean;
203
- /**
204
- * Get item from sessionStorage with JSON deserialization
205
- */
206
- getSession<T>(key: string, defaultValue?: T): T | null;
207
- /**
208
- * Remove item from sessionStorage
209
- */
210
- removeSession(key: string): void;
211
- /**
212
- * Clear all sessionStorage items
213
- */
214
- clearSession(): void;
215
- /**
216
- * Check if key exists in sessionStorage
217
- */
218
- hasSession(key: string): boolean;
219
- /**
220
- * Get all sessionStorage keys
221
- */
222
- getSessionKeys(): string[];
223
- /**
224
- * Set item with expiration time
225
- * @param key - Storage key
226
- * @param value - Value to store
227
- * @param expirationMs - Expiration time in milliseconds
228
- * @param useSession - Use sessionStorage instead of localStorage
229
- */
230
- setWithExpiration<T>(key: string, value: T, expirationMs: number, useSession?: boolean): boolean;
231
- /**
232
- * Get item with expiration check
233
- * Returns null if item is expired
234
- */
235
- getWithExpiration<T>(key: string, useSession?: boolean): T | null;
236
- }
237
-
238
- /**
239
- * Log level enum
240
- */
241
- declare enum LogLevel {
242
- DEBUG = 0,
243
- INFO = 1,
244
- WARN = 2,
245
- ERROR = 3,
246
- NONE = 4
247
- }
248
- /**
249
- * Logger configuration
250
- */
251
- interface LoggerConfig {
252
- level?: LogLevel;
253
- enableTimestamp?: boolean;
254
- enableStackTrace?: boolean;
255
- prefix?: string;
256
- }
257
- /**
258
- * Logger - Centralized logging utility
259
- * Framework-agnostic implementation using browser console APIs
260
- * Supports different log levels and can be configured globally
261
- *
262
- * @example
263
- * ```typescript
264
- * const logger = new Logger();
265
- *
266
- * // Configure
267
- * logger.configure({
268
- * level: LogLevel.DEBUG,
269
- * enableTimestamp: true,
270
- * prefix: 'MyApp'
271
- * });
272
- *
273
- * // Use
274
- * logger.info('User logged in', { userId: '123' });
275
- * logger.error('Failed to load data', error);
276
- * ```
277
- */
278
- declare class Logger {
279
- private config;
280
- /**
281
- * Configure the logger
282
- */
283
- configure(config: LoggerConfig): void;
284
- /**
285
- * Set log level
286
- */
287
- setLevel(level: LogLevel): void;
288
- /**
289
- * Get current log level
290
- */
291
- getLevel(): LogLevel;
292
- /**
293
- * Format log message with timestamp and prefix
294
- */
295
- private formatMessage;
296
- /**
297
- * Check if log level should be logged
298
- */
299
- private shouldLog;
300
- /**
301
- * Log debug message
302
- */
303
- debug(message: string, ...args: any[]): void;
304
- /**
305
- * Log info message
306
- */
307
- info(message: string, ...args: any[]): void;
308
- /**
309
- * Log warning message
310
- */
311
- warn(message: string, ...args: any[]): void;
312
- /**
313
- * Log error message
314
- */
315
- error(message: string, error?: any, ...args: any[]): void;
316
- /**
317
- * Log a group of messages
318
- */
319
- group(label: string, callback: () => void): void;
320
- /**
321
- * Log a collapsed group of messages
322
- */
323
- groupCollapsed(label: string, callback: () => void): void;
324
- /**
325
- * Log a table (useful for arrays of objects)
326
- */
327
- table(data: any, columns?: string[]): void;
328
- /**
329
- * Log execution time of a function
330
- */
331
- time<T>(label: string, fn: () => Promise<T> | T): Promise<T>;
332
- }
333
-
334
- /**
335
- * NgEventEmitter - Angular service wrapper for EventBus
336
- * Provides Angular dependency injection support for the framework-agnostic EventBus
337
- *
338
- * @example
339
- * ```typescript
340
- * import { Component, inject } from '@angular/core';
341
- * import { NgEventEmitter } from 'common-libs';
342
- *
343
- * @Component({
344
- * selector: 'app-example',
345
- * template: '...'
346
- * })
347
- * export class ExampleComponent {
348
- * private eventEmitter = inject(NgEventEmitter);
349
- *
350
- * ngOnInit() {
351
- * this.eventEmitter.on('user:login').subscribe(data => {
352
- * console.log('User logged in:', data);
353
- * });
354
- * }
355
- *
356
- * login() {
357
- * this.eventEmitter.emit('user:login', { userId: '123' });
358
- * }
359
- * }
360
- * ```
361
- */
362
- declare class NgEventEmitter extends EventBus {
363
- constructor();
364
- }
365
-
366
- /**
367
- * TokenService - Angular service wrapper for TokenManager
368
- * Provides Angular dependency injection support for the framework-agnostic TokenManager
369
- *
370
- * @example
371
- * ```typescript
372
- * import { Component, inject } from '@angular/core';
373
- * import { TokenService } from 'common-libs';
374
- *
375
- * export class AuthService {
376
- * private tokenService = inject(TokenService);
377
- *
378
- * login(token: string) {
379
- * this.tokenService.setToken(token);
380
- * }
381
- *
382
- * isAuthenticated(): boolean {
383
- * return this.tokenService.isAuthenticated();
384
- * }
385
- * }
386
- * ```
387
- */
388
- declare class TokenService extends TokenManager {
389
- constructor();
390
- }
391
-
392
- /**
393
- * StorageService - Angular service wrapper for StorageManager
394
- * Provides Angular dependency injection support for the framework-agnostic StorageManager
395
- *
396
- * @example
397
- * ```typescript
398
- * import { Component, inject } from '@angular/core';
399
- * import { StorageService } from 'common-libs';
400
- *
401
- * export class UserPreferencesService {
402
- * private storage = inject(StorageService);
403
- *
404
- * savePreferences(prefs: any) {
405
- * this.storage.setLocal('user-prefs', prefs);
406
- * }
407
- *
408
- * getPreferences() {
409
- * return this.storage.getLocal('user-prefs');
410
- * }
411
- * }
412
- * ```
413
- */
414
- declare class StorageService extends StorageManager {
415
- constructor();
416
- }
417
-
418
- /**
419
- * LoggerService - Angular service wrapper for Logger
420
- * Provides Angular dependency injection support for the framework-agnostic Logger
421
- *
422
- * @example
423
- * ```typescript
424
- * import { Component, inject } from '@angular/core';
425
- * import { LoggerService, LogLevel } from 'common-libs';
426
- *
427
- * export class MyService {
428
- * private logger = inject(LoggerService);
429
- *
430
- * constructor() {
431
- * this.logger.configure({
432
- * level: LogLevel.DEBUG,
433
- * prefix: 'MyApp'
434
- * });
435
- * }
436
- *
437
- * doSomething() {
438
- * this.logger.info('Doing something');
439
- * }
440
- * }
441
- * ```
442
- */
443
- declare class LoggerService extends Logger {
444
- constructor();
445
- }
446
-
447
- /**
448
- * PermissionService - Manages user permissions and roles
449
- */
450
- declare class PermissionService {
451
- private tokenService;
452
- /**
453
- * Check if user has a specific permission
454
- */
455
- hasPermission(permission: string): boolean;
456
- /**
457
- * Check if user has any of the specified permissions
458
- */
459
- hasAnyPermission(permissions: string[]): boolean;
460
- /**
461
- * Check if user has all of the specified permissions
462
- */
463
- hasAllPermissions(permissions: string[]): boolean;
464
- /**
465
- * Check if user has a specific role
466
- */
467
- hasRole(role: string): boolean;
468
- /**
469
- * Check if user has any of the specified roles
470
- */
471
- hasAnyRole(roles: string[]): boolean;
472
- /**
473
- * Check if user has all of the specified roles
474
- */
475
- hasAllRoles(roles: string[]): boolean;
476
- /**
477
- * Get all user permissions
478
- */
479
- getPermissions(): string[];
480
- /**
481
- * Get all user roles
482
- */
483
- getRoles(): string[];
484
- /**
485
- * Get user ID from token
486
- */
487
- getUserId(): string | null;
488
- /**
489
- * Get username from token
490
- */
491
- getUsername(): string | null;
492
- /**
493
- * Get user email from token
494
- */
495
- getUserEmail(): string | null;
496
- }
72
+ declare const APP_CONFIG: {
73
+ auth0Domain: string;
74
+ auth0ClientId: string;
75
+ apiUrl: string;
76
+ };
497
77
 
498
78
  /**
499
79
  * EventBusService - Angular service for cross-application event communication
@@ -613,15 +193,13 @@ interface UserData {
613
193
  * To enable navigation after auth operations, uncomment the marked sections in consuming components.
614
194
  */
615
195
  declare class AuthService {
616
- private http;
617
196
  private eventBus;
618
- id: string;
619
197
  private readonly STANDARD_JWT_CLAIMS;
620
198
  private auth0Client;
621
199
  private initializationPromise;
622
200
  private userSubject;
623
201
  user$: Observable<UserInfo | null>;
624
- constructor(http: HttpClient, eventBus: EventBusService);
202
+ constructor(eventBus: EventBusService);
625
203
  /**
626
204
  * Initialize Auth0 client
627
205
  */
@@ -655,6 +233,13 @@ declare class AuthService {
655
233
  success: boolean;
656
234
  appState?: any;
657
235
  }>;
236
+ /**
237
+ * Decode and log the access token to console
238
+ * NOTE: This logs sensitive token information to console for debugging purposes.
239
+ * In production environments, consider disabling this or filtering console logs.
240
+ * @param token - The JWT access token
241
+ */
242
+ private decodeAndLogToken;
658
243
  /**
659
244
  * Log all user claims for debugging
660
245
  * @param user - User info from Auth0
@@ -762,199 +347,6 @@ declare class AuthService {
762
347
  private emitAuthEvent;
763
348
  }
764
349
 
765
- /**
766
- * Auth guard configuration
767
- */
768
- interface AuthGuardConfig {
769
- redirectUrl?: string;
770
- checkExpiration?: boolean;
771
- }
772
- /**
773
- * Factory function to create an auth guard with configuration
774
- *
775
- * @example
776
- * ```typescript
777
- * // In routes
778
- * {
779
- * path: 'dashboard',
780
- * component: DashboardComponent,
781
- * canActivate: [createAuthGuard({ redirectUrl: '/login' })]
782
- * }
783
- * ```
784
- */
785
- declare function createAuthGuard(config?: AuthGuardConfig): CanActivateFn;
786
- /**
787
- * Default auth guard - redirects to '/login' if not authenticated
788
- */
789
- declare const authGuard: CanActivateFn;
790
- /**
791
- * Permission-based guard factory
792
- * Checks if user has required permissions from token
793
- *
794
- * @example
795
- * ```typescript
796
- * {
797
- * path: 'admin',
798
- * component: AdminComponent,
799
- * canActivate: [createPermissionGuard(['admin', 'editor'])]
800
- * }
801
- * ```
802
- */
803
- declare function createPermissionGuard(requiredPermissions: string[], config?: AuthGuardConfig): CanActivateFn;
804
- /**
805
- * Role-based guard factory
806
- * Checks if user has required role from token
807
- *
808
- * @example
809
- * ```typescript
810
- * {
811
- * path: 'admin',
812
- * component: AdminComponent,
813
- * canActivate: [createRoleGuard(['admin'])]
814
- * }
815
- * ```
816
- */
817
- declare function createRoleGuard(requiredRoles: string[], config?: AuthGuardConfig): CanActivateFn;
818
-
819
- /**
820
- * Auth interceptor configuration
821
- */
822
- interface AuthInterceptorConfig {
823
- headerName?: string;
824
- tokenPrefix?: string;
825
- excludedUrls?: string[];
826
- }
827
- /**
828
- * Configure the auth interceptor
829
- */
830
- declare function configureAuthInterceptor(config: AuthInterceptorConfig): void;
831
- /**
832
- * Auth Interceptor - Automatically adds authentication token to HTTP requests
833
- *
834
- * @example
835
- * ```typescript
836
- * // In app.config.ts
837
- * export const appConfig: ApplicationConfig = {
838
- * providers: [
839
- * provideHttpClient(
840
- * withInterceptors([authInterceptor])
841
- * )
842
- * ]
843
- * };
844
- * ```
845
- */
846
- declare const authInterceptor: HttpInterceptorFn;
847
-
848
- /**
849
- * Error handling configuration
850
- */
851
- interface ErrorHandlingConfig {
852
- enableLogging?: boolean;
853
- retryAttempts?: number;
854
- retryDelay?: number;
855
- retryStatusCodes?: number[];
856
- excludedUrls?: string[];
857
- }
858
- /**
859
- * Configure the error handling interceptor
860
- */
861
- declare function configureErrorHandling(config: ErrorHandlingConfig): void;
862
- /**
863
- * Error handling interceptor - Handles HTTP errors and retries
864
- *
865
- * @example
866
- * ```typescript
867
- * // In app.config.ts
868
- * export const appConfig: ApplicationConfig = {
869
- * providers: [
870
- * provideHttpClient(
871
- * withInterceptors([errorHandlingInterceptor])
872
- * )
873
- * ]
874
- * };
875
- *
876
- * // Configure retry behavior
877
- * configureErrorHandling({
878
- * retryAttempts: 3,
879
- * retryDelay: 2000,
880
- * retryStatusCodes: [500, 502, 503]
881
- * });
882
- * ```
883
- */
884
- declare const errorHandlingInterceptor: HttpInterceptorFn;
885
- /**
886
- * HTTP Error class with additional context
887
- */
888
- declare class HttpError extends Error {
889
- status: number;
890
- statusText: string;
891
- url: string;
892
- originalError: HttpErrorResponse;
893
- constructor(status: number, statusText: string, url: string, originalError: HttpErrorResponse);
894
- }
895
- /**
896
- * Parse HTTP error and return user-friendly message
897
- */
898
- declare function parseHttpError(error: HttpErrorResponse): string;
899
- /**
900
- * Check if error is a network error
901
- */
902
- declare function isNetworkError(error: HttpErrorResponse): boolean;
903
- /**
904
- * Check if error is a server error (5xx)
905
- */
906
- declare function isServerError(error: HttpErrorResponse): boolean;
907
- /**
908
- * Check if error is a client error (4xx)
909
- */
910
- declare function isClientError(error: HttpErrorResponse): boolean;
911
-
912
- /**
913
- * Cache configuration
914
- */
915
- interface CacheConfig {
916
- enabled?: boolean;
917
- maxAge?: number;
918
- excludedUrls?: string[];
919
- cacheableUrls?: string[];
920
- cacheMethods?: string[];
921
- }
922
- /**
923
- * Configure the caching interceptor
924
- */
925
- declare function configureCaching(config: CacheConfig): void;
926
- /**
927
- * Clear all cached entries
928
- */
929
- declare function clearCache(): void;
930
- /**
931
- * Clear cache entry for specific URL
932
- */
933
- declare function clearCacheEntry(url: string): void;
934
- /**
935
- * Caching interceptor - Caches HTTP GET requests
936
- *
937
- * @example
938
- * ```typescript
939
- * // In app.config.ts
940
- * export const appConfig: ApplicationConfig = {
941
- * providers: [
942
- * provideHttpClient(
943
- * withInterceptors([cachingInterceptor])
944
- * )
945
- * ]
946
- * };
947
- *
948
- * // Configure caching
949
- * configureCaching({
950
- * enabled: true,
951
- * maxAge: 300000, // 5 minutes
952
- * cacheableUrls: ['/api/users', '/api/products']
953
- * });
954
- * ```
955
- */
956
- declare const cachingInterceptor: HttpInterceptorFn;
957
-
958
350
  /**
959
351
  * Auth0 Configuration
960
352
  * Centralized configuration for Auth0 integration
@@ -1031,5 +423,5 @@ declare function removeStorageItem(key: string, storageType?: 'localStorage' | '
1031
423
  */
1032
424
  declare function configureAuth0(config: Partial<typeof AUTH0_CONFIG>): void;
1033
425
 
1034
- export { AUTH0_CONFIG, AuthService, EventBus, EventBusService, HttpError, LogLevel, Logger, LoggerService, NgEventEmitter, PermissionService, STORAGE_CONFIG, STORAGE_KEYS, StorageManager, StorageService, TokenManager, TokenService, authGuard, authInterceptor, cachingInterceptor, clearCache, clearCacheEntry, configureAuth0, configureAuthInterceptor, configureCaching, configureErrorHandling, createAuthGuard, createPermissionGuard, createRoleGuard, errorHandlingInterceptor, getStorageItem, isClientError, isNetworkError, isServerError, parseHttpError, removeStorageItem, setStorageItem };
1035
- export type { AuthGuardConfig, AuthInterceptorConfig, CacheConfig, ErrorHandlingConfig, EventPayload, LoggerConfig, TokenConfig, UserData, UserInfo };
426
+ export { APP_CONFIG, AUTH0_CONFIG, AuthService, EventBus, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, configureAuth0, getStorageItem, removeStorageItem, setStorageItem };
427
+ export type { EventPayload, UserData, UserInfo };