@opensourcekd/ng-common-libs 1.2.8 → 2.0.0

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,443 +0,0 @@
1
- import { ReplaySubject, Observable } from 'rxjs';
2
- import { EventType } from 'mitt';
3
-
4
- /**
5
- * EventBusService - Angular service for cross-application event communication
6
- * Uses mitt library for efficient event handling and RxJS ReplaySubject for observable stream
7
- *
8
- * This service is designed for MicroFrontend architectures where different apps need to communicate
9
- * The ReplaySubject keeps last 100 events in memory for late subscribers
10
- *
11
- * **IMPORTANT for Module Federation / MicroFrontends:**
12
- * This service uses a module-level singleton to ensure ONE instance across all MFEs and shell.
13
- * Before using `inject(EventBusService)` in components, you must provide it at application level:
14
- *
15
- * @example
16
- * ```typescript
17
- * // In app.config.ts (standalone) or app.module.ts (NgModule)
18
- * import { EventBusService, getEventBusService } from '@opensourcekd/ng-common-libs';
19
- *
20
- * export const appConfig: ApplicationConfig = {
21
- * providers: [
22
- * { provide: EventBusService, useFactory: getEventBusService }
23
- * ]
24
- * };
25
- * ```
26
- *
27
- * Then use in components:
28
- * ```typescript
29
- * import { Component, inject, OnInit } from '@angular/core';
30
- * import { EventBusService } from '@opensourcekd/ng-common-libs';
31
- *
32
- * @Component({
33
- * selector: 'app-example',
34
- * template: '...'
35
- * })
36
- * export class ExampleComponent implements OnInit {
37
- * private eventBus = inject(EventBusService);
38
- *
39
- * ngOnInit() {
40
- * // Subscribe to all events
41
- * this.eventBus.onePlusNEvents.subscribe(event => {
42
- * console.log('Event received:', event);
43
- * });
44
- * }
45
- *
46
- * sendCustomEvent() {
47
- * // Send a custom event
48
- * this.eventBus.sendEvent('user:action');
49
- *
50
- * // Or send structured event with data
51
- * this.eventBus.sendEvent(JSON.stringify({
52
- * type: 'user:login',
53
- * payload: { userId: '123' },
54
- * timestamp: new Date().toISOString()
55
- * }));
56
- * }
57
- * }
58
- * ```
59
- */
60
- declare class EventBusService {
61
- /**
62
- * ReplaySubject that buffers the last 100 events for late subscribers
63
- * Subscribe to this observable to receive all events
64
- */
65
- onePlusNEvents: ReplaySubject<EventType>;
66
- /**
67
- * mitt event emitter instance
68
- * Lightweight event emitter library
69
- */
70
- private emitter;
71
- constructor();
72
- /**
73
- * Send an event through the event bus
74
- * The event will be forwarded to all subscribers via the ReplaySubject
75
- *
76
- * @param s - Event string, can be a simple event name or JSON stringified structured data
77
- *
78
- * @example
79
- * ```typescript
80
- * // Simple event
81
- * eventBus.sendEvent('user:logout');
82
- *
83
- * // Structured event
84
- * eventBus.sendEvent(JSON.stringify({
85
- * type: 'auth:token_updated',
86
- * payload: { token: 'abc123' },
87
- * timestamp: new Date().toISOString()
88
- * }));
89
- * ```
90
- */
91
- sendEvent(s: string): void;
92
- }
93
- /**
94
- * Factory function to get the singleton EventBusService instance
95
- * Use this in your application providers to ensure singleton behavior across MFEs
96
- *
97
- * @example
98
- * ```typescript
99
- * // In app.config.ts or app.module.ts
100
- * import { EventBusService, getEventBusService } from '@opensourcekd/ng-common-libs';
101
- *
102
- * export const appConfig: ApplicationConfig = {
103
- * providers: [
104
- * { provide: EventBusService, useFactory: getEventBusService }
105
- * ]
106
- * };
107
- * ```
108
- *
109
- * @returns The singleton EventBusService instance
110
- */
111
- declare function getEventBusService(): EventBusService;
112
-
113
- /**
114
- * User information from ID token
115
- * Standard OIDC claims compatible with Auth0
116
- */
117
- interface UserInfo {
118
- sub: string;
119
- name?: string;
120
- email?: string;
121
- email_verified?: boolean;
122
- preferred_username?: string;
123
- given_name?: string;
124
- family_name?: string;
125
- nickname?: string;
126
- locale?: string;
127
- picture?: string;
128
- phone?: string;
129
- phone_verified?: boolean;
130
- updated_at?: string;
131
- role?: string;
132
- org?: string;
133
- organization?: string;
134
- [key: string]: any;
135
- }
136
- /**
137
- * Simplified user data extracted from token
138
- */
139
- interface UserData {
140
- id: string;
141
- name: string;
142
- email: string;
143
- role: string;
144
- org: string;
145
- }
146
- /**
147
- * Authentication service for Auth0 integration
148
- * Handles login, logout, token management, and user session
149
- * Uses sessionStorage for sensitive data and emits authentication events for MicroApps
150
- *
151
- * Configuration is centralized in config/auth.config.ts for easy management
152
- *
153
- * **IMPORTANT for Module Federation / MicroFrontends:**
154
- * This service uses a module-level singleton to ensure ONE instance across all MFEs and shell.
155
- * Before using `inject(AuthService)` in components, you must provide it at application level:
156
- *
157
- * @example
158
- * ```typescript
159
- * // In app.config.ts (standalone) or app.module.ts (NgModule)
160
- * import { AuthService, getAuthService, EventBusService, getEventBusService } from '@opensourcekd/ng-common-libs';
161
- *
162
- * export const appConfig: ApplicationConfig = {
163
- * providers: [
164
- * { provide: EventBusService, useFactory: getEventBusService },
165
- * { provide: AuthService, useFactory: getAuthService }
166
- * ]
167
- * };
168
- * ```
169
- *
170
- * NOTE: All navigation logic using setTimeout is commented out as per requirements.
171
- * To enable navigation after auth operations, uncomment the marked sections in consuming components.
172
- */
173
- declare class AuthService {
174
- private eventBus;
175
- private readonly STANDARD_JWT_CLAIMS;
176
- private auth0Client;
177
- private initializationPromise;
178
- private userSubject;
179
- user$: Observable<UserInfo | null>;
180
- constructor(eventBus: EventBusService);
181
- /**
182
- * Initialize Auth0 client
183
- */
184
- private initializeAuth0;
185
- /**
186
- * Ensure Auth0 client is initialized before use
187
- */
188
- private ensureInitialized;
189
- /**
190
- * Login with Auth0
191
- * Redirects to Auth0 Universal Login
192
- * Preserves current URL parameters (like invitation tokens) through the auth flow
193
- *
194
- * @param user - Optional user identifier for logging
195
- * @param options - Optional login options including invitation and organization parameters
196
- */
197
- login(user?: string, options?: {
198
- invitation?: string;
199
- organization?: string;
200
- }): Promise<void>;
201
- /**
202
- * Handle OAuth2 callback after successful authorization
203
- * Processes the callback and retrieves user info
204
- *
205
- * NOTE: Navigation after successful/failed authentication should be handled in the calling component
206
- * using setTimeout. See commented examples in app.component.ts
207
- *
208
- * @returns Promise<{ success: boolean, appState?: any }> - Success status and preserved appState
209
- */
210
- handleCallback(): Promise<{
211
- success: boolean;
212
- appState?: any;
213
- }>;
214
- /**
215
- * Decode and log the access token to console
216
- * NOTE: This logs sensitive token information to console for debugging purposes.
217
- * In production environments, consider disabling this or filtering console logs.
218
- * @param token - The JWT access token
219
- */
220
- private decodeAndLogToken;
221
- /**
222
- * Log all user claims for debugging
223
- * @param user - User info from Auth0
224
- */
225
- private logUserClaims;
226
- /**
227
- * Log standard OIDC claims
228
- * @param user - User info from Auth0
229
- */
230
- private logStandardClaims;
231
- /**
232
- * Log claims with consistent formatting
233
- * @param header - Section header to display
234
- * @param claims - Array of claim keys to log
235
- * @param user - User info object
236
- */
237
- private logClaims;
238
- /**
239
- * Get custom namespaced claims from user info
240
- * @param user - User info object
241
- * @returns Array of custom claim keys
242
- */
243
- private getCustomClaims;
244
- /**
245
- * Get additional non-namespaced claims from user info
246
- * @param user - User info object
247
- * @returns Array of additional claim keys
248
- */
249
- private getAdditionalClaims;
250
- /**
251
- * Check if a claim key is namespaced
252
- * @param key - Claim key to check
253
- * @returns True if the key starts with http:// or https://
254
- */
255
- private isNamespacedClaim;
256
- /**
257
- * Logout user and clear authentication state
258
- * Redirects to Auth0 logout endpoint and clears local state
259
- */
260
- logout(): Promise<void>;
261
- /**
262
- * Get current access token from storage or Auth0 client
263
- * @returns string | null - Access token or null if not authenticated
264
- */
265
- getToken(): Promise<string | null>;
266
- /**
267
- * Get current access token synchronously from storage only
268
- * Use this for synchronous operations like interceptors
269
- * @returns string | null - Access token or null if not authenticated
270
- */
271
- getTokenSync(): string | null;
272
- /**
273
- * Set access token in storage and emit event for MicroApps
274
- * @param token - Access token to store
275
- */
276
- private setToken;
277
- /**
278
- * Check if user is authenticated
279
- * @returns boolean - True if user has valid token
280
- */
281
- isAuthenticated(): Promise<boolean>;
282
- /**
283
- * Check if user is authenticated synchronously
284
- * Only checks storage, doesn't verify with Auth0
285
- * @returns boolean - True if user has token in storage
286
- */
287
- isAuthenticatedSync(): boolean;
288
- /**
289
- * Get current user information
290
- * @returns UserInfo | null - Current user or null if not authenticated
291
- */
292
- getUser(): UserInfo | null;
293
- /**
294
- * Get simplified user data from token
295
- * Extracts user details, role, and organization from ID token claims
296
- * Checks both top-level claims and namespaced custom claims
297
- * @returns UserData | null - Simplified user data or null if not authenticated
298
- */
299
- getUserData(): UserData | null;
300
- /**
301
- * Extract claim value from user info, checking both direct properties and namespaced custom claims
302
- * @param userInfo - User info object
303
- * @param claimNames - Single claim name or array of claim names to search for
304
- * @param defaultValue - Default value if claim is not found
305
- * @returns Extracted claim value or default value
306
- */
307
- private extractClaimValue;
308
- /**
309
- * Get user information from storage
310
- * @returns UserInfo | null - Stored user info or null
311
- */
312
- private getUserInfoFromStorage;
313
- /**
314
- * Set user information in storage, update observable and emit event for MicroApps
315
- * Logs all Auth0 claims for debugging
316
- * @param userInfo - User information to store
317
- */
318
- private setUserInfo;
319
- /**
320
- * Emit authentication event for MicroApps to consume
321
- * Events are emitted via EventBus for cross-MFE communication
322
- * @param eventType - Type of authentication event
323
- * @param payload - Event payload
324
- */
325
- private emitAuthEvent;
326
- }
327
- /**
328
- * Factory function to get the singleton AuthService instance
329
- * Use this in your application providers to ensure singleton behavior across MFEs
330
- *
331
- * Lazy initialization ensures Auth0 can be configured before service creation
332
- *
333
- * @example
334
- * ```typescript
335
- * // In app.config.ts or app.module.ts
336
- * import { AuthService, getAuthService, EventBusService, getEventBusService } from '@opensourcekd/ng-common-libs';
337
- *
338
- * export const appConfig: ApplicationConfig = {
339
- * providers: [
340
- * { provide: EventBusService, useFactory: getEventBusService },
341
- * { provide: AuthService, useFactory: getAuthService }
342
- * ]
343
- * };
344
- * ```
345
- *
346
- * @returns The singleton AuthService instance
347
- */
348
- declare function getAuthService(): AuthService;
349
-
350
- /**
351
- * Auth0 Configuration
352
- * Centralized configuration for Auth0 integration
353
- *
354
- * Environment variables are typically set in consuming applications
355
- * Default values are provided for development/testing
356
- */
357
- /**
358
- * Auth0 client configuration
359
- * Override these values in your consuming application by setting them before importing AuthService
360
- *
361
- * Note: redirectUri defaults to window.location.origin (base URL without path).
362
- * Auth0 will redirect back to this URL after authentication.
363
- * You can override this to a specific callback URL (e.g., '/auth-callback') using configureAuth0().
364
- */
365
- declare const AUTH0_CONFIG: {
366
- domain: string;
367
- clientId: string;
368
- redirectUri: string;
369
- logoutUri: string;
370
- audience: string;
371
- scope: string;
372
- connection: string | undefined;
373
- };
374
- /**
375
- * Storage configuration
376
- * Controls where sensitive data is stored
377
- */
378
- declare const STORAGE_CONFIG: {
379
- TOKEN_STORAGE: "localStorage" | "sessionStorage";
380
- USER_INFO_STORAGE: "localStorage" | "sessionStorage";
381
- };
382
- /**
383
- * Storage keys for auth data
384
- */
385
- declare const STORAGE_KEYS: {
386
- ACCESS_TOKEN: string;
387
- USER_INFO: string;
388
- };
389
- /**
390
- * Helper functions for storage operations
391
- * These work with both localStorage and sessionStorage
392
- */
393
- /**
394
- * Get item from storage
395
- * @param key - Storage key
396
- * @param storageType - Type of storage to use
397
- * @returns Stored value or null
398
- */
399
- declare function getStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): string | null;
400
- /**
401
- * Set item in storage
402
- * @param key - Storage key
403
- * @param value - Value to store
404
- * @param storageType - Type of storage to use
405
- */
406
- declare function setStorageItem(key: string, value: string, storageType?: 'localStorage' | 'sessionStorage'): void;
407
- /**
408
- * Remove item from storage
409
- * @param key - Storage key
410
- * @param storageType - Type of storage to use
411
- */
412
- declare function removeStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): void;
413
- /**
414
- * Configure Auth0 settings (OPTIONAL)
415
- * Call this function in your consuming application to override default Auth0 configuration.
416
- * Only the values you provide will be overridden; all other defaults remain unchanged.
417
- *
418
- * Note: This function is optional. If not called, default values will be used.
419
- *
420
- * @param config - Partial Auth0 configuration object with values to override
421
- *
422
- * @example
423
- * ```typescript
424
- * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
425
- *
426
- * // Only override specific values - others keep their defaults
427
- * configureAuth0({
428
- * domain: 'your-domain.auth0.com',
429
- * clientId: 'your-client-id',
430
- * audience: 'https://your-api.com'
431
- * // redirectUri, logoutUri, scope, etc. will use defaults
432
- * });
433
- *
434
- * // Or override just redirectUri to use a specific callback page
435
- * configureAuth0({
436
- * redirectUri: window.location.origin + '/auth-callback'
437
- * });
438
- * ```
439
- */
440
- declare function configureAuth0(config: Partial<typeof AUTH0_CONFIG>): void;
441
-
442
- export { AUTH0_CONFIG, AuthService, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, configureAuth0, getAuthService, getEventBusService, getStorageItem, removeStorageItem, setStorageItem };
443
- export type { UserData, UserInfo };