@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.
@@ -1,499 +1,5 @@
1
- import { Observable, ReplaySubject } from 'rxjs';
2
- import { HttpClient, HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
1
+ import { ReplaySubject, Observable } from 'rxjs';
3
2
  import { EventType } from 'mitt';
4
- import { CanActivateFn } from '@angular/router';
5
-
6
- /**
7
- * Event payload interface
8
- */
9
- interface EventPayload<T = any> {
10
- type: string;
11
- data: T;
12
- timestamp?: number;
13
- }
14
- /**
15
- * EventBus - A centralized event bus for application-wide communication
16
- * Framework-agnostic implementation using only RxJS
17
- *
18
- * @example
19
- * ```typescript
20
- * // Create an instance
21
- * const eventBus = new EventBus();
22
- *
23
- * // Emit an event
24
- * eventBus.emit('user:login', { userId: '123', username: 'john' });
25
- *
26
- * // Subscribe to an event
27
- * eventBus.on('user:login').subscribe(data => {
28
- * console.log('User logged in:', data);
29
- * });
30
- * ```
31
- */
32
- declare class EventBus {
33
- private eventSubject;
34
- /**
35
- * Emit an event with optional data
36
- * @param eventType - The type/name of the event
37
- * @param data - Optional data to send with the event
38
- */
39
- emit<T = any>(eventType: string, data?: T): void;
40
- /**
41
- * Subscribe to a specific event type
42
- * @param eventType - The type/name of the event to listen for
43
- * @returns Observable that emits the event data
44
- */
45
- on<T = any>(eventType: string): Observable<T>;
46
- /**
47
- * Subscribe to multiple event types
48
- * @param eventTypes - Array of event types to listen for
49
- * @returns Observable that emits the full event payload
50
- */
51
- onMultiple(eventTypes: string[]): Observable<EventPayload>;
52
- /**
53
- * Subscribe to all events
54
- * @returns Observable that emits all event payloads
55
- */
56
- onAll(): Observable<EventPayload>;
57
- }
58
-
59
- /**
60
- * NgEventEmitter - Angular service wrapper for EventBus
61
- * Provides Angular dependency injection support for the framework-agnostic EventBus
62
- *
63
- * @example
64
- * ```typescript
65
- * import { Component, inject } from '@angular/core';
66
- * import { NgEventEmitter } from 'common-libs';
67
- *
68
- * @Component({
69
- * selector: 'app-example',
70
- * template: '...'
71
- * })
72
- * export class ExampleComponent {
73
- * private eventEmitter = inject(NgEventEmitter);
74
- *
75
- * ngOnInit() {
76
- * this.eventEmitter.on('user:login').subscribe(data => {
77
- * console.log('User logged in:', data);
78
- * });
79
- * }
80
- *
81
- * login() {
82
- * this.eventEmitter.emit('user:login', { userId: '123' });
83
- * }
84
- * }
85
- * ```
86
- */
87
- declare class NgEventEmitter extends EventBus {
88
- constructor();
89
- }
90
-
91
- /**
92
- * Token configuration interface
93
- */
94
- interface TokenConfig {
95
- tokenKey?: string;
96
- refreshTokenKey?: string;
97
- useSessionStorage?: boolean;
98
- }
99
- /**
100
- * TokenManager - Manages authentication tokens
101
- * Framework-agnostic implementation using browser storage APIs
102
- * Handles storage, retrieval, and validation of JWT tokens
103
- *
104
- * @example
105
- * ```typescript
106
- * const tokenManager = new TokenManager();
107
- *
108
- * // Store a token
109
- * tokenManager.setToken('your-jwt-token');
110
- *
111
- * // Check if authenticated
112
- * if (tokenManager.isAuthenticated()) {
113
- * const userData = tokenManager.getUserFromToken();
114
- * }
115
- * ```
116
- */
117
- declare class TokenManager {
118
- private TOKEN_KEY;
119
- private REFRESH_TOKEN_KEY;
120
- private useSessionStorage;
121
- /**
122
- * Configure token manager
123
- */
124
- configure(config: TokenConfig): void;
125
- /**
126
- * Get the storage mechanism based on configuration
127
- */
128
- private getStorage;
129
- /**
130
- * Set authentication token
131
- */
132
- setToken(token: string): void;
133
- /**
134
- * Get authentication token
135
- */
136
- getToken(): string | null;
137
- /**
138
- * Remove authentication token
139
- */
140
- removeToken(): void;
141
- /**
142
- * Set refresh token
143
- */
144
- setRefreshToken(token: string): void;
145
- /**
146
- * Get refresh token
147
- */
148
- getRefreshToken(): string | null;
149
- /**
150
- * Remove refresh token
151
- */
152
- removeRefreshToken(): void;
153
- /**
154
- * Clear all tokens
155
- */
156
- clearTokens(): void;
157
- /**
158
- * Check if token exists
159
- */
160
- hasToken(): boolean;
161
- /**
162
- * Decode JWT token (without verification)
163
- * @param token - JWT token to decode
164
- * @returns Decoded token payload or null if invalid
165
- */
166
- decodeToken(token?: string): any;
167
- /**
168
- * Check if token is expired
169
- * @param token - Optional token to check (defaults to stored token)
170
- * @returns true if token is expired or invalid
171
- */
172
- isTokenExpired(token?: string): boolean;
173
- /**
174
- * Check if user is authenticated (has valid, non-expired token)
175
- */
176
- isAuthenticated(): boolean;
177
- /**
178
- * Get token expiration date
179
- */
180
- getTokenExpirationDate(token?: string): Date | null;
181
- /**
182
- * Get user data from token
183
- */
184
- getUserFromToken(token?: string): any;
185
- }
186
-
187
- /**
188
- * TokenService - Angular service wrapper for TokenManager
189
- * Provides Angular dependency injection support for the framework-agnostic TokenManager
190
- *
191
- * @example
192
- * ```typescript
193
- * import { Component, inject } from '@angular/core';
194
- * import { TokenService } from 'common-libs';
195
- *
196
- * export class AuthService {
197
- * private tokenService = inject(TokenService);
198
- *
199
- * login(token: string) {
200
- * this.tokenService.setToken(token);
201
- * }
202
- *
203
- * isAuthenticated(): boolean {
204
- * return this.tokenService.isAuthenticated();
205
- * }
206
- * }
207
- * ```
208
- */
209
- declare class TokenService extends TokenManager {
210
- constructor();
211
- }
212
-
213
- /**
214
- * StorageManager - Type-safe wrapper for browser storage
215
- * Framework-agnostic implementation using browser storage APIs
216
- * Provides JSON serialization/deserialization and error handling
217
- *
218
- * @example
219
- * ```typescript
220
- * const storage = new StorageManager();
221
- *
222
- * // Store data
223
- * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
224
- *
225
- * // Retrieve data
226
- * const prefs = storage.getLocal('user-prefs');
227
- *
228
- * // With expiration
229
- * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
230
- * ```
231
- */
232
- declare class StorageManager {
233
- /**
234
- * Set item in localStorage with JSON serialization
235
- */
236
- setLocal<T>(key: string, value: T): boolean;
237
- /**
238
- * Get item from localStorage with JSON deserialization
239
- */
240
- getLocal<T>(key: string, defaultValue?: T): T | null;
241
- /**
242
- * Remove item from localStorage
243
- */
244
- removeLocal(key: string): void;
245
- /**
246
- * Clear all localStorage items
247
- */
248
- clearLocal(): void;
249
- /**
250
- * Check if key exists in localStorage
251
- */
252
- hasLocal(key: string): boolean;
253
- /**
254
- * Get all localStorage keys
255
- */
256
- getLocalKeys(): string[];
257
- /**
258
- * Set item in sessionStorage with JSON serialization
259
- */
260
- setSession<T>(key: string, value: T): boolean;
261
- /**
262
- * Get item from sessionStorage with JSON deserialization
263
- */
264
- getSession<T>(key: string, defaultValue?: T): T | null;
265
- /**
266
- * Remove item from sessionStorage
267
- */
268
- removeSession(key: string): void;
269
- /**
270
- * Clear all sessionStorage items
271
- */
272
- clearSession(): void;
273
- /**
274
- * Check if key exists in sessionStorage
275
- */
276
- hasSession(key: string): boolean;
277
- /**
278
- * Get all sessionStorage keys
279
- */
280
- getSessionKeys(): string[];
281
- /**
282
- * Set item with expiration time
283
- * @param key - Storage key
284
- * @param value - Value to store
285
- * @param expirationMs - Expiration time in milliseconds
286
- * @param useSession - Use sessionStorage instead of localStorage
287
- */
288
- setWithExpiration<T>(key: string, value: T, expirationMs: number, useSession?: boolean): boolean;
289
- /**
290
- * Get item with expiration check
291
- * Returns null if item is expired
292
- */
293
- getWithExpiration<T>(key: string, useSession?: boolean): T | null;
294
- }
295
-
296
- /**
297
- * StorageService - Angular service wrapper for StorageManager
298
- * Provides Angular dependency injection support for the framework-agnostic StorageManager
299
- *
300
- * @example
301
- * ```typescript
302
- * import { Component, inject } from '@angular/core';
303
- * import { StorageService } from 'common-libs';
304
- *
305
- * export class UserPreferencesService {
306
- * private storage = inject(StorageService);
307
- *
308
- * savePreferences(prefs: any) {
309
- * this.storage.setLocal('user-prefs', prefs);
310
- * }
311
- *
312
- * getPreferences() {
313
- * return this.storage.getLocal('user-prefs');
314
- * }
315
- * }
316
- * ```
317
- */
318
- declare class StorageService extends StorageManager {
319
- constructor();
320
- }
321
-
322
- /**
323
- * Log level enum
324
- */
325
- declare enum LogLevel {
326
- DEBUG = 0,
327
- INFO = 1,
328
- WARN = 2,
329
- ERROR = 3,
330
- NONE = 4
331
- }
332
- /**
333
- * Logger configuration
334
- */
335
- interface LoggerConfig {
336
- level?: LogLevel;
337
- enableTimestamp?: boolean;
338
- enableStackTrace?: boolean;
339
- prefix?: string;
340
- }
341
- /**
342
- * Logger - Centralized logging utility
343
- * Framework-agnostic implementation using browser console APIs
344
- * Supports different log levels and can be configured globally
345
- *
346
- * @example
347
- * ```typescript
348
- * const logger = new Logger();
349
- *
350
- * // Configure
351
- * logger.configure({
352
- * level: LogLevel.DEBUG,
353
- * enableTimestamp: true,
354
- * prefix: 'MyApp'
355
- * });
356
- *
357
- * // Use
358
- * logger.info('User logged in', { userId: '123' });
359
- * logger.error('Failed to load data', error);
360
- * ```
361
- */
362
- declare class Logger {
363
- private config;
364
- /**
365
- * Configure the logger
366
- */
367
- configure(config: LoggerConfig): void;
368
- /**
369
- * Set log level
370
- */
371
- setLevel(level: LogLevel): void;
372
- /**
373
- * Get current log level
374
- */
375
- getLevel(): LogLevel;
376
- /**
377
- * Format log message with timestamp and prefix
378
- */
379
- private formatMessage;
380
- /**
381
- * Check if log level should be logged
382
- */
383
- private shouldLog;
384
- /**
385
- * Log debug message
386
- */
387
- debug(message: string, ...args: any[]): void;
388
- /**
389
- * Log info message
390
- */
391
- info(message: string, ...args: any[]): void;
392
- /**
393
- * Log warning message
394
- */
395
- warn(message: string, ...args: any[]): void;
396
- /**
397
- * Log error message
398
- */
399
- error(message: string, error?: any, ...args: any[]): void;
400
- /**
401
- * Log a group of messages
402
- */
403
- group(label: string, callback: () => void): void;
404
- /**
405
- * Log a collapsed group of messages
406
- */
407
- groupCollapsed(label: string, callback: () => void): void;
408
- /**
409
- * Log a table (useful for arrays of objects)
410
- */
411
- table(data: any, columns?: string[]): void;
412
- /**
413
- * Log execution time of a function
414
- */
415
- time<T>(label: string, fn: () => Promise<T> | T): Promise<T>;
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
- }
497
3
 
498
4
  /**
499
5
  * EventBusService - Angular service for cross-application event communication
@@ -613,15 +119,13 @@ interface UserData {
613
119
  * To enable navigation after auth operations, uncomment the marked sections in consuming components.
614
120
  */
615
121
  declare class AuthService {
616
- private http;
617
122
  private eventBus;
618
- id: string;
619
123
  private readonly STANDARD_JWT_CLAIMS;
620
124
  private auth0Client;
621
125
  private initializationPromise;
622
126
  private userSubject;
623
127
  user$: Observable<UserInfo | null>;
624
- constructor(http: HttpClient, eventBus: EventBusService);
128
+ constructor(eventBus: EventBusService);
625
129
  /**
626
130
  * Initialize Auth0 client
627
131
  */
@@ -655,6 +159,13 @@ declare class AuthService {
655
159
  success: boolean;
656
160
  appState?: any;
657
161
  }>;
162
+ /**
163
+ * Decode and log the access token to console
164
+ * NOTE: This logs sensitive token information to console for debugging purposes.
165
+ * In production environments, consider disabling this or filtering console logs.
166
+ * @param token - The JWT access token
167
+ */
168
+ private decodeAndLogToken;
658
169
  /**
659
170
  * Log all user claims for debugging
660
171
  * @param user - User info from Auth0
@@ -762,199 +273,6 @@ declare class AuthService {
762
273
  private emitAuthEvent;
763
274
  }
764
275
 
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
276
  /**
959
277
  * Auth0 Configuration
960
278
  * Centralized configuration for Auth0 integration
@@ -1031,5 +349,5 @@ declare function removeStorageItem(key: string, storageType?: 'localStorage' | '
1031
349
  */
1032
350
  declare function configureAuth0(config: Partial<typeof AUTH0_CONFIG>): void;
1033
351
 
1034
- export { AUTH0_CONFIG, AuthService, EventBusService, HttpError, LogLevel, LoggerService, NgEventEmitter, PermissionService, STORAGE_CONFIG, STORAGE_KEYS, StorageService, 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, LoggerConfig, TokenConfig, UserData, UserInfo };
352
+ export { AUTH0_CONFIG, AuthService, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, configureAuth0, getStorageItem, removeStorageItem, setStorageItem };
353
+ export type { UserData, UserInfo };