@telperion/ng-pack 1.2.2 → 1.3.1

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
@@ -60,6 +60,77 @@ export class SettingsComponent {
60
60
 
61
61
  ---
62
62
 
63
+ ### SSE Client
64
+
65
+ **Import:** `@telperion/ng-pack/sse-client`
66
+
67
+ Angular service for Server-Sent Events (SSE) with RxJS Observables and HttpClient-inspired interceptors.
68
+
69
+ #### Key Features
70
+
71
+ - 🚀 Observable-based API integrated with RxJS ecosystem
72
+ - 🔗 HttpClient-inspired interceptor chain for request manipulation
73
+ - 🎯 Type-safe with full generic support
74
+ - ⚡ EventSource wrapper with automatic cleanup
75
+ - 🔄 Real-time streaming data updates
76
+ - 🎨 Feature-based configuration
77
+
78
+ #### Quick Start
79
+
80
+ ```typescript
81
+ import { ApplicationConfig } from '@angular/core';
82
+ import { provideSseClient, withSseInterceptors } from '@telperion/ng-pack/sse-client';
83
+
84
+ export const appConfig: ApplicationConfig = {
85
+ providers: [
86
+ provideSseClient(
87
+ withSseInterceptors(loggingInterceptor, authInterceptor)
88
+ ),
89
+ ]
90
+ };
91
+ ```
92
+
93
+ ```typescript
94
+ import { Component, inject } from '@angular/core';
95
+ import { SseClient } from '@telperion/ng-pack/sse-client';
96
+ import { AsyncPipe } from '@angular/common';
97
+
98
+ interface StockUpdate {
99
+ symbol: string;
100
+ price: number;
101
+ change: number;
102
+ }
103
+
104
+ @Component({
105
+ selector: 'app-stock-ticker',
106
+ template: `
107
+ <div>
108
+ <h2>Live Stock Prices</h2>
109
+ @if (stockUpdates$ | async; as update) {
110
+ <div class="stock-card">
111
+ <span>{{ update.symbol }}: \${{ update.price }}</span>
112
+ <span [class.positive]="update.change > 0">
113
+ {{ update.change > 0 ? '+' : '' }}{{ update.change }}%
114
+ </span>
115
+ </div>
116
+ }
117
+ </div>
118
+ `,
119
+ standalone: true,
120
+ imports: [AsyncPipe]
121
+ })
122
+ export class StockTickerComponent {
123
+ private sseClient = inject(SseClient);
124
+
125
+ // Start SSE connection and get Observable stream
126
+ stockUpdates$ = this.sseClient.start<StockUpdate>('/api/stocks/stream');
127
+ }
128
+ ```
129
+
130
+ [Full documentation →](https://github.com/telperiontech/telperion/tree/main/libs/ng-pack/sse-client)
131
+
132
+ ---
133
+
63
134
  ### Template Signal Forms
64
135
 
65
136
  **Import:** `@telperion/ng-pack/template-signal-forms`
@@ -0,0 +1,152 @@
1
+ import * as i0 from '@angular/core';
2
+ import { InjectionToken, inject, Injectable } from '@angular/core';
3
+ import { Observable } from 'rxjs';
4
+
5
+ /**
6
+ * Enum identifying different types of SSE features.
7
+ */
8
+ var SseFeatureKind;
9
+ (function (SseFeatureKind) {
10
+ SseFeatureKind[SseFeatureKind["InterceptorFunction"] = 0] = "InterceptorFunction";
11
+ })(SseFeatureKind || (SseFeatureKind = {}));
12
+
13
+ /**
14
+ * Configures functional interceptors for the SSE client.
15
+ * Interceptors are executed in the order they are provided.
16
+ *
17
+ * @param interceptors - One or more functional interceptor functions
18
+ * @returns Array of SSE features to be used with provideSseClient()
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * const loggingInterceptor: SseInterceptorFn<any> = (req, next) => {
23
+ * console.log('Connecting to:', req.url);
24
+ * return next(req);
25
+ * };
26
+ *
27
+ * provideSseClient(
28
+ * withSseInterceptors(loggingInterceptor)
29
+ * )
30
+ * ```
31
+ */
32
+ function withSseInterceptors(...interceptors) {
33
+ return interceptors.map(interceptor => ({
34
+ kind: SseFeatureKind.InterceptorFunction,
35
+ interceptor,
36
+ }));
37
+ }
38
+
39
+ /**
40
+ * Injection token for providing SSE interceptors.
41
+ * Use with multi: true to provide multiple interceptors.
42
+ */
43
+ const SSE_INTERCEPTORS = new InjectionToken('Telperion/SSE_INTERCEPTORS');
44
+
45
+ /**
46
+ * Angular service for managing Server-Sent Events (SSE) connections.
47
+ * Wraps the EventSource API with RxJS Observables and an HttpClient-inspired interceptor chain.
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * class MyComponent {
52
+ * private sseClient = inject(SseClient);
53
+ *
54
+ * messages$ = this.sseClient.start<string>('/api/events');
55
+ * }
56
+ * ```
57
+ */
58
+ class SseClient {
59
+ #interceptors = inject(SSE_INTERCEPTORS, { optional: true }) ?? [];
60
+ constructor() {
61
+ if (!(this.#interceptors instanceof Array)) {
62
+ throw new Error('SSE_INTERCEPTORS must be provided as an array. Please ensure you are using multi: true when providing interceptors.');
63
+ }
64
+ }
65
+ /**
66
+ * Starts a new Server-Sent Events connection and returns an Observable stream.
67
+ *
68
+ * @param url - The URL endpoint for the SSE connection
69
+ * @param init - Optional EventSource initialization configuration
70
+ * @returns Observable stream of server-sent events
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * this.sseClient.start<MessageData>('/api/notifications', { withCredentials: true })
75
+ * .subscribe(data => console.log('Received:', data));
76
+ * ```
77
+ */
78
+ start(url, init = {}) {
79
+ return this.#interceptors.reduceRight((next, interceptor) => (req) => interceptor.sseIntercept(req, next), (req) => this.#createEventSource(req))({ url, init });
80
+ }
81
+ #createEventSource(request) {
82
+ return new Observable((subscriber) => {
83
+ const eventSource = new EventSource(request.url, request.init);
84
+ function handleMessage(event) {
85
+ subscriber.next(event.data);
86
+ }
87
+ function handleError(err) {
88
+ subscriber.error(err);
89
+ eventSource.close();
90
+ }
91
+ eventSource.addEventListener('message', handleMessage);
92
+ eventSource.addEventListener('error', handleError);
93
+ return () => {
94
+ eventSource.removeEventListener('message', handleMessage);
95
+ eventSource.removeEventListener('error', handleError);
96
+ eventSource.close();
97
+ };
98
+ });
99
+ }
100
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.1.5", ngImport: i0, type: SseClient, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
101
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.1.5", ngImport: i0, type: SseClient });
102
+ }
103
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.1.5", ngImport: i0, type: SseClient, decorators: [{
104
+ type: Injectable
105
+ }], ctorParameters: () => [] });
106
+
107
+ /**
108
+ * Provides the SseClient service with optional features.
109
+ * Configure SSE client with interceptors and other features using a functional API.
110
+ *
111
+ * @param features - Optional feature configurations (e.g., withSseInterceptors())
112
+ * @returns Array of Angular providers
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * import { provideSseClient, withSseInterceptors } from '@telperion/ng-pack/sse-client';
117
+ *
118
+ * export const appConfig: ApplicationConfig = {
119
+ * providers: [
120
+ * provideSseClient(
121
+ * withSseInterceptors(loggingInterceptor, authInterceptor)
122
+ * )
123
+ * ]
124
+ * };
125
+ * ```
126
+ */
127
+ function provideSseClient(...features) {
128
+ const interceptorFns = features
129
+ .flat()
130
+ .filter(feature => feature.kind === SseFeatureKind.InterceptorFunction)
131
+ .map(feature => ({
132
+ provide: SSE_INTERCEPTORS,
133
+ useValue: {
134
+ sseIntercept: feature.interceptor,
135
+ },
136
+ multi: true,
137
+ }));
138
+ return [
139
+ {
140
+ provide: SseClient,
141
+ useClass: SseClient
142
+ },
143
+ ...interceptorFns
144
+ ];
145
+ }
146
+
147
+ /**
148
+ * Generated bundle index. Do not edit.
149
+ */
150
+
151
+ export { SSE_INTERCEPTORS, SseClient, SseFeatureKind, provideSseClient, withSseInterceptors };
152
+ //# sourceMappingURL=telperion-ng-pack-sse-client.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telperion-ng-pack-sse-client.mjs","sources":["../../sse-client/src/features/feature.ts","../../sse-client/src/features/with-interceptors.ts","../../sse-client/src/interceptor.ts","../../sse-client/src/client.ts","../../sse-client/src/provider.ts","../../sse-client/src/telperion-ng-pack-sse-client.ts"],"sourcesContent":["/**\r\n * Enum identifying different types of SSE features.\r\n */\r\nexport enum SseFeatureKind {\r\n InterceptorFunction\r\n}\r\n\r\n/**\r\n * Base interface for SSE feature configurations.\r\n */\r\nexport interface SseFeature {\r\n kind: SseFeatureKind;\r\n}\r\n","import { SseInterceptorFn } from \"../interceptor\";\r\nimport { SseFeature, SseFeatureKind } from \"./feature\";\r\n\r\n/**\r\n * Feature interface for functional interceptors.\r\n * @internal\r\n */\r\nexport interface SseInterceptorFunctionFeature extends SseFeature {\r\n kind: SseFeatureKind.InterceptorFunction;\r\n interceptor: SseInterceptorFn<unknown>;\r\n}\r\n\r\n/**\r\n * Configures functional interceptors for the SSE client.\r\n * Interceptors are executed in the order they are provided.\r\n *\r\n * @param interceptors - One or more functional interceptor functions\r\n * @returns Array of SSE features to be used with provideSseClient()\r\n *\r\n * @example\r\n * ```typescript\r\n * const loggingInterceptor: SseInterceptorFn<any> = (req, next) => {\r\n * console.log('Connecting to:', req.url);\r\n * return next(req);\r\n * };\r\n *\r\n * provideSseClient(\r\n * withSseInterceptors(loggingInterceptor)\r\n * )\r\n * ```\r\n */\r\nexport function withSseInterceptors<T = unknown>(...interceptors: SseInterceptorFn<T>[]): SseFeature[] {\r\n return interceptors.map(interceptor => ({\r\n kind: SseFeatureKind.InterceptorFunction,\r\n interceptor,\r\n }));\r\n}\r\n","import { InjectionToken } from \"@angular/core\";\r\nimport type { Observable } from \"rxjs\";\r\n\r\n/**\r\n * Represents an SSE request with URL and initialization options.\r\n */\r\nexport interface SseRequest {\r\n url: string;\r\n init: EventSourceInit;\r\n}\r\n\r\n/**\r\n * Function type for passing the request to the next handler in the interceptor chain.\r\n */\r\nexport type SseNextFn<T> = (request: SseRequest) => Observable<T>;\r\n\r\n/**\r\n * Functional interceptor type for intercepting SSE requests.\r\n * Interceptors can modify requests, handle errors, add logging, etc.\r\n *\r\n * @example\r\n * ```typescript\r\n * const loggingInterceptor: SseInterceptorFn<any> = (req, next) => {\r\n * console.log('SSE Request:', req.url);\r\n * return next(req);\r\n * };\r\n * ```\r\n */\r\nexport type SseInterceptorFn<T> = (\r\n request: SseRequest,\r\n next: SseNextFn<T>\r\n) => Observable<T>;\r\n\r\n/**\r\n * Class-based interceptor interface for SSE requests.\r\n * Implements the same pattern as Angular's HttpInterceptor.\r\n */\r\nexport interface SseInterceptor<T = unknown> {\r\n sseIntercept<U = T>(...args: Parameters<SseInterceptorFn<U>>): ReturnType<SseInterceptorFn<U>>;\r\n}\r\n\r\n/**\r\n * Injection token for providing SSE interceptors.\r\n * Use with multi: true to provide multiple interceptors.\r\n */\r\nexport const SSE_INTERCEPTORS = new InjectionToken<SseInterceptor<unknown>[]>('Telperion/SSE_INTERCEPTORS');\r\n","import { inject, Injectable } from \"@angular/core\";\r\nimport { Observable } from \"rxjs\";\r\n\r\nimport { SSE_INTERCEPTORS, SseRequest } from \"./interceptor\";\r\n\r\n/**\r\n * Angular service for managing Server-Sent Events (SSE) connections.\r\n * Wraps the EventSource API with RxJS Observables and an HttpClient-inspired interceptor chain.\r\n *\r\n * @example\r\n * ```typescript\r\n * class MyComponent {\r\n * private sseClient = inject(SseClient);\r\n *\r\n * messages$ = this.sseClient.start<string>('/api/events');\r\n * }\r\n * ```\r\n */\r\n@Injectable()\r\nexport class SseClient {\r\n #interceptors = inject(SSE_INTERCEPTORS, { optional: true }) ?? [];\r\n\r\n constructor() {\r\n if (!(this.#interceptors instanceof Array)) {\r\n throw new Error('SSE_INTERCEPTORS must be provided as an array. Please ensure you are using multi: true when providing interceptors.');\r\n }\r\n }\r\n\r\n /**\r\n * Starts a new Server-Sent Events connection and returns an Observable stream.\r\n *\r\n * @param url - The URL endpoint for the SSE connection\r\n * @param init - Optional EventSource initialization configuration\r\n * @returns Observable stream of server-sent events\r\n *\r\n * @example\r\n * ```typescript\r\n * this.sseClient.start<MessageData>('/api/notifications', { withCredentials: true })\r\n * .subscribe(data => console.log('Received:', data));\r\n * ```\r\n */\r\n start<T>(url: string, init: EventSourceInit = {}): Observable<T> {\r\n return this.#interceptors.reduceRight(\r\n (next, interceptor) => (req) => interceptor.sseIntercept(req, next),\r\n (req: SseRequest) => this.#createEventSource(req) as Observable<T>\r\n )({ url, init });\r\n }\r\n\r\n #createEventSource<T>(request: SseRequest): Observable<T> {\r\n return new Observable<T>((subscriber) => {\r\n const eventSource = new EventSource(request.url, request.init);\r\n\r\n function handleMessage(event: MessageEvent) {\r\n subscriber.next(event.data);\r\n }\r\n\r\n function handleError(err: Event) {\r\n subscriber.error(err);\r\n eventSource.close();\r\n }\r\n\r\n eventSource.addEventListener('message', handleMessage);\r\n eventSource.addEventListener('error', handleError);\r\n\r\n return () => {\r\n eventSource.removeEventListener('message', handleMessage);\r\n eventSource.removeEventListener('error', handleError);\r\n eventSource.close();\r\n };\r\n });\r\n }\r\n}\r\n","import { Provider } from \"@angular/core\";\r\n\r\nimport { SseClient } from \"./client\";\r\nimport { SseFeature, SseFeatureKind, SseInterceptorFunctionFeature } from \"./features\";\r\nimport { SSE_INTERCEPTORS } from \"./interceptor\";\r\n\r\n/**\r\n * Provides the SseClient service with optional features.\r\n * Configure SSE client with interceptors and other features using a functional API.\r\n *\r\n * @param features - Optional feature configurations (e.g., withSseInterceptors())\r\n * @returns Array of Angular providers\r\n *\r\n * @example\r\n * ```typescript\r\n * import { provideSseClient, withSseInterceptors } from '@telperion/ng-pack/sse-client';\r\n *\r\n * export const appConfig: ApplicationConfig = {\r\n * providers: [\r\n * provideSseClient(\r\n * withSseInterceptors(loggingInterceptor, authInterceptor)\r\n * )\r\n * ]\r\n * };\r\n * ```\r\n */\r\nexport function provideSseClient(...features: SseFeature[][]): Provider[] {\r\n const interceptorFns = features\r\n .flat()\r\n .filter(feature => feature.kind === SseFeatureKind.InterceptorFunction)\r\n .map(feature => ({\r\n provide: SSE_INTERCEPTORS,\r\n useValue: {\r\n sseIntercept: (feature as SseInterceptorFunctionFeature).interceptor,\r\n },\r\n multi: true,\r\n }));\r\n\r\n return [\r\n {\r\n provide: SseClient,\r\n useClass: SseClient\r\n },\r\n ...interceptorFns\r\n ];\r\n}\r\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@telperion/ng-pack",
3
- "version": "1.2.2",
3
+ "version": "1.3.1",
4
+ "description": "Collection of Angular utilities and libraries organized as secondary entry points. Includes signal-based storage (localStorage/sessionStorage), SSE client with HttpClient-inspired interceptors, event modifier plugins, and more. Built with TypeScript, RxJS, and Angular Signals for modern Angular applications.",
5
+ "keywords": [
6
+ "angular",
7
+ "angular-signals",
8
+ "rxjs",
9
+ "sse",
10
+ "server-sent-events",
11
+ "eventsource",
12
+ "localstorage",
13
+ "sessionstorage",
14
+ "storage",
15
+ "signals",
16
+ "interceptors",
17
+ "event-modifiers",
18
+ "utilities",
19
+ "typescript",
20
+ "reactive",
21
+ "real-time",
22
+ "httpclient",
23
+ "secondary-entrypoint",
24
+ "angular-utilities",
25
+ "event-manager"
26
+ ],
4
27
  "peerDependencies": {
5
28
  "@angular/common": "^21.0.0",
6
29
  "@angular/core": "^21.0.0",
@@ -40,6 +63,10 @@
40
63
  "types": "./types/telperion-ng-pack.d.ts",
41
64
  "default": "./fesm2022/telperion-ng-pack.mjs"
42
65
  },
66
+ "./sse-client": {
67
+ "types": "./types/telperion-ng-pack-sse-client.d.ts",
68
+ "default": "./fesm2022/telperion-ng-pack-sse-client.mjs"
69
+ },
43
70
  "./storage-signals": {
44
71
  "types": "./types/telperion-ng-pack-storage-signals.d.ts",
45
72
  "default": "./fesm2022/telperion-ng-pack-storage-signals.mjs"
@@ -0,0 +1,719 @@
1
+ # @telperion/ng-pack/sse-client
2
+
3
+ Angular service for Server-Sent Events (SSE) with RxJS Observables and HttpClient-inspired interceptors.
4
+
5
+ ## Features
6
+
7
+ - 🚀 **Observable-based API** - Seamlessly integrate with RxJS ecosystem
8
+ - 🔗 **HttpClient-inspired interceptors** - Functional and class-based interceptors (shareable with HttpClient)
9
+ - 🎯 **Type-safe** - Full TypeScript support with generic typing
10
+ - ⚡ **EventSource wrapper** - Clean abstraction over native EventSource API
11
+ - 🔄 **Reactive streaming** - Real-time data updates with automatic cleanup
12
+ - 🎨 **Feature-based configuration** - Extensible architecture following modern Angular patterns
13
+ - 🧹 **Automatic cleanup** - Proper resource management on unsubscribe
14
+
15
+ ## Installation
16
+
17
+ This is a secondary entry point of `@telperion/ng-pack`. Import from `@telperion/ng-pack/sse-client`.
18
+
19
+ ```bash
20
+ npm install @telperion/ng-pack
21
+ ```
22
+
23
+ ## Setup
24
+
25
+ Configure the SSE client in your application config:
26
+
27
+ ```typescript
28
+ import { ApplicationConfig } from '@angular/core';
29
+ import { provideSseClient } from '@telperion/ng-pack/sse-client';
30
+
31
+ export const appConfig: ApplicationConfig = {
32
+ providers: [
33
+ provideSseClient(),
34
+ // ... other providers
35
+ ]
36
+ };
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ ### Basic Usage
42
+
43
+ Create a component that connects to an SSE endpoint and displays real-time data:
44
+
45
+ ```typescript
46
+ import { Component, inject } from '@angular/core';
47
+ import { SseClient } from '@telperion/ng-pack/sse-client';
48
+ import { AsyncPipe } from '@angular/common';
49
+
50
+ interface StockUpdate {
51
+ symbol: string;
52
+ price: number;
53
+ change: number;
54
+ }
55
+
56
+ @Component({
57
+ selector: 'app-stock-ticker',
58
+ template: `
59
+ <div class="stock-ticker">
60
+ <h2>Live Stock Prices</h2>
61
+ @if (stockUpdates$ | async; as update) {
62
+ <div class="stock-card">
63
+ <span class="symbol">{{ update.symbol }}</span>
64
+ <span class="price">\${{ update.price }}</span>
65
+ <span [class.positive]="update.change > 0" [class.negative]="update.change < 0">
66
+ {{ update.change > 0 ? '+' : '' }}{{ update.change }}%
67
+ </span>
68
+ </div>
69
+ }
70
+ </div>
71
+ `,
72
+ standalone: true,
73
+ imports: [AsyncPipe]
74
+ })
75
+ export class StockTickerComponent {
76
+ private sseClient = inject(SseClient);
77
+
78
+ // Start SSE connection and get Observable stream
79
+ stockUpdates$ = this.sseClient.start<StockUpdate>('/api/stocks/stream');
80
+ }
81
+ ```
82
+
83
+ ### Using Interceptors
84
+
85
+ Interceptors allow you to modify requests, add logging, handle authentication, or implement retry logic. They work just like Angular's HttpClient interceptors.
86
+
87
+ #### Logging Interceptor
88
+
89
+ ```typescript
90
+ import { SseInterceptorFn } from '@telperion/ng-pack/sse-client';
91
+ import { tap } from 'rxjs/operators';
92
+
93
+ export const loggingInterceptor: SseInterceptorFn<any> = (req, next) => {
94
+ console.log('[SSE] Connecting to:', req.url);
95
+
96
+ return next(req).pipe(
97
+ tap({
98
+ next: data => console.log('[SSE] Received:', data),
99
+ error: err => console.error('[SSE] Error:', err),
100
+ complete: () => console.log('[SSE] Connection closed')
101
+ })
102
+ );
103
+ };
104
+ ```
105
+
106
+ #### Authentication Interceptor
107
+
108
+ ```typescript
109
+ import { SseInterceptorFn } from '@telperion/ng-pack/sse-client';
110
+
111
+ export const authInterceptor: SseInterceptorFn<any> = (req, next) => {
112
+ // Add authentication token to URL or modify request
113
+ const token = localStorage.getItem('auth_token');
114
+ const authenticatedUrl = `${req.url}?token=${token}`;
115
+
116
+ return next({
117
+ ...req,
118
+ url: authenticatedUrl
119
+ });
120
+ };
121
+ ```
122
+
123
+ #### Retry Interceptor
124
+
125
+ ```typescript
126
+ import { SseInterceptorFn } from '@telperion/ng-pack/sse-client';
127
+ import { retry, timer } from 'rxjs';
128
+
129
+ export const retryInterceptor: SseInterceptorFn<any> = (req, next) => {
130
+ return next(req).pipe(
131
+ retry({
132
+ count: 3,
133
+ delay: (error, retryCount) => {
134
+ console.log(`[SSE] Retry attempt ${retryCount} after error:`, error);
135
+ return timer(1000 * retryCount); // Exponential backoff
136
+ }
137
+ })
138
+ );
139
+ };
140
+ ```
141
+
142
+ #### Configuring Interceptors
143
+
144
+ Provide interceptors using the `withSseInterceptors()` feature function:
145
+
146
+ ```typescript
147
+ import { ApplicationConfig } from '@angular/core';
148
+ import { provideSseClient, withSseInterceptors } from '@telperion/ng-pack/sse-client';
149
+ import { loggingInterceptor, authInterceptor, retryInterceptor } from './interceptors';
150
+
151
+ export const appConfig: ApplicationConfig = {
152
+ providers: [
153
+ provideSseClient(
154
+ withSseInterceptors(
155
+ loggingInterceptor,
156
+ authInterceptor,
157
+ retryInterceptor
158
+ )
159
+ )
160
+ ]
161
+ };
162
+ ```
163
+
164
+ **Interceptor execution order:** Interceptors are executed in the order they are provided. In the example above, the chain is: logging → auth → retry → EventSource connection.
165
+
166
+ #### Class-based Interceptors
167
+
168
+ For more complex scenarios, you can create class-based interceptors and provide them directly using the `SSE_INTERCEPTORS` token. This is particularly useful when you need dependency injection or want to share logic between HTTP and SSE interceptors.
169
+
170
+ **Using SSE_INTERCEPTORS token:**
171
+
172
+ ```typescript
173
+ import { Injectable } from '@angular/core';
174
+ import { SseInterceptor, SseRequest, SseNextFn, SSE_INTERCEPTORS } from '@telperion/ng-pack/sse-client';
175
+ import { Observable } from 'rxjs';
176
+
177
+ @Injectable()
178
+ export class ApiUrlInterceptor implements SseInterceptor<unknown> {
179
+ sseIntercept<T = unknown>(request: SseRequest, next: SseNextFn<T>): Observable<T> {
180
+ const url = request.url.replace(/^@/, 'https://api.example.com');
181
+ return next({ ...request, url });
182
+ }
183
+ }
184
+
185
+ // Provide directly using the token
186
+ export const appConfig: ApplicationConfig = {
187
+ providers: [
188
+ provideSseClient(),
189
+ { provide: SSE_INTERCEPTORS, useClass: ApiUrlInterceptor, multi: true }
190
+ ]
191
+ };
192
+ ```
193
+
194
+ **Unified HTTP and SSE Interceptor:**
195
+
196
+ You can create a single interceptor class that handles both HTTP and SSE requests, allowing you to share authentication, URL rewriting, or other common logic:
197
+
198
+ ```typescript
199
+ import { Injectable } from '@angular/core';
200
+ import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HTTP_INTERCEPTORS } from '@angular/common/http';
201
+ import { SseInterceptor, SseRequest, SseNextFn, SSE_INTERCEPTORS } from '@telperion/ng-pack/sse-client';
202
+ import { localStorageSignal } from '@telperion/ng-pack/storage-signals';
203
+ import { Observable } from 'rxjs';
204
+
205
+ @Injectable()
206
+ export class BaseApiInterceptor implements HttpInterceptor, SseInterceptor<unknown> {
207
+
208
+ // Handle HTTP requests
209
+ intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
210
+ return next.handle(req.clone({ url: this.#replaceUrl(req.url) }));
211
+ }
212
+
213
+ // Handle SSE requests
214
+ sseIntercept<T = unknown>(request: SseRequest, next: SseNextFn<T>): Observable<T> {
215
+ return next({ ...request, url: this.replaceUrl(request.url)});
216
+ }
217
+
218
+ #replaceUrl(url: string): string {
219
+ return `https://my-api.domain.com/${url}`;
220
+ }
221
+ }
222
+
223
+ // Register for both HTTP and SSE
224
+ export const appConfig: ApplicationConfig = {
225
+ providers: [
226
+ // Provide the same interceptor for both HTTP and SSE
227
+ { provide: HTTP_INTERCEPTORS, useClass: BaseApiInterceptor, multi: true },
228
+ { provide: SSE_INTERCEPTORS, useClass: BaseApiInterceptor, multi: true },
229
+
230
+ provideHttpClient(withFetch(), withInterceptorsFromDi()),
231
+ provideSseClient(),
232
+ ]
233
+ };
234
+ ```
235
+
236
+ This pattern is especially useful when you want to:
237
+ - Share authentication logic between HTTP and SSE
238
+ - Apply consistent URL transformations
239
+ - Reuse common error handling
240
+ - Maintain a single source of truth for API configuration
241
+
242
+ **Note:** You can combine both approaches - use the `SSE_INTERCEPTORS` token for class-based interceptors and `withSseInterceptors()` for functional interceptors. Class-based interceptors provided via the token will execute before functional interceptors provided via `withSseInterceptors()`.
243
+
244
+ ### Advanced Usage
245
+
246
+ #### Real-time Notifications
247
+
248
+ ```typescript
249
+ import { Component, inject } from '@angular/core';
250
+ import { SseClient } from '@telperion/ng-pack/sse-client';
251
+ import { AsyncPipe } from '@angular/common';
252
+
253
+ interface Notification {
254
+ id: string;
255
+ message: string;
256
+ type: 'info' | 'warning' | 'error';
257
+ timestamp: number;
258
+ }
259
+
260
+ @Component({
261
+ selector: 'app-notifications',
262
+ template: `
263
+ <div class="notifications">
264
+ @for (notification of notifications$ | async; track notification.id) {
265
+ <div [class]="'notification ' + notification.type">
266
+ <span class="message">{{ notification.message }}</span>
267
+ <span class="time">{{ notification.timestamp | date:'short' }}</span>
268
+ </div>
269
+ }
270
+ </div>
271
+ `,
272
+ standalone: true,
273
+ imports: [AsyncPipe]
274
+ })
275
+ export class NotificationsComponent {
276
+ private sseClient = inject(SseClient);
277
+
278
+ notifications$ = this.sseClient.start<Notification>('/api/notifications/stream');
279
+ }
280
+ ```
281
+
282
+ #### Managing Subscriptions
283
+
284
+ Always unsubscribe from SSE connections when they're no longer needed:
285
+
286
+ ```typescript
287
+ import { Component, inject, OnDestroy } from '@angular/core';
288
+ import { SseClient } from '@telperion/ng-pack/sse-client';
289
+ import { Subscription } from 'rxjs';
290
+
291
+ @Component({
292
+ selector: 'app-dashboard',
293
+ template: `
294
+ <div>
295
+ <h2>Dashboard</h2>
296
+ <p>Active users: {{ activeUsers }}</p>
297
+ </div>
298
+ `
299
+ })
300
+ export class DashboardComponent implements OnDestroy {
301
+ private sseClient = inject(SseClient);
302
+ private subscription?: Subscription;
303
+
304
+ activeUsers = 0;
305
+
306
+ ngOnInit() {
307
+ // Subscribe manually for more control
308
+ this.subscription = this.sseClient
309
+ .start<{ count: number }>('/api/dashboard/active-users')
310
+ .subscribe({
311
+ next: data => this.activeUsers = data.count,
312
+ error: err => console.error('SSE error:', err)
313
+ });
314
+ }
315
+
316
+ ngOnDestroy() {
317
+ // Clean up subscription and close EventSource
318
+ this.subscription?.unsubscribe();
319
+ }
320
+ }
321
+ ```
322
+
323
+ **Best practice:** Use the `AsyncPipe` when possible to automatically handle subscription management.
324
+
325
+ #### Error Handling
326
+
327
+ ```typescript
328
+ import { Component, inject } from '@angular/core';
329
+ import { SseClient } from '@telperion/ng-pack/sse-client';
330
+ import { catchError, of } from 'rxjs';
331
+
332
+ @Component({
333
+ selector: 'app-feed',
334
+ template: `
335
+ <div>
336
+ @if (error) {
337
+ <div class="error">{{ error }}</div>
338
+ } @else {
339
+ <div>{{ data$ | async }}</div>
340
+ }
341
+ </div>
342
+ `
343
+ })
344
+ export class FeedComponent {
345
+ private sseClient = inject(SseClient);
346
+ error?: string;
347
+
348
+ data$ = this.sseClient.start('/api/feed').pipe(
349
+ catchError(err => {
350
+ this.error = 'Failed to connect to live feed';
351
+ console.error('SSE connection error:', err);
352
+ return of(null);
353
+ })
354
+ );
355
+ }
356
+ ```
357
+
358
+ #### Custom EventSource Configuration
359
+
360
+ Pass EventSource initialization options to configure credentials, CORS, etc.:
361
+
362
+ ```typescript
363
+ @Component({
364
+ selector: 'app-secure-feed',
365
+ template: `<div>{{ data$ | async }}</div>`
366
+ })
367
+ export class SecureFeedComponent {
368
+ private sseClient = inject(SseClient);
369
+
370
+ data$ = this.sseClient.start('/api/secure/feed', {
371
+ withCredentials: true // Send cookies with the request
372
+ });
373
+ }
374
+ ```
375
+
376
+ ## API Reference
377
+
378
+ ### `provideSseClient(...features: SseFeature[][]): Provider[]`
379
+
380
+ Provides the SSE client service with optional feature configurations.
381
+
382
+ **Parameters:**
383
+ - `features` (optional) - Feature configurations such as `withSseInterceptors()`
384
+
385
+ **Returns:** Array of Angular providers
386
+
387
+ **Example:**
388
+ ```typescript
389
+ provideSseClient(
390
+ withSseInterceptors(loggingInterceptor, authInterceptor)
391
+ )
392
+ ```
393
+
394
+ ---
395
+
396
+ ### `SseClient`
397
+
398
+ Injectable service for managing SSE connections.
399
+
400
+ #### `start<T>(url: string, init?: EventSourceInit): Observable<T>`
401
+
402
+ Starts a new Server-Sent Events connection and returns an Observable stream.
403
+
404
+ **Parameters:**
405
+ - `url` - The endpoint URL for the SSE connection
406
+ - `init` (optional) - EventSource initialization options (e.g., `{ withCredentials: true }`)
407
+
408
+ **Returns:** Observable stream of typed server-sent events
409
+
410
+ **Example:**
411
+ ```typescript
412
+ sseClient.start<MessageData>('/api/events', { withCredentials: true })
413
+ .subscribe(data => console.log('Received:', data));
414
+ ```
415
+
416
+ ---
417
+
418
+ ### `withSseInterceptors(...interceptors: SseInterceptorFn<T>[]): SseFeature[]`
419
+
420
+ Configures functional interceptors for the SSE client.
421
+
422
+ **Parameters:**
423
+ - `interceptors` - One or more functional interceptor functions
424
+
425
+ **Returns:** Array of SSE features to be used with `provideSseClient()`
426
+
427
+ **Example:**
428
+ ```typescript
429
+ withSseInterceptors(
430
+ loggingInterceptor,
431
+ authInterceptor,
432
+ retryInterceptor
433
+ )
434
+ ```
435
+
436
+ ---
437
+
438
+ ### `SseInterceptorFn<T>`
439
+
440
+ Type definition for functional interceptors.
441
+
442
+ ```typescript
443
+ type SseInterceptorFn<T> = (
444
+ request: SseRequest,
445
+ next: SseNextFn<T>
446
+ ) => Observable<T>;
447
+ ```
448
+
449
+ **Parameters:**
450
+ - `request` - The SSE request containing `url` and `init`
451
+ - `next` - Function to call the next interceptor in the chain
452
+
453
+ **Returns:** Observable of the intercepted request
454
+
455
+ ---
456
+
457
+ ### `SseRequest`
458
+
459
+ Interface representing an SSE request.
460
+
461
+ ```typescript
462
+ interface SseRequest {
463
+ url: string;
464
+ init: EventSourceInit;
465
+ }
466
+ ```
467
+
468
+ ---
469
+
470
+ ### `SseInterceptor<T>`
471
+
472
+ Class-based interceptor interface (for advanced use cases).
473
+
474
+ ```typescript
475
+ interface SseInterceptor<T = unknown> {
476
+ sseIntercept<U = T>(
477
+ request: SseRequest,
478
+ next: SseNextFn<U>
479
+ ): Observable<U>;
480
+ }
481
+ ```
482
+
483
+ **Example:**
484
+ ```typescript
485
+ @Injectable()
486
+ class MyInterceptor implements SseInterceptor<unknown> {
487
+ sseIntercept<T>(request: SseRequest, next: SseNextFn<T>): Observable<T> {
488
+ console.log('Intercepting:', request.url);
489
+ return next(request);
490
+ }
491
+ }
492
+ ```
493
+
494
+ ---
495
+
496
+ ### `SSE_INTERCEPTORS`
497
+
498
+ Injection token for providing class-based SSE interceptors directly.
499
+
500
+ ```typescript
501
+ const SSE_INTERCEPTORS: InjectionToken<SseInterceptor<unknown>[]>
502
+ ```
503
+
504
+ **Usage:**
505
+ ```typescript
506
+ import { SSE_INTERCEPTORS } from '@telperion/ng-pack/sse-client';
507
+
508
+ export const appConfig: ApplicationConfig = {
509
+ providers: [
510
+ provideSseClient(),
511
+ { provide: SSE_INTERCEPTORS, useClass: MyInterceptor, multi: true }
512
+ ]
513
+ };
514
+ ```
515
+
516
+ **Note:** This token allows you to provide class-based interceptors that can leverage dependency injection. It's particularly useful for creating interceptors that implement both `HttpInterceptor` and `SseInterceptor` to share logic between HTTP and SSE requests.
517
+
518
+ ## Best Practices
519
+
520
+ ### 1. Always Unsubscribe
521
+
522
+ Use the `AsyncPipe` or manually unsubscribe to prevent memory leaks and close connections:
523
+
524
+ ```typescript
525
+ // ✅ Good - using AsyncPipe (automatic cleanup)
526
+ data$ = this.sseClient.start('/api/feed');
527
+
528
+ // ✅ Good - manual subscription with cleanup
529
+ ngOnInit() {
530
+ this.subscription = this.sseClient.start('/api/feed').subscribe(...);
531
+ }
532
+
533
+ ngOnDestroy() {
534
+ this.subscription?.unsubscribe();
535
+ }
536
+
537
+ // ❌ Bad - no cleanup
538
+ ngOnInit() {
539
+ this.sseClient.start('/api/feed').subscribe(...);
540
+ }
541
+ ```
542
+
543
+ ### 2. Handle Errors Gracefully
544
+
545
+ Always implement error handling for SSE connections:
546
+
547
+ ```typescript
548
+ data$ = this.sseClient.start('/api/feed').pipe(
549
+ catchError(err => {
550
+ console.error('SSE error:', err);
551
+ // Return fallback value or retry
552
+ return of(null);
553
+ })
554
+ );
555
+ ```
556
+
557
+ ### 3. Use Type Safety
558
+
559
+ Leverage TypeScript generics for type-safe event data:
560
+
561
+ ```typescript
562
+ // ✅ Good - typed
563
+ interface StockUpdate {
564
+ symbol: string;
565
+ price: number;
566
+ }
567
+ data$ = this.sseClient.start<StockUpdate>('/api/stocks');
568
+
569
+ // ❌ Bad - untyped
570
+ data$ = this.sseClient.start('/api/stocks');
571
+ ```
572
+
573
+ ### 4. Interceptor Order Matters
574
+
575
+ Place interceptors in logical order. Generally: logging → authentication → error handling → retry:
576
+
577
+ ```typescript
578
+ provideSseClient(
579
+ withSseInterceptors(
580
+ loggingInterceptor, // First: log everything
581
+ authInterceptor, // Second: add auth
582
+ errorHandlerInterceptor, // Third: handle errors
583
+ retryInterceptor // Last: retry failed connections
584
+ )
585
+ )
586
+ ```
587
+
588
+ ### 5. Consider Reconnection Strategies
589
+
590
+ For production applications, implement retry logic with exponential backoff:
591
+
592
+ ```typescript
593
+ const retryInterceptor: SseInterceptorFn<any> = (req, next) => {
594
+ return next(req).pipe(
595
+ retry({
596
+ count: 5,
597
+ delay: (error, retryCount) => timer(Math.min(1000 * Math.pow(2, retryCount), 30000))
598
+ })
599
+ );
600
+ };
601
+ ```
602
+
603
+ ### 6. Use Environment-Specific Configuration
604
+
605
+ Configure different interceptors for development and production:
606
+
607
+ ```typescript
608
+ // app.config.ts
609
+ const interceptors = environment.production
610
+ ? [authInterceptor, retryInterceptor]
611
+ : [loggingInterceptor, authInterceptor, retryInterceptor];
612
+
613
+ export const appConfig: ApplicationConfig = {
614
+ providers: [
615
+ provideSseClient(withSseInterceptors(...interceptors))
616
+ ]
617
+ };
618
+ ```
619
+
620
+ ### 7. Share Logic with HTTP Interceptors
621
+
622
+ When you need the same logic for both HTTP and SSE (auth, URL rewriting, etc.), create a unified interceptor class:
623
+
624
+ ```typescript
625
+ @Injectable()
626
+ class UnifiedInterceptor implements HttpInterceptor, SseInterceptor<unknown> {
627
+ intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
628
+ // HTTP logic
629
+ }
630
+
631
+ sseIntercept<T>(request: SseRequest, next: SseNextFn<T>): Observable<T> {
632
+ // SSE logic (can reuse same helper methods)
633
+ }
634
+ }
635
+
636
+ // ✅ Good - shared interceptor for both
637
+ providers: [
638
+ { provide: HTTP_INTERCEPTORS, useClass: UnifiedInterceptor, multi: true },
639
+ { provide: SSE_INTERCEPTORS, useClass: UnifiedInterceptor, multi: true },
640
+ ]
641
+
642
+ // ❌ Bad - duplicated logic in separate interceptors
643
+ ```
644
+
645
+ This approach:
646
+ - Reduces code duplication
647
+ - Ensures consistent behavior across HTTP and SSE
648
+ - Makes configuration and API changes easier to manage
649
+ - Allows sharing of injected dependencies
650
+
651
+ ## Common Use Cases
652
+
653
+ ### Real-time Chat
654
+
655
+ ```typescript
656
+ interface ChatMessage {
657
+ id: string;
658
+ user: string;
659
+ message: string;
660
+ timestamp: number;
661
+ }
662
+
663
+ messages$ = this.sseClient.start<ChatMessage>('/api/chat/stream');
664
+ ```
665
+
666
+ ### Live Dashboard Metrics
667
+
668
+ ```typescript
669
+ interface Metrics {
670
+ cpu: number;
671
+ memory: number;
672
+ activeUsers: number;
673
+ }
674
+
675
+ metrics$ = this.sseClient.start<Metrics>('/api/dashboard/metrics');
676
+ ```
677
+
678
+ ### Stock Price Updates
679
+
680
+ ```typescript
681
+ interface StockPrice {
682
+ symbol: string;
683
+ price: number;
684
+ volume: number;
685
+ }
686
+
687
+ stocks$ = this.sseClient.start<StockPrice>('/api/stocks/live');
688
+ ```
689
+
690
+ ### Server Logs Streaming
691
+
692
+ ```typescript
693
+ interface LogEntry {
694
+ level: 'info' | 'warn' | 'error';
695
+ message: string;
696
+ timestamp: number;
697
+ }
698
+
699
+ logs$ = this.sseClient.start<LogEntry>('/api/logs/stream');
700
+ ```
701
+
702
+ ## Comparison with HttpClient
703
+
704
+ The SSE client deliberately mirrors Angular's HttpClient pattern:
705
+
706
+ | Feature | HttpClient | SseClient |
707
+ |---------|------------|-----------|
708
+ | **Return Type** | `Observable` | `Observable` |
709
+ | **Interceptors** | `HttpInterceptor` | `SseInterceptor` |
710
+ | **Provider** | `provideHttpClient()` | `provideSseClient()` |
711
+ | **Features** | `withInterceptors()` | `withSseInterceptors()` |
712
+ | **Connection** | Request/Response | Persistent stream |
713
+ | **Use Case** | REST APIs | Real-time updates |
714
+
715
+ This familiar pattern makes it easy for Angular developers to adopt SSE for real-time features.
716
+
717
+ ## License
718
+
719
+ This library is part of the Telperion monorepo.
@@ -0,0 +1,141 @@
1
+ import * as i0 from '@angular/core';
2
+ import { InjectionToken, Provider } from '@angular/core';
3
+ import { Observable } from 'rxjs';
4
+
5
+ /**
6
+ * Enum identifying different types of SSE features.
7
+ */
8
+ declare enum SseFeatureKind {
9
+ InterceptorFunction = 0
10
+ }
11
+ /**
12
+ * Base interface for SSE feature configurations.
13
+ */
14
+ interface SseFeature {
15
+ kind: SseFeatureKind;
16
+ }
17
+
18
+ /**
19
+ * Represents an SSE request with URL and initialization options.
20
+ */
21
+ interface SseRequest {
22
+ url: string;
23
+ init: EventSourceInit;
24
+ }
25
+ /**
26
+ * Function type for passing the request to the next handler in the interceptor chain.
27
+ */
28
+ type SseNextFn<T> = (request: SseRequest) => Observable<T>;
29
+ /**
30
+ * Functional interceptor type for intercepting SSE requests.
31
+ * Interceptors can modify requests, handle errors, add logging, etc.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * const loggingInterceptor: SseInterceptorFn<any> = (req, next) => {
36
+ * console.log('SSE Request:', req.url);
37
+ * return next(req);
38
+ * };
39
+ * ```
40
+ */
41
+ type SseInterceptorFn<T> = (request: SseRequest, next: SseNextFn<T>) => Observable<T>;
42
+ /**
43
+ * Class-based interceptor interface for SSE requests.
44
+ * Implements the same pattern as Angular's HttpInterceptor.
45
+ */
46
+ interface SseInterceptor<T = unknown> {
47
+ sseIntercept<U = T>(...args: Parameters<SseInterceptorFn<U>>): ReturnType<SseInterceptorFn<U>>;
48
+ }
49
+ /**
50
+ * Injection token for providing SSE interceptors.
51
+ * Use with multi: true to provide multiple interceptors.
52
+ */
53
+ declare const SSE_INTERCEPTORS: InjectionToken<SseInterceptor<unknown>[]>;
54
+
55
+ /**
56
+ * Feature interface for functional interceptors.
57
+ * @internal
58
+ */
59
+ interface SseInterceptorFunctionFeature extends SseFeature {
60
+ kind: SseFeatureKind.InterceptorFunction;
61
+ interceptor: SseInterceptorFn<unknown>;
62
+ }
63
+ /**
64
+ * Configures functional interceptors for the SSE client.
65
+ * Interceptors are executed in the order they are provided.
66
+ *
67
+ * @param interceptors - One or more functional interceptor functions
68
+ * @returns Array of SSE features to be used with provideSseClient()
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * const loggingInterceptor: SseInterceptorFn<any> = (req, next) => {
73
+ * console.log('Connecting to:', req.url);
74
+ * return next(req);
75
+ * };
76
+ *
77
+ * provideSseClient(
78
+ * withSseInterceptors(loggingInterceptor)
79
+ * )
80
+ * ```
81
+ */
82
+ declare function withSseInterceptors<T = unknown>(...interceptors: SseInterceptorFn<T>[]): SseFeature[];
83
+
84
+ /**
85
+ * Angular service for managing Server-Sent Events (SSE) connections.
86
+ * Wraps the EventSource API with RxJS Observables and an HttpClient-inspired interceptor chain.
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * class MyComponent {
91
+ * private sseClient = inject(SseClient);
92
+ *
93
+ * messages$ = this.sseClient.start<string>('/api/events');
94
+ * }
95
+ * ```
96
+ */
97
+ declare class SseClient {
98
+ #private;
99
+ constructor();
100
+ /**
101
+ * Starts a new Server-Sent Events connection and returns an Observable stream.
102
+ *
103
+ * @param url - The URL endpoint for the SSE connection
104
+ * @param init - Optional EventSource initialization configuration
105
+ * @returns Observable stream of server-sent events
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * this.sseClient.start<MessageData>('/api/notifications', { withCredentials: true })
110
+ * .subscribe(data => console.log('Received:', data));
111
+ * ```
112
+ */
113
+ start<T>(url: string, init?: EventSourceInit): Observable<T>;
114
+ static ɵfac: i0.ɵɵFactoryDeclaration<SseClient, never>;
115
+ static ɵprov: i0.ɵɵInjectableDeclaration<SseClient>;
116
+ }
117
+
118
+ /**
119
+ * Provides the SseClient service with optional features.
120
+ * Configure SSE client with interceptors and other features using a functional API.
121
+ *
122
+ * @param features - Optional feature configurations (e.g., withSseInterceptors())
123
+ * @returns Array of Angular providers
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * import { provideSseClient, withSseInterceptors } from '@telperion/ng-pack/sse-client';
128
+ *
129
+ * export const appConfig: ApplicationConfig = {
130
+ * providers: [
131
+ * provideSseClient(
132
+ * withSseInterceptors(loggingInterceptor, authInterceptor)
133
+ * )
134
+ * ]
135
+ * };
136
+ * ```
137
+ */
138
+ declare function provideSseClient(...features: SseFeature[][]): Provider[];
139
+
140
+ export { SSE_INTERCEPTORS, SseClient, SseFeatureKind, provideSseClient, withSseInterceptors };
141
+ export type { SseFeature, SseInterceptor, SseInterceptorFn, SseInterceptorFunctionFeature, SseNextFn, SseRequest };