@opensourcekd/ng-common-libs 2.0.2 → 2.0.3

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,5 +1,4 @@
1
- import { Observable, ReplaySubject } from 'rxjs';
2
- import { EventType } from 'mitt';
1
+ import { Observable } from 'rxjs';
3
2
 
4
3
  /**
5
4
  * Event payload interface
@@ -76,84 +75,65 @@ declare const APP_CONFIG: {
76
75
  };
77
76
 
78
77
  /**
79
- * EventBusService - Angular service for cross-application event communication
80
- * Uses mitt library for efficient event handling and RxJS ReplaySubject for observable stream
81
- *
82
- * This service is designed for MicroFrontend architectures where different apps need to communicate
83
- * The ReplaySubject keeps last 100 events in memory for late subscribers
84
- *
85
- * **IMPORTANT for Module Federation / MicroFrontends:**
86
- * This service uses Angular's dependency injection with providedIn: 'root' to ensure
87
- * singleton behavior across all MFEs and shell when shared via Module Federation webpack config.
88
- *
89
- * Simply inject in components using Angular DI:
90
- *
91
- * @example
92
- * ```typescript
93
- * import { Component, inject, OnInit } from '@angular/core';
94
- * import { EventBusService } from '@opensourcekd/ng-common-libs';
95
- *
96
- * @Component({
97
- * selector: 'app-example',
98
- * template: '...'
99
- * })
100
- * export class ExampleComponent implements OnInit {
101
- * private eventBus = inject(EventBusService);
102
- *
103
- * ngOnInit() {
104
- * // Subscribe to all events
105
- * this.eventBus.onePlusNEvents.subscribe(event => {
106
- * console.log('Event received:', event);
107
- * });
108
- * }
109
- *
110
- * sendCustomEvent() {
111
- * // Send a custom event
112
- * this.eventBus.sendEvent('user:action');
78
+ * Auth0 Configuration
79
+ * Centralized configuration for Auth0 integration
80
+ * Framework-agnostic - works with any JavaScript framework
81
+ */
82
+ /**
83
+ * Auth0 client configuration
84
+ * Override these values in your consuming application by setting them before importing AuthService
113
85
  *
114
- * // Or send structured event with data
115
- * this.eventBus.sendEvent(JSON.stringify({
116
- * type: 'user:login',
117
- * payload: { userId: '123' },
118
- * timestamp: new Date().toISOString()
119
- * }));
120
- * }
121
- * }
122
- * ```
86
+ * Note: redirectUri defaults to window.location.origin (base URL without path).
87
+ * Auth0 will redirect back to this URL after authentication.
123
88
  */
124
- declare class EventBusService {
125
- /**
126
- * ReplaySubject that buffers the last 100 events for late subscribers
127
- * Subscribe to this observable to receive all events
128
- */
129
- onePlusNEvents: ReplaySubject<EventType>;
130
- /**
131
- * mitt event emitter instance
132
- * Lightweight event emitter library
133
- */
134
- private emitter;
135
- constructor();
136
- /**
137
- * Send an event through the event bus
138
- * The event will be forwarded to all subscribers via the ReplaySubject
139
- *
140
- * @param s - Event string, can be a simple event name or JSON stringified structured data
141
- *
142
- * @example
143
- * ```typescript
144
- * // Simple event
145
- * eventBus.sendEvent('user:logout');
146
- *
147
- * // Structured event
148
- * eventBus.sendEvent(JSON.stringify({
149
- * type: 'auth:token_updated',
150
- * payload: { token: 'abc123' },
151
- * timestamp: new Date().toISOString()
152
- * }));
153
- * ```
154
- */
155
- sendEvent(s: string): void;
156
- }
89
+ declare const AUTH0_CONFIG: {
90
+ domain: string;
91
+ clientId: string;
92
+ redirectUri: string;
93
+ logoutUri: string;
94
+ audience: string;
95
+ scope: string;
96
+ connection: string | undefined;
97
+ };
98
+ /**
99
+ * Storage configuration
100
+ * Controls where sensitive data is stored
101
+ */
102
+ declare const STORAGE_CONFIG: {
103
+ TOKEN_STORAGE: "localStorage" | "sessionStorage";
104
+ USER_INFO_STORAGE: "localStorage" | "sessionStorage";
105
+ };
106
+ /**
107
+ * Storage keys for auth data
108
+ */
109
+ declare const STORAGE_KEYS: {
110
+ ACCESS_TOKEN: string;
111
+ USER_INFO: string;
112
+ };
113
+ /**
114
+ * Helper functions for storage operations
115
+ * These work with both localStorage and sessionStorage
116
+ */
117
+ /**
118
+ * Get item from storage
119
+ * @param key - Storage key
120
+ * @param storageType - Type of storage to use
121
+ * @returns Stored value or null
122
+ */
123
+ declare function getStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): string | null;
124
+ /**
125
+ * Set item in storage
126
+ * @param key - Storage key
127
+ * @param value - Value to store
128
+ * @param storageType - Type of storage to use
129
+ */
130
+ declare function setStorageItem(key: string, value: string, storageType?: 'localStorage' | 'sessionStorage'): void;
131
+ /**
132
+ * Remove item from storage
133
+ * @param key - Storage key
134
+ * @param storageType - Type of storage to use
135
+ */
136
+ declare function removeStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): void;
157
137
 
158
138
  /**
159
139
  * User information from ID token
@@ -215,60 +195,88 @@ interface CallbackResult {
215
195
  appState?: AppState;
216
196
  }
217
197
  /**
218
- * Authentication service for Auth0 integration
219
- * Handles login, logout, token management, and user session
220
- * Uses sessionStorage for sensitive data and emits authentication events for MicroApps
221
- *
222
- * Configuration is centralized in config/auth.config.ts for easy management
223
- *
224
- * **IMPORTANT for Module Federation / MicroFrontends:**
225
- * This service uses Angular's dependency injection with providedIn: 'root' to ensure
226
- * singleton behavior across all MFEs and shell when shared via Module Federation webpack config.
198
+ * Auth0 Configuration interface
199
+ */
200
+ interface Auth0Config {
201
+ domain: string;
202
+ clientId: string;
203
+ redirectUri: string;
204
+ logoutUri: string;
205
+ audience?: string;
206
+ scope: string;
207
+ connection?: string;
208
+ }
209
+ /**
210
+ * Storage configuration
211
+ */
212
+ interface StorageConfig {
213
+ TOKEN_STORAGE: 'localStorage' | 'sessionStorage';
214
+ USER_INFO_STORAGE: 'localStorage' | 'sessionStorage';
215
+ }
216
+ /**
217
+ * Storage keys
218
+ */
219
+ interface StorageKeys {
220
+ ACCESS_TOKEN: string;
221
+ USER_INFO: string;
222
+ }
223
+ /**
224
+ * Pure TypeScript Authentication Service for Auth0 integration
225
+ * Framework-agnostic - works with any JavaScript framework (Angular, React, Vue, etc.)
227
226
  *
228
- * Simply inject in components using Angular DI:
227
+ * Handles login, logout, token management, and user session
228
+ * Uses configurable storage (sessionStorage/localStorage) for sensitive data
229
+ * Emits authentication events via EventBus for cross-application communication
229
230
  *
230
231
  * @example
231
232
  * ```typescript
232
- * import { Component, inject } from '@angular/core';
233
- * import { AuthService } from '@opensourcekd/ng-common-libs';
233
+ * import { AuthService, EventBus } from '@opensourcekd/ng-common-libs';
234
234
  *
235
- * @Component({
236
- * selector: 'app-example',
237
- * template: '...'
238
- * })
239
- * export class ExampleComponent {
240
- * private authService = inject(AuthService);
241
- * }
242
- * ```
235
+ * // Create instances
236
+ * const eventBus = new EventBus();
237
+ * const authConfig = {
238
+ * domain: 'your-domain.auth0.com',
239
+ * clientId: 'your-client-id',
240
+ * redirectUri: window.location.origin,
241
+ * logoutUri: window.location.origin,
242
+ * scope: 'openid profile email'
243
+ * };
244
+ * const authService = new AuthService(authConfig, eventBus);
243
245
  *
244
- * NOTE: All navigation logic using setTimeout is commented out as per requirements.
245
- * To enable navigation after auth operations, uncomment the marked sections in consuming components.
246
+ * // Use the service
247
+ * await authService.login();
248
+ * const user = authService.getUser();
249
+ * const token = await authService.getToken();
250
+ * ```
246
251
  */
247
252
  declare class AuthService {
248
- private eventBus;
249
253
  private readonly STANDARD_JWT_CLAIMS;
250
254
  private auth0Client;
251
255
  private initializationPromise;
252
256
  private userSubject;
253
257
  user$: Observable<UserInfo | null>;
254
- constructor(eventBus: EventBusService);
258
+ private config;
259
+ private storageConfig;
260
+ private storageKeys;
261
+ private eventBus;
262
+ /**
263
+ * Create a new AuthService instance
264
+ * @param config - Auth0 configuration
265
+ * @param eventBus - EventBus instance for emitting auth events
266
+ * @param storageConfig - Storage configuration (optional, defaults to sessionStorage)
267
+ * @param storageKeys - Storage keys (optional, defaults to standard keys)
268
+ */
269
+ constructor(config: Auth0Config, eventBus: EventBus, storageConfig?: StorageConfig, storageKeys?: StorageKeys);
255
270
  /**
256
271
  * Initialize Auth0 client
257
272
  */
258
273
  private initializeAuth0;
259
274
  /**
260
275
  * Ensure Auth0 client is initialized before use
261
- * Lazy initialization pattern - client is created on first use
262
- * Handles concurrent calls safely by checking promise first
263
276
  */
264
277
  private ensureInitialized;
265
278
  /**
266
279
  * Login with Auth0
267
- * Redirects to Auth0 Universal Login
268
- * Preserves current URL parameters (like invitation tokens) through the auth flow
269
- *
270
- * @param user - Optional user identifier for logging
271
- * @param options - Optional login options including invitation and organization parameters
272
280
  */
273
281
  login(user?: string, options?: {
274
282
  invitation?: string;
@@ -276,228 +284,63 @@ declare class AuthService {
276
284
  }): Promise<void>;
277
285
  /**
278
286
  * Handle OAuth2 callback after successful authorization
279
- * Processes the callback and retrieves user info
280
- *
281
- * NOTE: Navigation after successful/failed authentication should be handled in the calling component
282
- * using setTimeout. See commented examples in app.component.ts
283
- *
284
- * @returns Promise<CallbackResult> - Success status and preserved appState
285
287
  */
286
288
  handleCallback(): Promise<CallbackResult>;
287
289
  /**
288
290
  * Log all user claims for debugging
289
- * @param user - User info from Auth0
290
291
  */
291
292
  private logUserClaims;
292
- /**
293
- * Log standard OIDC claims
294
- * @param user - User info from Auth0
295
- */
296
293
  private logStandardClaims;
297
- /**
298
- * Log claims with consistent formatting
299
- * @param header - Section header to display
300
- * @param claims - Array of claim keys to log
301
- * @param user - User info object
302
- */
303
294
  private logClaims;
304
- /**
305
- * Get custom namespaced claims from user info
306
- * @param user - User info object
307
- * @returns Array of custom claim keys
308
- */
309
295
  private getCustomClaims;
310
- /**
311
- * Get additional non-namespaced claims from user info
312
- * @param user - User info object
313
- * @returns Array of additional claim keys
314
- */
315
296
  private getAdditionalClaims;
316
- /**
317
- * Check if a claim key is namespaced
318
- * @param key - Claim key to check
319
- * @returns True if the key starts with http:// or https://
320
- */
321
297
  private isNamespacedClaim;
322
298
  /**
323
299
  * Logout user and clear authentication state
324
- * Redirects to Auth0 logout endpoint and clears local state
325
300
  */
326
301
  logout(): Promise<void>;
327
302
  /**
328
- * Get current access token from storage or Auth0 client
329
- * @returns string | null - Access token or null if not authenticated
303
+ * Get current access token
330
304
  */
331
305
  getToken(): Promise<string | null>;
332
306
  /**
333
307
  * Get current access token synchronously from storage only
334
- * Use this for synchronous operations like interceptors
335
- * @returns string | null - Access token or null if not authenticated
336
308
  */
337
309
  getTokenSync(): string | null;
338
310
  /**
339
- * Set access token in storage and emit event for MicroApps
340
- * @param token - Access token to store
311
+ * Set access token in storage and emit event
341
312
  */
342
313
  private setToken;
343
314
  /**
344
315
  * Check if user is authenticated
345
- * @returns boolean - True if user has valid token
346
316
  */
347
317
  isAuthenticated(): Promise<boolean>;
348
318
  /**
349
319
  * Check if user is authenticated synchronously
350
- * Only checks storage, doesn't verify with Auth0
351
- * @returns boolean - True if user has token in storage
352
320
  */
353
321
  isAuthenticatedSync(): boolean;
354
322
  /**
355
323
  * Get current user information
356
- * @returns UserInfo | null - Current user or null if not authenticated
357
324
  */
358
325
  getUser(): UserInfo | null;
359
326
  /**
360
327
  * Get simplified user data from token
361
- * Extracts user details, role, and organization from ID token claims
362
- * Checks both top-level claims and namespaced custom claims
363
- * @returns UserData | null - Simplified user data or null if not authenticated
364
328
  */
365
329
  getUserData(): UserData | null;
366
- /**
367
- * Extract claim value from user info, checking both direct properties and namespaced custom claims
368
- * @param userInfo - User info object
369
- * @param claimNames - Single claim name or array of claim names to search for
370
- * @param defaultValue - Default value if claim is not found
371
- * @returns Extracted claim value or default value
372
- */
373
330
  private extractClaimValue;
374
331
  /**
375
332
  * Get user information from storage
376
- * @returns UserInfo | null - Stored user info or null
377
333
  */
378
334
  private getUserInfoFromStorage;
379
335
  /**
380
- * Set user information in storage, update observable and emit event for MicroApps
381
- * Logs all Auth0 claims for debugging
382
- * @param userInfo - User information to store
336
+ * Set user information in storage and update observable
383
337
  */
384
338
  private setUserInfo;
385
339
  /**
386
- * Emit authentication event for MicroApps to consume
387
- * Events are emitted via EventBus for cross-MFE communication
388
- * @param eventType - Type of authentication event
389
- * @param payload - Event payload
340
+ * Emit authentication event for cross-application communication
390
341
  */
391
342
  private emitAuthEvent;
392
343
  }
393
344
 
394
- /**
395
- * Auth0 Configuration
396
- * Centralized configuration for Auth0 integration
397
- *
398
- * Environment variables are typically set in consuming applications
399
- * Default values are provided for development/testing
400
- */
401
- /**
402
- * Auth0 client configuration
403
- * Override these values in your consuming application by setting them before importing AuthService
404
- *
405
- * Note: redirectUri defaults to window.location.origin (base URL without path).
406
- * Auth0 will redirect back to this URL after authentication.
407
- * You can override this to a specific callback URL (e.g., '/auth-callback') using configureAuth0().
408
- */
409
- declare const AUTH0_CONFIG: {
410
- domain: string;
411
- clientId: string;
412
- redirectUri: string;
413
- logoutUri: string;
414
- audience: string;
415
- scope: string;
416
- connection: string | undefined;
417
- };
418
- /**
419
- * Storage configuration
420
- * Controls where sensitive data is stored
421
- */
422
- declare const STORAGE_CONFIG: {
423
- TOKEN_STORAGE: "localStorage" | "sessionStorage";
424
- USER_INFO_STORAGE: "localStorage" | "sessionStorage";
425
- };
426
- /**
427
- * Storage keys for auth data
428
- */
429
- declare const STORAGE_KEYS: {
430
- ACCESS_TOKEN: string;
431
- USER_INFO: string;
432
- };
433
- /**
434
- * Helper functions for storage operations
435
- * These work with both localStorage and sessionStorage
436
- */
437
- /**
438
- * Get item from storage
439
- * @param key - Storage key
440
- * @param storageType - Type of storage to use
441
- * @returns Stored value or null
442
- */
443
- declare function getStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): string | null;
444
- /**
445
- * Set item in storage
446
- * @param key - Storage key
447
- * @param value - Value to store
448
- * @param storageType - Type of storage to use
449
- */
450
- declare function setStorageItem(key: string, value: string, storageType?: 'localStorage' | 'sessionStorage'): void;
451
- /**
452
- * Remove item from storage
453
- * @param key - Storage key
454
- * @param storageType - Type of storage to use
455
- */
456
- declare function removeStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): void;
457
- /**
458
- * Configure Auth0 settings (OPTIONAL)
459
- * Call this function in your consuming application to override default Auth0 configuration.
460
- * Only the values you provide will be overridden; all other defaults remain unchanged.
461
- *
462
- * Note: This function is optional. If not called, default values will be used.
463
- *
464
- * @param config - Partial Auth0 configuration object with values to override
465
- *
466
- * @example
467
- * ```typescript
468
- * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
469
- *
470
- * // Only override specific values - others keep their defaults
471
- * configureAuth0({
472
- * domain: 'your-domain.auth0.com',
473
- * clientId: 'your-client-id',
474
- * audience: 'https://your-api.com'
475
- * // redirectUri, logoutUri, scope, etc. will use defaults
476
- * });
477
- *
478
- * // Or override just redirectUri to use a specific callback page
479
- * configureAuth0({
480
- * redirectUri: window.location.origin + '/auth-callback'
481
- * });
482
- * ```
483
- */
484
- /**
485
- * Get the API URL
486
- * Returns the API URL that was configured during library build from GitHub repository variables.
487
- * No configuration needed - the value is baked into the library during CI/CD build process.
488
- *
489
- * @returns string - The API URL from APP_CONFIG (set during build time)
490
- *
491
- * @example
492
- * ```typescript
493
- * import { getApiUrl } from '@opensourcekd/ng-common-libs';
494
- *
495
- * // Use in HTTP interceptor or service
496
- * const apiUrl = getApiUrl();
497
- * const fullUrl = `${apiUrl}/users`;
498
- * ```
499
- */
500
- declare function getApiUrl(): string;
501
-
502
- export { APP_CONFIG, AUTH0_CONFIG, AuthService, EventBus, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, getApiUrl, getStorageItem, removeStorageItem, setStorageItem };
503
- export type { AppState, AuthorizationParams, CallbackResult, EventPayload, UserData, UserInfo };
345
+ export { APP_CONFIG, AUTH0_CONFIG, AuthService, EventBus, STORAGE_CONFIG, STORAGE_KEYS, getStorageItem, removeStorageItem, setStorageItem };
346
+ export type { AppState, Auth0Config, AuthorizationParams, CallbackResult, EventPayload, StorageConfig, StorageKeys, UserData, UserInfo };