@connexis/transport-sse 1.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.
- package/LICENSE +21 -0
- package/dist/index.d.mts +32 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +180 -0
- package/dist/index.mjs +155 -0
- package/package.json +24 -0
- package/src/index.ts +189 -0
- package/tsconfig.json +8 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Connexis Realtime Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Transport, ConnectionState, TransportCapabilities } from '@connexis/core';
|
|
2
|
+
|
|
3
|
+
interface SSETransportOptions {
|
|
4
|
+
publishUrl?: string;
|
|
5
|
+
publish?: (topic: string, data: any) => Promise<void>;
|
|
6
|
+
withCredentials?: boolean;
|
|
7
|
+
}
|
|
8
|
+
declare class SSETransport implements Transport {
|
|
9
|
+
private url;
|
|
10
|
+
private options;
|
|
11
|
+
readonly type = "sse";
|
|
12
|
+
private eventSource;
|
|
13
|
+
private _state;
|
|
14
|
+
private messageCb;
|
|
15
|
+
private stateCb;
|
|
16
|
+
private activeListeners;
|
|
17
|
+
constructor(url: string, options?: SSETransportOptions);
|
|
18
|
+
get state(): ConnectionState;
|
|
19
|
+
connect(): Promise<void>;
|
|
20
|
+
disconnect(): Promise<void>;
|
|
21
|
+
publish(topic: string, data: any): Promise<void>;
|
|
22
|
+
subscribe(topic: string, _filter?: Record<string, any>): Promise<void>;
|
|
23
|
+
unsubscribe(topic: string, _filter?: Record<string, any>): Promise<void>;
|
|
24
|
+
capabilities(): TransportCapabilities;
|
|
25
|
+
onMessage(cb: (topic: string, data: any) => void): void;
|
|
26
|
+
onStateChange(cb: (state: ConnectionState, error?: Error) => void): void;
|
|
27
|
+
clone(): SSETransport;
|
|
28
|
+
private handleGenericMessage;
|
|
29
|
+
private updateState;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export { SSETransport, type SSETransportOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Transport, ConnectionState, TransportCapabilities } from '@connexis/core';
|
|
2
|
+
|
|
3
|
+
interface SSETransportOptions {
|
|
4
|
+
publishUrl?: string;
|
|
5
|
+
publish?: (topic: string, data: any) => Promise<void>;
|
|
6
|
+
withCredentials?: boolean;
|
|
7
|
+
}
|
|
8
|
+
declare class SSETransport implements Transport {
|
|
9
|
+
private url;
|
|
10
|
+
private options;
|
|
11
|
+
readonly type = "sse";
|
|
12
|
+
private eventSource;
|
|
13
|
+
private _state;
|
|
14
|
+
private messageCb;
|
|
15
|
+
private stateCb;
|
|
16
|
+
private activeListeners;
|
|
17
|
+
constructor(url: string, options?: SSETransportOptions);
|
|
18
|
+
get state(): ConnectionState;
|
|
19
|
+
connect(): Promise<void>;
|
|
20
|
+
disconnect(): Promise<void>;
|
|
21
|
+
publish(topic: string, data: any): Promise<void>;
|
|
22
|
+
subscribe(topic: string, _filter?: Record<string, any>): Promise<void>;
|
|
23
|
+
unsubscribe(topic: string, _filter?: Record<string, any>): Promise<void>;
|
|
24
|
+
capabilities(): TransportCapabilities;
|
|
25
|
+
onMessage(cb: (topic: string, data: any) => void): void;
|
|
26
|
+
onStateChange(cb: (state: ConnectionState, error?: Error) => void): void;
|
|
27
|
+
clone(): SSETransport;
|
|
28
|
+
private handleGenericMessage;
|
|
29
|
+
private updateState;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export { SSETransport, type SSETransportOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
SSETransport: () => SSETransport
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
var SSETransport = class _SSETransport {
|
|
27
|
+
constructor(url, options = {}) {
|
|
28
|
+
this.url = url;
|
|
29
|
+
this.options = options;
|
|
30
|
+
}
|
|
31
|
+
url;
|
|
32
|
+
options;
|
|
33
|
+
type = "sse";
|
|
34
|
+
eventSource = null;
|
|
35
|
+
_state = "idle";
|
|
36
|
+
messageCb = null;
|
|
37
|
+
stateCb = null;
|
|
38
|
+
activeListeners = /* @__PURE__ */ new Map();
|
|
39
|
+
get state() {
|
|
40
|
+
return this._state;
|
|
41
|
+
}
|
|
42
|
+
async connect() {
|
|
43
|
+
if (this._state === "connected" || this._state === "connecting") {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
this.updateState("connecting");
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
try {
|
|
49
|
+
this.eventSource = new EventSource(this.url, {
|
|
50
|
+
withCredentials: this.options.withCredentials
|
|
51
|
+
});
|
|
52
|
+
} catch (err) {
|
|
53
|
+
this.updateState("error", err);
|
|
54
|
+
reject(err);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
let hasOpened = false;
|
|
58
|
+
this.eventSource.onopen = () => {
|
|
59
|
+
hasOpened = true;
|
|
60
|
+
this.updateState("connected");
|
|
61
|
+
resolve();
|
|
62
|
+
};
|
|
63
|
+
this.eventSource.onerror = (_event) => {
|
|
64
|
+
const error = new Error("SSE EventSource connection error");
|
|
65
|
+
if (!hasOpened) {
|
|
66
|
+
this.updateState("error", error);
|
|
67
|
+
this.disconnect();
|
|
68
|
+
reject(error);
|
|
69
|
+
} else {
|
|
70
|
+
this.updateState("error", error);
|
|
71
|
+
this.disconnect();
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
this.eventSource.onmessage = (event) => {
|
|
75
|
+
this.handleGenericMessage(event.data);
|
|
76
|
+
};
|
|
77
|
+
for (const [topic, listener] of this.activeListeners.entries()) {
|
|
78
|
+
this.eventSource.addEventListener(topic, listener);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
async disconnect() {
|
|
83
|
+
if (this.eventSource) {
|
|
84
|
+
for (const [topic, listener] of this.activeListeners.entries()) {
|
|
85
|
+
this.eventSource.removeEventListener(topic, listener);
|
|
86
|
+
}
|
|
87
|
+
this.eventSource.close();
|
|
88
|
+
this.eventSource = null;
|
|
89
|
+
}
|
|
90
|
+
this.updateState("closed");
|
|
91
|
+
}
|
|
92
|
+
async publish(topic, data) {
|
|
93
|
+
if (this.options.publish) {
|
|
94
|
+
await this.options.publish(topic, data);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (this.options.publishUrl) {
|
|
98
|
+
const response = await fetch(this.options.publishUrl, {
|
|
99
|
+
method: "POST",
|
|
100
|
+
headers: {
|
|
101
|
+
"Content-Type": "application/json"
|
|
102
|
+
},
|
|
103
|
+
body: JSON.stringify({ topic, data })
|
|
104
|
+
});
|
|
105
|
+
if (!response.ok) {
|
|
106
|
+
throw new Error(`SSE publish HTTP request failed with status ${response.status}`);
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
throw new Error(
|
|
111
|
+
"Publishing is not supported by SSE without a configured publishUrl or publish function"
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
async subscribe(topic, _filter) {
|
|
115
|
+
if (this.activeListeners.has(topic)) return;
|
|
116
|
+
const listener = (event) => {
|
|
117
|
+
try {
|
|
118
|
+
const parsed = JSON.parse(event.data);
|
|
119
|
+
this.messageCb?.(topic, parsed);
|
|
120
|
+
} catch (err) {
|
|
121
|
+
this.messageCb?.(topic, event.data);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
this.activeListeners.set(topic, listener);
|
|
125
|
+
if (this.eventSource && this.eventSource.readyState === EventSource.OPEN) {
|
|
126
|
+
this.eventSource.addEventListener(topic, listener);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async unsubscribe(topic, _filter) {
|
|
130
|
+
const listener = this.activeListeners.get(topic);
|
|
131
|
+
if (!listener) return;
|
|
132
|
+
if (this.eventSource) {
|
|
133
|
+
this.eventSource.removeEventListener(topic, listener);
|
|
134
|
+
}
|
|
135
|
+
this.activeListeners.delete(topic);
|
|
136
|
+
}
|
|
137
|
+
capabilities() {
|
|
138
|
+
return {
|
|
139
|
+
publish: !!(this.options.publish || this.options.publishUrl),
|
|
140
|
+
subscribe: true,
|
|
141
|
+
latency: "high"
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
onMessage(cb) {
|
|
145
|
+
this.messageCb = cb;
|
|
146
|
+
}
|
|
147
|
+
onStateChange(cb) {
|
|
148
|
+
this.stateCb = cb;
|
|
149
|
+
}
|
|
150
|
+
clone() {
|
|
151
|
+
return new _SSETransport(this.url, this.options);
|
|
152
|
+
}
|
|
153
|
+
handleGenericMessage(rawData) {
|
|
154
|
+
if (!this.messageCb) return;
|
|
155
|
+
try {
|
|
156
|
+
const parsed = JSON.parse(rawData);
|
|
157
|
+
if (parsed && typeof parsed === "object") {
|
|
158
|
+
const { topic, data } = parsed;
|
|
159
|
+
if (typeof topic === "string") {
|
|
160
|
+
this.messageCb(topic, data !== void 0 ? data : parsed);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
this.messageCb("message", parsed);
|
|
165
|
+
} catch (err) {
|
|
166
|
+
this.messageCb("message", rawData);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
updateState(state, error) {
|
|
170
|
+
if (this._state === state) return;
|
|
171
|
+
this._state = state;
|
|
172
|
+
if (this.stateCb) {
|
|
173
|
+
this.stateCb(state, error);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
178
|
+
0 && (module.exports = {
|
|
179
|
+
SSETransport
|
|
180
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var SSETransport = class _SSETransport {
|
|
3
|
+
constructor(url, options = {}) {
|
|
4
|
+
this.url = url;
|
|
5
|
+
this.options = options;
|
|
6
|
+
}
|
|
7
|
+
url;
|
|
8
|
+
options;
|
|
9
|
+
type = "sse";
|
|
10
|
+
eventSource = null;
|
|
11
|
+
_state = "idle";
|
|
12
|
+
messageCb = null;
|
|
13
|
+
stateCb = null;
|
|
14
|
+
activeListeners = /* @__PURE__ */ new Map();
|
|
15
|
+
get state() {
|
|
16
|
+
return this._state;
|
|
17
|
+
}
|
|
18
|
+
async connect() {
|
|
19
|
+
if (this._state === "connected" || this._state === "connecting") {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
this.updateState("connecting");
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
try {
|
|
25
|
+
this.eventSource = new EventSource(this.url, {
|
|
26
|
+
withCredentials: this.options.withCredentials
|
|
27
|
+
});
|
|
28
|
+
} catch (err) {
|
|
29
|
+
this.updateState("error", err);
|
|
30
|
+
reject(err);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
let hasOpened = false;
|
|
34
|
+
this.eventSource.onopen = () => {
|
|
35
|
+
hasOpened = true;
|
|
36
|
+
this.updateState("connected");
|
|
37
|
+
resolve();
|
|
38
|
+
};
|
|
39
|
+
this.eventSource.onerror = (_event) => {
|
|
40
|
+
const error = new Error("SSE EventSource connection error");
|
|
41
|
+
if (!hasOpened) {
|
|
42
|
+
this.updateState("error", error);
|
|
43
|
+
this.disconnect();
|
|
44
|
+
reject(error);
|
|
45
|
+
} else {
|
|
46
|
+
this.updateState("error", error);
|
|
47
|
+
this.disconnect();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
this.eventSource.onmessage = (event) => {
|
|
51
|
+
this.handleGenericMessage(event.data);
|
|
52
|
+
};
|
|
53
|
+
for (const [topic, listener] of this.activeListeners.entries()) {
|
|
54
|
+
this.eventSource.addEventListener(topic, listener);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
async disconnect() {
|
|
59
|
+
if (this.eventSource) {
|
|
60
|
+
for (const [topic, listener] of this.activeListeners.entries()) {
|
|
61
|
+
this.eventSource.removeEventListener(topic, listener);
|
|
62
|
+
}
|
|
63
|
+
this.eventSource.close();
|
|
64
|
+
this.eventSource = null;
|
|
65
|
+
}
|
|
66
|
+
this.updateState("closed");
|
|
67
|
+
}
|
|
68
|
+
async publish(topic, data) {
|
|
69
|
+
if (this.options.publish) {
|
|
70
|
+
await this.options.publish(topic, data);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (this.options.publishUrl) {
|
|
74
|
+
const response = await fetch(this.options.publishUrl, {
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers: {
|
|
77
|
+
"Content-Type": "application/json"
|
|
78
|
+
},
|
|
79
|
+
body: JSON.stringify({ topic, data })
|
|
80
|
+
});
|
|
81
|
+
if (!response.ok) {
|
|
82
|
+
throw new Error(`SSE publish HTTP request failed with status ${response.status}`);
|
|
83
|
+
}
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
throw new Error(
|
|
87
|
+
"Publishing is not supported by SSE without a configured publishUrl or publish function"
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
async subscribe(topic, _filter) {
|
|
91
|
+
if (this.activeListeners.has(topic)) return;
|
|
92
|
+
const listener = (event) => {
|
|
93
|
+
try {
|
|
94
|
+
const parsed = JSON.parse(event.data);
|
|
95
|
+
this.messageCb?.(topic, parsed);
|
|
96
|
+
} catch (err) {
|
|
97
|
+
this.messageCb?.(topic, event.data);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
this.activeListeners.set(topic, listener);
|
|
101
|
+
if (this.eventSource && this.eventSource.readyState === EventSource.OPEN) {
|
|
102
|
+
this.eventSource.addEventListener(topic, listener);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async unsubscribe(topic, _filter) {
|
|
106
|
+
const listener = this.activeListeners.get(topic);
|
|
107
|
+
if (!listener) return;
|
|
108
|
+
if (this.eventSource) {
|
|
109
|
+
this.eventSource.removeEventListener(topic, listener);
|
|
110
|
+
}
|
|
111
|
+
this.activeListeners.delete(topic);
|
|
112
|
+
}
|
|
113
|
+
capabilities() {
|
|
114
|
+
return {
|
|
115
|
+
publish: !!(this.options.publish || this.options.publishUrl),
|
|
116
|
+
subscribe: true,
|
|
117
|
+
latency: "high"
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
onMessage(cb) {
|
|
121
|
+
this.messageCb = cb;
|
|
122
|
+
}
|
|
123
|
+
onStateChange(cb) {
|
|
124
|
+
this.stateCb = cb;
|
|
125
|
+
}
|
|
126
|
+
clone() {
|
|
127
|
+
return new _SSETransport(this.url, this.options);
|
|
128
|
+
}
|
|
129
|
+
handleGenericMessage(rawData) {
|
|
130
|
+
if (!this.messageCb) return;
|
|
131
|
+
try {
|
|
132
|
+
const parsed = JSON.parse(rawData);
|
|
133
|
+
if (parsed && typeof parsed === "object") {
|
|
134
|
+
const { topic, data } = parsed;
|
|
135
|
+
if (typeof topic === "string") {
|
|
136
|
+
this.messageCb(topic, data !== void 0 ? data : parsed);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
this.messageCb("message", parsed);
|
|
141
|
+
} catch (err) {
|
|
142
|
+
this.messageCb("message", rawData);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
updateState(state, error) {
|
|
146
|
+
if (this._state === state) return;
|
|
147
|
+
this._state = state;
|
|
148
|
+
if (this.stateCb) {
|
|
149
|
+
this.stateCb(state, error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
export {
|
|
154
|
+
SSETransport
|
|
155
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@connexis/transport-sse",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Server-Sent Events (SSE) transport for @connexis",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@connexis/core": "1.0.0"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"typescript": "^5.5.2"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean"
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { Transport, ConnectionState, TransportCapabilities } from '@connexis/core';
|
|
2
|
+
|
|
3
|
+
export interface SSETransportOptions {
|
|
4
|
+
publishUrl?: string;
|
|
5
|
+
publish?: (topic: string, data: any) => Promise<void>;
|
|
6
|
+
withCredentials?: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class SSETransport implements Transport {
|
|
10
|
+
public readonly type = 'sse';
|
|
11
|
+
private eventSource: EventSource | null = null;
|
|
12
|
+
private _state: ConnectionState = 'idle';
|
|
13
|
+
|
|
14
|
+
private messageCb: ((topic: string, data: any) => void) | null = null;
|
|
15
|
+
private stateCb: ((state: ConnectionState, error?: Error) => void) | null = null;
|
|
16
|
+
private activeListeners = new Map<string, (e: MessageEvent) => void>();
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
private url: string,
|
|
20
|
+
private options: SSETransportOptions = {}
|
|
21
|
+
) {}
|
|
22
|
+
|
|
23
|
+
get state(): ConnectionState {
|
|
24
|
+
return this._state;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async connect(): Promise<void> {
|
|
28
|
+
if (this._state === 'connected' || this._state === 'connecting') {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
this.updateState('connecting');
|
|
33
|
+
|
|
34
|
+
return new Promise<void>((resolve, reject) => {
|
|
35
|
+
try {
|
|
36
|
+
this.eventSource = new EventSource(this.url, {
|
|
37
|
+
withCredentials: this.options.withCredentials
|
|
38
|
+
});
|
|
39
|
+
} catch (err) {
|
|
40
|
+
this.updateState('error', err as Error);
|
|
41
|
+
reject(err);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let hasOpened = false;
|
|
46
|
+
|
|
47
|
+
this.eventSource.onopen = () => {
|
|
48
|
+
hasOpened = true;
|
|
49
|
+
this.updateState('connected');
|
|
50
|
+
resolve();
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
this.eventSource.onerror = (_event) => {
|
|
54
|
+
const error = new Error('SSE EventSource connection error');
|
|
55
|
+
if (!hasOpened) {
|
|
56
|
+
this.updateState('error', error);
|
|
57
|
+
this.disconnect();
|
|
58
|
+
reject(error);
|
|
59
|
+
} else {
|
|
60
|
+
// If already connected, transition to error so Connection triggers reconnect
|
|
61
|
+
this.updateState('error', error);
|
|
62
|
+
this.disconnect();
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Listen to generic messages
|
|
67
|
+
this.eventSource.onmessage = (event) => {
|
|
68
|
+
this.handleGenericMessage(event.data);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// Re-register any active topic listeners
|
|
72
|
+
for (const [topic, listener] of this.activeListeners.entries()) {
|
|
73
|
+
this.eventSource.addEventListener(topic, listener as any);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async disconnect(): Promise<void> {
|
|
79
|
+
if (this.eventSource) {
|
|
80
|
+
// Remove all event listeners to avoid leaks
|
|
81
|
+
for (const [topic, listener] of this.activeListeners.entries()) {
|
|
82
|
+
this.eventSource.removeEventListener(topic, listener as any);
|
|
83
|
+
}
|
|
84
|
+
this.eventSource.close();
|
|
85
|
+
this.eventSource = null;
|
|
86
|
+
}
|
|
87
|
+
this.updateState('closed');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async publish(topic: string, data: any): Promise<void> {
|
|
91
|
+
if (this.options.publish) {
|
|
92
|
+
await this.options.publish(topic, data);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (this.options.publishUrl) {
|
|
97
|
+
const response = await fetch(this.options.publishUrl, {
|
|
98
|
+
method: 'POST',
|
|
99
|
+
headers: {
|
|
100
|
+
'Content-Type': 'application/json'
|
|
101
|
+
},
|
|
102
|
+
body: JSON.stringify({ topic, data })
|
|
103
|
+
});
|
|
104
|
+
if (!response.ok) {
|
|
105
|
+
throw new Error(`SSE publish HTTP request failed with status ${response.status}`);
|
|
106
|
+
}
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
throw new Error(
|
|
111
|
+
'Publishing is not supported by SSE without a configured publishUrl or publish function'
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async subscribe(topic: string, _filter?: Record<string, any>): Promise<void> {
|
|
116
|
+
if (this.activeListeners.has(topic)) return;
|
|
117
|
+
|
|
118
|
+
const listener = (event: MessageEvent) => {
|
|
119
|
+
try {
|
|
120
|
+
const parsed = JSON.parse(event.data);
|
|
121
|
+
this.messageCb?.(topic, parsed);
|
|
122
|
+
} catch (err) {
|
|
123
|
+
this.messageCb?.(topic, event.data);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
this.activeListeners.set(topic, listener);
|
|
128
|
+
|
|
129
|
+
if (this.eventSource && this.eventSource.readyState === EventSource.OPEN) {
|
|
130
|
+
this.eventSource.addEventListener(topic, listener as any);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async unsubscribe(topic: string, _filter?: Record<string, any>): Promise<void> {
|
|
135
|
+
const listener = this.activeListeners.get(topic);
|
|
136
|
+
if (!listener) return;
|
|
137
|
+
|
|
138
|
+
if (this.eventSource) {
|
|
139
|
+
this.eventSource.removeEventListener(topic, listener as any);
|
|
140
|
+
}
|
|
141
|
+
this.activeListeners.delete(topic);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
capabilities(): TransportCapabilities {
|
|
145
|
+
return {
|
|
146
|
+
publish: !!(this.options.publish || this.options.publishUrl),
|
|
147
|
+
subscribe: true,
|
|
148
|
+
latency: 'high'
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
onMessage(cb: (topic: string, data: any) => void): void {
|
|
153
|
+
this.messageCb = cb;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
onStateChange(cb: (state: ConnectionState, error?: Error) => void): void {
|
|
157
|
+
this.stateCb = cb;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
clone(): SSETransport {
|
|
161
|
+
return new SSETransport(this.url, this.options);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private handleGenericMessage(rawData: string): void {
|
|
165
|
+
if (!this.messageCb) return;
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
const parsed = JSON.parse(rawData);
|
|
169
|
+
if (parsed && typeof parsed === 'object') {
|
|
170
|
+
const { topic, data } = parsed;
|
|
171
|
+
if (typeof topic === 'string') {
|
|
172
|
+
this.messageCb(topic, data !== undefined ? data : parsed);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
this.messageCb('message', parsed);
|
|
177
|
+
} catch (err) {
|
|
178
|
+
this.messageCb('message', rawData);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private updateState(state: ConnectionState, error?: Error): void {
|
|
183
|
+
if (this._state === state) return;
|
|
184
|
+
this._state = state;
|
|
185
|
+
if (this.stateCb) {
|
|
186
|
+
this.stateCb(state, error);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|