@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/README.md CHANGED
@@ -1,24 +1,19 @@
1
1
  # ng-common-libs
2
2
 
3
- Angular 18 shareable utility library with framework-agnostic core and Angular wrappers for event handling, authorization, storage management, logging, and HTTP operations.
3
+ Angular 18 library with Auth0 authentication service and MicroFrontend event bus.
4
4
 
5
5
  ## 🎯 Dual-Layer Architecture
6
6
 
7
7
  This library features a **dual-layer architecture**:
8
8
 
9
- - **Core Layer** (`@opensourcekd/ng-common-libs/core`): Framework-agnostic utilities using only RxJS and browser APIs. Use these in React, Vue, Svelte, or vanilla JavaScript projects.
10
- - **Angular Layer** (`@opensourcekd/ng-common-libs` or `/angular`): Angular-specific wrappers with dependency injection, plus guards and interceptors that require Angular.
9
+ - **Core Layer** (`@opensourcekd/ng-common-libs/core`): Framework-agnostic event bus using only RxJS. Use in React, Vue, Svelte, or vanilla JavaScript projects.
10
+ - **Angular Layer** (`@opensourcekd/ng-common-libs` or `/angular`): Angular-specific services with dependency injection.
11
11
 
12
12
  ## 🚀 Features
13
13
 
14
- - **Event Bus**: Centralized event communication (framework-agnostic)
14
+ - **APP_CONFIG**: Framework-agnostic configuration utility for all environment variables (Auth0, API URLs)
15
15
  - **EventBusService**: MicroFrontend-ready event bus with replay buffer for cross-app communication
16
16
  - **Auth0 Integration**: Complete Auth0 authentication service with token management
17
- - **Token Manager**: JWT token management and validation (framework-agnostic)
18
- - **Storage Manager**: Type-safe localStorage/sessionStorage wrapper (framework-agnostic)
19
- - **Logger**: Configurable logging with multiple levels (framework-agnostic)
20
- - **Authorization**: Angular guards, interceptors, and permission handling
21
- - **HTTP Utilities**: Error handling, caching, and retry logic for Angular HTTP requests
22
17
 
23
18
  ## 📦 Installation
24
19
 
@@ -32,68 +27,25 @@ npm install @opensourcekd/ng-common-libs
32
27
 
33
28
  ## 🔧 Usage
34
29
 
35
- ### For Angular Projects
30
+ ### Configuration (Framework-Agnostic)
36
31
 
37
- Use the Angular-specific imports that provide dependency injection:
32
+ The library provides a framework-agnostic configuration utility with **statically configured values** from GitHub repository variables:
38
33
 
39
34
  ```typescript
40
- import { Component, OnInit, inject } from '@angular/core';
41
- import { NgEventEmitter } from '@opensourcekd/ng-common-libs';
42
-
43
- @Component({
44
- selector: 'app-example',
45
- template: `...`
46
- })
47
- export class ExampleComponent implements OnInit {
48
- private eventEmitter = inject(NgEventEmitter);
35
+ // Import from /core for framework-agnostic usage
36
+ import { APP_CONFIG } from '@opensourcekd/ng-common-libs/core';
49
37
 
50
- ngOnInit() {
51
- // Subscribe to events
52
- this.eventEmitter.on('user:login').subscribe(data => {
53
- console.log('User logged in:', data);
54
- });
55
- }
56
-
57
- login() {
58
- // Emit events
59
- this.eventEmitter.emit('user:login', {
60
- userId: '123',
61
- username: 'john'
62
- });
63
- }
64
- }
38
+ // Access pre-configured values anywhere in your app
39
+ console.log(APP_CONFIG.apiUrl); // Configured during build from GitHub vars
40
+ console.log(APP_CONFIG.auth0Domain); // Configured during build from GitHub vars
41
+ console.log(APP_CONFIG.auth0ClientId); // Configured during build from GitHub vars
65
42
  ```
66
43
 
67
- ### Authorization
68
-
69
- #### Token Service
70
-
71
- Manage authentication tokens with ease:
72
-
73
- ```typescript
74
- import { inject } from '@angular/core';
75
- import { TokenService } from '@opensourcekd/ng-common-libs';
76
-
77
- export class AuthService {
78
- private tokenService = inject(TokenService);
79
-
80
- login(token: string) {
81
- this.tokenService.setToken(token);
82
- }
83
-
84
- logout() {
85
- this.tokenService.clearTokens();
86
- }
87
-
88
- isAuthenticated(): boolean {
89
- return this.tokenService.isAuthenticated();
90
- }
91
-
92
- getUserData() {
93
- return this.tokenService.getUserFromToken();
94
- }
95
- }
96
- ```
44
+ **Key Features:**
45
+ - Values are **statically baked** into the library during build time from GitHub repository variables
46
+ - No runtime configuration needed - values are available immediately
47
+ - Can be used across any framework: Angular, React, Vue, Svelte, vanilla JS
48
+ - Perfect for MicroFrontends (MFEs) and shell applications
97
49
 
98
50
  ### Auth0 Authentication
99
51
 
@@ -102,12 +54,13 @@ Complete Auth0 integration with automatic token management and event emission:
102
54
  ```typescript
103
55
  import { Component, inject } from '@angular/core';
104
56
  import { AuthService, configureAuth0 } from '@opensourcekd/ng-common-libs';
57
+ import { APP_CONFIG } from '@opensourcekd/ng-common-libs/core';
105
58
 
106
- // Configure Auth0 in your app.config.ts
59
+ // Use pre-configured values from APP_CONFIG
107
60
  configureAuth0({
108
- domain: 'your-domain.auth0.com',
109
- clientId: 'your-client-id',
110
- audience: 'https://your-api.com',
61
+ domain: APP_CONFIG.auth0Domain,
62
+ clientId: APP_CONFIG.auth0ClientId,
63
+ audience: APP_CONFIG.apiUrl,
111
64
  });
112
65
 
113
66
  @Component({
@@ -169,198 +122,13 @@ export class EventExampleComponent implements OnInit {
169
122
 
170
123
  See the [EventBus Service Usage Guide](./docs/EVENT_BUS_USAGE.md) for advanced patterns and MicroFrontend examples.
171
124
 
172
- #### Auth Guard
173
-
174
- Protect routes with authentication guards:
175
-
176
- ```typescript
177
- import { Routes } from '@angular/router';
178
- import { authGuard, createRoleGuard } from '@opensourcekd/ng-common-libs';
179
-
180
- export const routes: Routes = [
181
- {
182
- path: 'dashboard',
183
- component: DashboardComponent,
184
- canActivate: [authGuard]
185
- },
186
- {
187
- path: 'admin',
188
- component: AdminComponent,
189
- canActivate: [createRoleGuard(['admin'], { redirectUrl: '/unauthorized' })]
190
- }
191
- ];
192
- ```
193
-
194
- #### Auth Interceptor
195
-
196
- Automatically add authentication tokens to HTTP requests:
197
-
198
- ```typescript
199
- import { ApplicationConfig } from '@angular/core';
200
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
201
- import { authInterceptor, configureAuthInterceptor } from '@opensourcekd/ng-common-libs';
202
-
203
- // Configure the interceptor (optional)
204
- configureAuthInterceptor({
205
- headerName: 'Authorization',
206
- tokenPrefix: 'Bearer',
207
- excludedUrls: ['/auth/login', '/auth/register']
208
- });
209
-
210
- export const appConfig: ApplicationConfig = {
211
- providers: [
212
- provideHttpClient(
213
- withInterceptors([authInterceptor])
214
- )
215
- ]
216
- };
217
- ```
218
-
219
- #### Permission Service
220
-
221
- Check user permissions and roles:
222
-
223
- ```typescript
224
- import { inject } from '@angular/core';
225
- import { PermissionService } from '@opensourcekd/ng-common-libs';
226
-
227
- export class MyComponent {
228
- private permissionService = inject(PermissionService);
229
-
230
- canEditPost(): boolean {
231
- return this.permissionService.hasPermission('posts:edit');
232
- }
233
-
234
- isAdmin(): boolean {
235
- return this.permissionService.hasRole('admin');
236
- }
237
- }
238
- ```
239
-
240
- ### Storage Service
241
-
242
- Type-safe storage operations with JSON serialization:
243
-
244
- ```typescript
245
- import { inject } from '@angular/core';
246
- import { StorageService } from '@opensourcekd/ng-common-libs';
247
-
248
- export class UserPreferencesService {
249
- private storage = inject(StorageService);
250
-
251
- savePreferences(prefs: UserPreferences) {
252
- this.storage.setLocal('user-prefs', prefs);
253
- }
254
-
255
- getPreferences(): UserPreferences | null {
256
- return this.storage.getLocal<UserPreferences>('user-prefs');
257
- }
258
-
259
- // With expiration (1 hour)
260
- saveTempData(data: any) {
261
- this.storage.setWithExpiration('temp-data', data, 3600000);
262
- }
263
-
264
- getTempData() {
265
- return this.storage.getWithExpiration('temp-data');
266
- }
267
- }
268
- ```
269
-
270
- ### Logger Service
271
-
272
- Centralized logging with configurable levels:
273
-
274
- ```typescript
275
- import { inject } from '@angular/core';
276
- import { LoggerService, LogLevel } from '@opensourcekd/ng-common-libs';
277
-
278
- export class MyService {
279
- private logger = inject(LoggerService);
280
-
281
- constructor() {
282
- // Configure logger
283
- this.logger.configure({
284
- level: LogLevel.DEBUG,
285
- enableTimestamp: true,
286
- prefix: 'MyApp'
287
- });
288
- }
289
-
290
- doSomething() {
291
- this.logger.debug('Debug message');
292
- this.logger.info('Info message');
293
- this.logger.warn('Warning message');
294
- this.logger.error('Error message', new Error('Something went wrong'));
295
-
296
- // Measure execution time
297
- this.logger.time('fetchData', async () => {
298
- return await this.fetchData();
299
- });
300
- }
301
- }
302
- ```
303
-
304
- ### HTTP Utilities
305
-
306
- #### Error Handling Interceptor
307
-
308
- Handle HTTP errors with automatic retry:
309
-
310
- ```typescript
311
- import { ApplicationConfig } from '@angular/core';
312
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
313
- import { errorHandlingInterceptor, configureErrorHandling } from '@opensourcekd/ng-common-libs';
314
-
315
- // Configure error handling
316
- configureErrorHandling({
317
- enableLogging: true,
318
- retryAttempts: 3,
319
- retryDelay: 1000,
320
- retryStatusCodes: [500, 502, 503, 504]
321
- });
322
-
323
- export const appConfig: ApplicationConfig = {
324
- providers: [
325
- provideHttpClient(
326
- withInterceptors([errorHandlingInterceptor])
327
- )
328
- ]
329
- };
330
- ```
331
-
332
- #### Caching Interceptor
333
-
334
- Cache HTTP responses:
335
-
336
- ```typescript
337
- import { ApplicationConfig } from '@angular/core';
338
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
339
- import { cachingInterceptor, configureCaching } from '@opensourcekd/ng-common-libs';
340
-
341
- // Configure caching
342
- configureCaching({
343
- enabled: true,
344
- maxAge: 300000, // 5 minutes
345
- cacheableUrls: ['/api/users', '/api/products']
346
- });
347
-
348
- export const appConfig: ApplicationConfig = {
349
- providers: [
350
- provideHttpClient(
351
- withInterceptors([cachingInterceptor])
352
- )
353
- ]
354
- };
355
- ```
356
-
357
125
  ### For Non-Angular Projects (React, Vue, Svelte, Vanilla JS)
358
126
 
359
- Use the framework-agnostic core utilities:
127
+ Use the framework-agnostic core event bus:
360
128
 
361
129
  ```typescript
362
130
  // Import from /core
363
- import { EventBus, TokenManager, StorageManager, Logger, LogLevel } from '@opensourcekd/ng-common-libs/core';
131
+ import { EventBus } from '@opensourcekd/ng-common-libs/core';
364
132
 
365
133
  // Event Bus
366
134
  const eventBus = new EventBus();
@@ -368,23 +136,6 @@ eventBus.emit('user:login', { userId: '123' });
368
136
  eventBus.on('user:login').subscribe(data => {
369
137
  console.log('User logged in:', data);
370
138
  });
371
-
372
- // Token Manager
373
- const tokenManager = new TokenManager();
374
- tokenManager.setToken('your-jwt-token');
375
- if (tokenManager.isAuthenticated()) {
376
- const user = tokenManager.getUserFromToken();
377
- }
378
-
379
- // Storage Manager
380
- const storage = new StorageManager();
381
- storage.setLocal('preferences', { theme: 'dark' });
382
- const prefs = storage.getLocal('preferences');
383
-
384
- // Logger
385
- const logger = new Logger();
386
- logger.configure({ level: LogLevel.DEBUG, prefix: 'MyApp' });
387
- logger.info('Application started');
388
139
  ```
389
140
 
390
141
  #### React Example
@@ -444,51 +195,48 @@ export default {
444
195
 
445
196
  ## 📚 Documentation
446
197
 
447
- - **[Usage Guide](./docs/USAGE.md)** - Complete usage examples for all utilities
448
- - **[API Reference](./docs/API.md)** - Detailed API documentation
449
198
  - **[Auth0 Service Usage](./docs/AUTH_SERVICE_USAGE.md)** - Complete Auth0 authentication integration guide
450
199
  - **[EventBus Service Usage](./docs/EVENT_BUS_USAGE.md)** - Cross-application event communication guide
451
200
  - **[Deployment Guide](./docs/DEPLOYMENT.md)** - Publishing, versioning, and consumption
452
201
  - **[Microapp Triggering Guide](./docs/MICROAPP_TRIGGERING.md)** - Automatic build triggering for consuming microapps
453
202
  - **[Module Federation Guide](./docs/MODULE_FEDERATION.md)** - Runtime sharing with Module Federation
454
- - **[Architecture Decisions](./ARCHITECTURE_DECISIONS.md)** - Detailed architecture and design decisions
455
203
 
456
204
  ## 📝 API Documentation
457
205
 
458
- ### NgEventEmitter
206
+ ### Core Configuration (Framework-Agnostic)
459
207
 
460
- - `emit<T>(eventType: string, data?: T): void` - Emit an event
461
- - `on<T>(eventType: string): Observable<T>` - Subscribe to an event
462
- - `onMultiple(eventTypes: string[]): Observable<EventPayload>` - Subscribe to multiple events
463
- - `onAll(): Observable<EventPayload>` - Subscribe to all events
208
+ - `APP_CONFIG` - Read-only application configuration object with values statically configured during build time:
209
+ - `auth0Domain: string` - Auth0 tenant domain (from GitHub var `AUTH0_DOMAIN`)
210
+ - `auth0ClientId: string` - Auth0 client ID (from GitHub var `AUTH0_CLIENT_ID`)
211
+ - `apiUrl: string` - API base URL (from GitHub var `API_URL`)
212
+
213
+ ### Angular Configuration
464
214
 
465
- ### TokenService
215
+ - `configureAuth0(config: Partial<AUTH0_CONFIG>): void` - Configure Auth0 settings (domain, clientId, etc.)
216
+ - `AUTH0_CONFIG` - Auth0 configuration object (domain, clientId, redirectUri, etc.)
466
217
 
467
- - `setToken(token: string): void` - Store authentication token
468
- - `getToken(): string | null` - Retrieve authentication token
469
- - `removeToken(): void` - Remove authentication token
470
- - `clearTokens(): void` - Clear all tokens
471
- - `isAuthenticated(): boolean` - Check if user is authenticated
472
- - `isTokenExpired(token?: string): boolean` - Check if token is expired
473
- - `getUserFromToken(token?: string): any` - Extract user data from token
218
+ ### AuthService
474
219
 
475
- ### StorageService
220
+ - `login(options?: RedirectLoginOptions): Promise<void>` - Initiate Auth0 login
221
+ - `logout(options?: LogoutOptions): Promise<void>` - Logout and clear session
222
+ - `handleCallback(): Promise<{ success: boolean, appState?: any }>` - Handle Auth0 callback
223
+ - `getToken(): Promise<string | null>` - Get access token asynchronously
224
+ - `getTokenSync(): string | null` - Get cached access token synchronously
225
+ - `getUser(): Signal<UserInfo | null>` - Get user information as signal
226
+ - `isAuthenticated(): Signal<boolean>` - Check authentication status
227
+ - `isLoading(): Signal<boolean>` - Check if authentication is loading
476
228
 
477
- - `setLocal<T>(key: string, value: T): boolean` - Set item in localStorage
478
- - `getLocal<T>(key: string, defaultValue?: T): T | null` - Get item from localStorage
479
- - `removeLocal(key: string): void` - Remove item from localStorage
480
- - `setSession<T>(key: string, value: T): boolean` - Set item in sessionStorage
481
- - `getSession<T>(key: string, defaultValue?: T): T | null` - Get item from sessionStorage
482
- - `setWithExpiration<T>(key, value, expirationMs, useSession?): boolean` - Set item with expiration
483
- - `getWithExpiration<T>(key, useSession?): T | null` - Get item with expiration check
229
+ ### EventBusService
484
230
 
485
- ### LoggerService
231
+ - `sendEvent(event: string): void` - Send event to all subscribers
232
+ - `onePlusNEvents: Observable<string>` - Subscribe to all events with replay buffer
486
233
 
487
- - `debug(message: string, ...args: any[]): void` - Log debug message
488
- - `info(message: string, ...args: any[]): void` - Log info message
489
- - `warn(message: string, ...args: any[]): void` - Log warning message
490
- - `error(message: string, error?: any, ...args: any[]): void` - Log error message
491
- - `time<T>(label: string, fn: () => Promise<T> | T): Promise<T>` - Measure execution time
234
+ ### EventBus (Core)
235
+
236
+ - `emit<T>(eventType: string, data?: T): void` - Emit an event
237
+ - `on<T>(eventType: string): Observable<T>` - Subscribe to an event
238
+ - `onMultiple(eventTypes: string[]): Observable<EventPayload>` - Subscribe to multiple events
239
+ - `onAll(): Observable<EventPayload>` - Subscribe to all events
492
240
 
493
241
  ## 🛠️ Development
494
242
 
@@ -518,4 +266,3 @@ Contributions, issues, and feature requests are welcome!
518
266
  ## ⭐ Show your support
519
267
 
520
268
  Give a ⭐️ if this project helped you!
521
-