@motiadev/stream-client-browser 0.2.1-beta.55 → 0.2.1-beta.56

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,28 +1,8 @@
1
1
  import { StreamSubscription } from './stream-subscription';
2
- import { GroupJoinMessage, Listener } from './stream.types';
2
+ import { GroupEventMessage, JoinMessage } from './stream.types';
3
3
  export declare class StreamGroupSubscription<TData extends {
4
4
  id: string;
5
- }> extends StreamSubscription {
6
- private readonly ws;
7
- private readonly sub;
8
- private onChangeListeners;
9
- private listeners;
10
- private state;
11
- constructor(ws: WebSocket, sub: GroupJoinMessage);
12
- /**
13
- * Close the subscription.
14
- */
15
- close(): void;
16
- /**
17
- * Add a change listener. This listener will be called whenever the state of the group changes.
18
- */
19
- addChangeListener(listener: Listener<TData[]>): void;
20
- /**
21
- * Remove a change listener.
22
- */
23
- removeChangeListener(listener: Listener<TData[]>): void;
24
- /**
25
- * Get the current state of the group.
26
- */
27
- getState(): TData[];
5
+ }> extends StreamSubscription<TData[], GroupEventMessage<TData>> {
6
+ constructor(sub: JoinMessage);
7
+ listener(message: GroupEventMessage<TData>): void;
28
8
  }
@@ -1,70 +1,32 @@
1
1
  import { StreamSubscription } from './stream-subscription';
2
2
  export class StreamGroupSubscription extends StreamSubscription {
3
- constructor(ws, sub) {
4
- super();
5
- this.ws = ws;
6
- this.sub = sub;
7
- this.onChangeListeners = new Set();
8
- this.listeners = new Set();
9
- this.state = [];
10
- const message = { type: 'join', data: sub };
11
- const listenerWrapper = (event) => {
12
- const message = JSON.parse(event.data);
13
- const isStreamName = message.streamName === this.sub.streamName;
14
- const isGroupId = 'groupId' in message && message.groupId === this.sub.groupId;
15
- if (isStreamName && isGroupId) {
16
- if (message.event.type === 'sync') {
17
- this.state = message.event.data;
18
- }
19
- else if (message.event.type === 'create') {
20
- const id = message.event.data.id;
21
- if (!this.state.find((item) => item.id === id)) {
22
- this.state = [...this.state, message.event.data];
23
- }
24
- }
25
- else if (message.event.type === 'update') {
26
- const messageData = message.event.data;
27
- const messageDataId = messageData.id;
28
- this.state = this.state.map((item) => (item.id === messageDataId ? messageData : item));
29
- }
30
- else if (message.event.type === 'delete') {
31
- const messageDataId = message.event.data.id;
32
- this.state = this.state.filter((item) => item.id !== messageDataId);
33
- }
34
- else if (message.event.type === 'event') {
35
- this.onEventReceived(message.event.event);
36
- }
37
- this.onChangeListeners.forEach((listener) => listener(this.state));
38
- }
39
- };
40
- this.ws.addEventListener('message', listenerWrapper);
41
- this.listeners.add(listenerWrapper);
42
- ws.send(JSON.stringify(message));
43
- }
44
- /**
45
- * Close the subscription.
46
- */
47
- close() {
48
- const message = { type: 'leave', data: this.sub };
49
- this.ws.send(JSON.stringify(message));
50
- this.listeners.forEach((listener) => this.ws.removeEventListener('message', listener));
51
- }
52
- /**
53
- * Add a change listener. This listener will be called whenever the state of the group changes.
54
- */
55
- addChangeListener(listener) {
56
- this.onChangeListeners.add(listener);
3
+ constructor(sub) {
4
+ super(sub, []);
57
5
  }
58
- /**
59
- * Remove a change listener.
60
- */
61
- removeChangeListener(listener) {
62
- this.onChangeListeners.delete(listener);
63
- }
64
- /**
65
- * Get the current state of the group.
66
- */
67
- getState() {
68
- return this.state;
6
+ listener(message) {
7
+ if (message.event.type === 'sync') {
8
+ this.setState(message.event.data);
9
+ }
10
+ else if (message.event.type === 'create') {
11
+ const id = message.event.data.id;
12
+ const state = this.getState();
13
+ if (!state.find((item) => item.id === id)) {
14
+ this.setState([...state, message.event.data]);
15
+ }
16
+ }
17
+ else if (message.event.type === 'update') {
18
+ const messageData = message.event.data;
19
+ const messageDataId = messageData.id;
20
+ const state = this.getState();
21
+ this.setState(state.map((item) => (item.id === messageDataId ? messageData : item)));
22
+ }
23
+ else if (message.event.type === 'delete') {
24
+ const messageDataId = message.event.data.id;
25
+ const state = this.getState();
26
+ this.setState(state.filter((item) => item.id !== messageDataId));
27
+ }
28
+ else if (message.event.type === 'event') {
29
+ this.onEventReceived(message.event.event);
30
+ }
69
31
  }
70
32
  }
@@ -1,28 +1,8 @@
1
1
  import { StreamSubscription } from './stream-subscription';
2
- import { ItemJoinMessage, Listener } from './stream.types';
2
+ import { ItemEventMessage, JoinMessage } from './stream.types';
3
3
  export declare class StreamItemSubscription<TData extends {
4
4
  id: string;
5
- }> extends StreamSubscription {
6
- private readonly ws;
7
- private readonly sub;
8
- private onChangeListeners;
9
- private listeners;
10
- private state;
11
- constructor(ws: WebSocket, sub: ItemJoinMessage);
12
- /**
13
- * Close the subscription.
14
- */
15
- close(): void;
16
- /**
17
- * Add a change listener. This listener will be called whenever the state of the item changes.
18
- */
19
- addChangeListener(listener: Listener<TData>): void;
20
- /**
21
- * Remove a change listener.
22
- */
23
- removeChangeListener(listener: Listener<TData>): void;
24
- /**
25
- * Get the current state of the item.
26
- */
27
- getState(): TData | null;
5
+ }> extends StreamSubscription<TData | null, ItemEventMessage<TData>> {
6
+ constructor(sub: JoinMessage);
7
+ listener(message: ItemEventMessage<TData>): void;
28
8
  }
@@ -1,58 +1,17 @@
1
1
  import { StreamSubscription } from './stream-subscription';
2
2
  export class StreamItemSubscription extends StreamSubscription {
3
- constructor(ws, sub) {
4
- super();
5
- this.ws = ws;
6
- this.sub = sub;
7
- this.onChangeListeners = new Set();
8
- this.listeners = new Set();
9
- this.state = null;
10
- const message = { type: 'join', data: sub };
11
- const listenerWrapper = (event) => {
12
- const message = JSON.parse(event.data);
13
- const isStreamName = message.streamName === this.sub.streamName;
14
- const isId = 'id' in message && message.id === this.sub.id;
15
- if (isStreamName && isId) {
16
- if (message.event.type === 'sync' || message.event.type === 'create' || message.event.type === 'update') {
17
- this.state = message.event.data;
18
- }
19
- else if (message.event.type === 'delete') {
20
- this.state = null;
21
- }
22
- else if (message.event.type === 'event') {
23
- this.onEventReceived(message.event.event);
24
- }
25
- this.onChangeListeners.forEach((listener) => listener(this.state));
26
- }
27
- };
28
- this.ws.addEventListener('message', listenerWrapper);
29
- this.listeners.add(listenerWrapper);
30
- ws.send(JSON.stringify(message));
3
+ constructor(sub) {
4
+ super(sub, null);
31
5
  }
32
- /**
33
- * Close the subscription.
34
- */
35
- close() {
36
- const message = { type: 'leave', data: this.sub };
37
- this.ws.send(JSON.stringify(message));
38
- this.listeners.forEach((listener) => this.ws.removeEventListener('message', listener));
39
- }
40
- /**
41
- * Add a change listener. This listener will be called whenever the state of the item changes.
42
- */
43
- addChangeListener(listener) {
44
- this.onChangeListeners.add(listener);
45
- }
46
- /**
47
- * Remove a change listener.
48
- */
49
- removeChangeListener(listener) {
50
- this.onChangeListeners.delete(listener);
51
- }
52
- /**
53
- * Get the current state of the item.
54
- */
55
- getState() {
56
- return this.state;
6
+ listener(message) {
7
+ if (message.event.type === 'sync' || message.event.type === 'create' || message.event.type === 'update') {
8
+ this.setState(message.event.data);
9
+ }
10
+ else if (message.event.type === 'delete') {
11
+ this.setState(null);
12
+ }
13
+ else if (message.event.type === 'event') {
14
+ this.onEventReceived(message.event.event);
15
+ }
57
16
  }
58
17
  }
@@ -1,7 +1,13 @@
1
- import { CustomEvent } from './stream.types';
1
+ import { CustomEvent, JoinMessage, Listener } from './stream.types';
2
2
  type CustomEventListener = (event: any) => void;
3
- export declare abstract class StreamSubscription {
3
+ export declare abstract class StreamSubscription<TData = unknown, TEventData = unknown> {
4
4
  private customEventListeners;
5
+ private closeListeners;
6
+ private onChangeListeners;
7
+ private state;
8
+ readonly sub: JoinMessage;
9
+ constructor(sub: JoinMessage, state: TData);
10
+ abstract listener(message: TEventData): void;
5
11
  protected onEventReceived(event: CustomEvent): void;
6
12
  /**
7
13
  * Add a custom event listener. This listener will be called whenever the custom event is received.
@@ -11,5 +17,20 @@ export declare abstract class StreamSubscription {
11
17
  * Remove a custom event listener.
12
18
  */
13
19
  offEvent(type: string, listener: CustomEventListener): void;
20
+ onClose(listener: () => void): void;
21
+ close(): void;
22
+ /**
23
+ * Add a change listener. This listener will be called whenever the state of the group changes.
24
+ */
25
+ addChangeListener(listener: Listener<TData>): void;
26
+ /**
27
+ * Remove a change listener.
28
+ */
29
+ removeChangeListener(listener: Listener<TData>): void;
30
+ /**
31
+ * Get the current state of the group.
32
+ */
33
+ getState(): TData;
34
+ protected setState(state: TData): void;
14
35
  }
15
36
  export {};
@@ -1,6 +1,10 @@
1
1
  export class StreamSubscription {
2
- constructor() {
2
+ constructor(sub, state) {
3
3
  this.customEventListeners = new Map();
4
+ this.closeListeners = new Set();
5
+ this.onChangeListeners = new Set();
6
+ this.sub = sub;
7
+ this.state = state;
4
8
  }
5
9
  onEventReceived(event) {
6
10
  const customEventListeners = this.customEventListeners.get(event.type);
@@ -23,4 +27,33 @@ export class StreamSubscription {
23
27
  const listeners = this.customEventListeners.get(type) || [];
24
28
  this.customEventListeners.set(type, listeners.filter((l) => l !== listener));
25
29
  }
30
+ onClose(listener) {
31
+ this.closeListeners.add(listener);
32
+ }
33
+ close() {
34
+ this.closeListeners.forEach((listener) => listener());
35
+ this.closeListeners.clear();
36
+ }
37
+ /**
38
+ * Add a change listener. This listener will be called whenever the state of the group changes.
39
+ */
40
+ addChangeListener(listener) {
41
+ this.onChangeListeners.add(listener);
42
+ }
43
+ /**
44
+ * Remove a change listener.
45
+ */
46
+ removeChangeListener(listener) {
47
+ this.onChangeListeners.delete(listener);
48
+ }
49
+ /**
50
+ * Get the current state of the group.
51
+ */
52
+ getState() {
53
+ return this.state;
54
+ }
55
+ setState(state) {
56
+ this.state = state;
57
+ this.onChangeListeners.forEach((listener) => listener(state));
58
+ }
26
59
  }
@@ -1,17 +1,21 @@
1
1
  import { StreamGroupSubscription } from './stream-group';
2
2
  import { StreamItemSubscription } from './stream-item';
3
3
  export declare class Stream {
4
+ private address;
4
5
  private ws;
5
- constructor(address: string, onReady: () => void);
6
+ private listeners;
7
+ constructor(address: string);
8
+ createSocket(): WebSocket;
6
9
  /**
7
10
  * Subscribe to an item in a stream.
8
11
  *
9
12
  * @argument streamName - The name of the stream to subscribe to.
13
+ * @argument groupId - The id of the group to subscribe to.
10
14
  * @argument id - The id of the item to subscribe to.
11
15
  */
12
16
  subscribeItem<TData extends {
13
17
  id: string;
14
- }>(streamName: string, id: string): StreamItemSubscription<TData>;
18
+ }>(streamName: string, groupId: string, id: string): StreamItemSubscription<TData>;
15
19
  /**
16
20
  * Subscribe to a group in a stream.
17
21
  *
@@ -22,4 +26,11 @@ export declare class Stream {
22
26
  id: string;
23
27
  }>(streamName: string, groupId: string): StreamGroupSubscription<TData>;
24
28
  close(): void;
29
+ private onSocketClose;
30
+ private onSocketOpen;
31
+ messageListener(event: MessageEvent<string>): void;
32
+ private subscribe;
33
+ private join;
34
+ private leave;
35
+ private roomName;
25
36
  }
@@ -2,19 +2,31 @@ import { v4 as uuidv4 } from 'uuid';
2
2
  import { StreamGroupSubscription } from './stream-group';
3
3
  import { StreamItemSubscription } from './stream-item';
4
4
  export class Stream {
5
- constructor(address, onReady) {
6
- this.ws = new WebSocket(address);
7
- this.ws.onopen = () => onReady();
5
+ constructor(address) {
6
+ this.address = address;
7
+ this.listeners = {};
8
+ this.ws = this.createSocket();
9
+ }
10
+ createSocket() {
11
+ this.ws = new WebSocket(this.address);
12
+ this.ws.addEventListener('message', (message) => this.messageListener(message));
13
+ this.ws.addEventListener('open', () => this.onSocketOpen());
14
+ this.ws.addEventListener('close', () => this.onSocketClose());
15
+ return this.ws;
8
16
  }
9
17
  /**
10
18
  * Subscribe to an item in a stream.
11
19
  *
12
20
  * @argument streamName - The name of the stream to subscribe to.
21
+ * @argument groupId - The id of the group to subscribe to.
13
22
  * @argument id - The id of the item to subscribe to.
14
23
  */
15
- subscribeItem(streamName, id) {
24
+ subscribeItem(streamName, groupId, id) {
16
25
  const subscriptionId = uuidv4();
17
- return new StreamItemSubscription(this.ws, { streamName, id, subscriptionId });
26
+ const sub = { streamName, groupId, id, subscriptionId };
27
+ const subscription = new StreamItemSubscription(sub);
28
+ this.subscribe(subscription);
29
+ return subscription;
18
30
  }
19
31
  /**
20
32
  * Subscribe to a group in a stream.
@@ -24,9 +36,58 @@ export class Stream {
24
36
  */
25
37
  subscribeGroup(streamName, groupId) {
26
38
  const subscriptionId = uuidv4();
27
- return new StreamGroupSubscription(this.ws, { streamName, groupId, subscriptionId });
39
+ const sub = { streamName, groupId, subscriptionId };
40
+ const subscription = new StreamGroupSubscription(sub);
41
+ this.subscribe(subscription);
42
+ return subscription;
28
43
  }
29
44
  close() {
45
+ this.listeners = {}; // clean up all listeners
46
+ this.ws.removeEventListener('message', this.messageListener);
47
+ this.ws.removeEventListener('open', this.onSocketOpen);
48
+ this.ws.removeEventListener('close', this.onSocketClose);
30
49
  this.ws.close();
31
50
  }
51
+ onSocketClose() {
52
+ // retry to connect
53
+ setTimeout(() => this.createSocket(), 2000);
54
+ }
55
+ onSocketOpen() {
56
+ Object.values(this.listeners).forEach((listeners) => {
57
+ listeners.forEach((subscription) => this.join(subscription));
58
+ });
59
+ }
60
+ messageListener(event) {
61
+ const message = JSON.parse(event.data);
62
+ const room = this.roomName(message);
63
+ this.listeners[room]?.forEach((listener) => listener.listener(message));
64
+ }
65
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
66
+ subscribe(subscription) {
67
+ const room = this.roomName(subscription.sub);
68
+ if (!this.listeners[room]) {
69
+ this.listeners[room] = new Set();
70
+ }
71
+ this.listeners[room].add(subscription);
72
+ this.join(subscription);
73
+ subscription.onClose(() => {
74
+ this.listeners[room].delete(subscription);
75
+ this.leave(subscription);
76
+ });
77
+ }
78
+ join(subscription) {
79
+ if (this.ws.readyState === WebSocket.OPEN) {
80
+ this.ws.send(JSON.stringify({ type: 'join', data: subscription.sub }));
81
+ }
82
+ }
83
+ leave(subscription) {
84
+ if (this.ws.readyState === WebSocket.OPEN) {
85
+ this.ws.send(JSON.stringify({ type: 'leave', data: subscription.sub }));
86
+ }
87
+ }
88
+ roomName(message) {
89
+ return message.id
90
+ ? `${message.streamName}:group:${message.groupId}:item:${message.id}`
91
+ : `${message.streamName}:group:${message.groupId}`;
92
+ }
32
93
  }
@@ -1,19 +1,9 @@
1
1
  export type BaseMessage = {
2
2
  streamName: string;
3
- } & ({
4
- id: string;
5
- } | {
6
3
  groupId: string;
7
- });
8
- export type JoinMessage = BaseMessage & {
9
- subscriptionId: string;
4
+ id?: string;
10
5
  };
11
- export type ItemJoinMessage = BaseMessage & {
12
- id: string;
13
- subscriptionId: string;
14
- };
15
- export type GroupJoinMessage = BaseMessage & {
16
- groupId: string;
6
+ export type JoinMessage = BaseMessage & {
17
7
  subscriptionId: string;
18
8
  };
19
9
  export type CustomEvent = {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@motiadev/stream-client-browser",
3
3
  "description": "Motia Stream Client Package – Responsible for managing streams of data.",
4
- "version": "0.2.1-beta.55",
4
+ "version": "0.2.1-beta.56",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -1,80 +1,37 @@
1
1
  import { StreamSubscription } from './stream-subscription'
2
- import { GroupEventMessage, GroupJoinMessage, Listener, Message } from './stream.types'
3
-
4
- export class StreamGroupSubscription<TData extends { id: string }> extends StreamSubscription {
5
- private onChangeListeners: Set<Listener<TData[]>> = new Set()
6
- private listeners: Set<EventListener> = new Set()
7
-
8
- private state: TData[] = []
9
-
10
- constructor(
11
- private readonly ws: WebSocket,
12
- private readonly sub: GroupJoinMessage,
13
- ) {
14
- super()
15
-
16
- const message: Message = { type: 'join', data: sub }
17
- const listenerWrapper = (event: MessageEvent<string>) => {
18
- const message: GroupEventMessage<TData> = JSON.parse(event.data)
19
- const isStreamName = message.streamName === this.sub.streamName
20
- const isGroupId = 'groupId' in message && message.groupId === this.sub.groupId
21
-
22
- if (isStreamName && isGroupId) {
23
- if (message.event.type === 'sync') {
24
- this.state = message.event.data
25
- } else if (message.event.type === 'create') {
26
- const id = message.event.data.id
2
+ import { GroupEventMessage, JoinMessage } from './stream.types'
3
+
4
+ export class StreamGroupSubscription<TData extends { id: string }> extends StreamSubscription<
5
+ TData[],
6
+ GroupEventMessage<TData>
7
+ > {
8
+ constructor(sub: JoinMessage) {
9
+ super(sub, [])
10
+ }
27
11
 
28
- if (!this.state.find((item) => item.id === id)) {
29
- this.state = [...this.state, message.event.data]
30
- }
31
- } else if (message.event.type === 'update') {
32
- const messageData = message.event.data
33
- const messageDataId = messageData.id
34
- this.state = this.state.map((item) => (item.id === messageDataId ? messageData : item))
35
- } else if (message.event.type === 'delete') {
36
- const messageDataId = message.event.data.id
37
- this.state = this.state.filter((item) => item.id !== messageDataId)
38
- } else if (message.event.type === 'event') {
39
- this.onEventReceived(message.event.event)
40
- }
12
+ listener(message: GroupEventMessage<TData>): void {
13
+ if (message.event.type === 'sync') {
14
+ this.setState(message.event.data)
15
+ } else if (message.event.type === 'create') {
16
+ const id = message.event.data.id
17
+ const state = this.getState()
41
18
 
42
- this.onChangeListeners.forEach((listener) => listener(this.state))
19
+ if (!state.find((item) => item.id === id)) {
20
+ this.setState([...state, message.event.data])
43
21
  }
22
+ } else if (message.event.type === 'update') {
23
+ const messageData = message.event.data
24
+ const messageDataId = messageData.id
25
+ const state = this.getState()
26
+
27
+ this.setState(state.map((item) => (item.id === messageDataId ? messageData : item)))
28
+ } else if (message.event.type === 'delete') {
29
+ const messageDataId = message.event.data.id
30
+ const state = this.getState()
31
+
32
+ this.setState(state.filter((item) => item.id !== messageDataId))
33
+ } else if (message.event.type === 'event') {
34
+ this.onEventReceived(message.event.event)
44
35
  }
45
- this.ws.addEventListener('message', listenerWrapper as EventListener)
46
- this.listeners.add(listenerWrapper as EventListener)
47
-
48
- ws.send(JSON.stringify(message))
49
- }
50
-
51
- /**
52
- * Close the subscription.
53
- */
54
- close() {
55
- const message: Message = { type: 'leave', data: this.sub }
56
- this.ws.send(JSON.stringify(message))
57
- this.listeners.forEach((listener) => this.ws.removeEventListener('message', listener))
58
- }
59
-
60
- /**
61
- * Add a change listener. This listener will be called whenever the state of the group changes.
62
- */
63
- addChangeListener(listener: Listener<TData[]>) {
64
- this.onChangeListeners.add(listener)
65
- }
66
-
67
- /**
68
- * Remove a change listener.
69
- */
70
- removeChangeListener(listener: Listener<TData[]>) {
71
- this.onChangeListeners.delete(listener)
72
- }
73
-
74
- /**
75
- * Get the current state of the group.
76
- */
77
- getState(): TData[] {
78
- return this.state
79
36
  }
80
37
  }
@@ -1,68 +1,21 @@
1
1
  import { StreamSubscription } from './stream-subscription'
2
- import { ItemEventMessage, ItemJoinMessage, Listener, Message } from './stream.types'
3
-
4
- export class StreamItemSubscription<TData extends { id: string }> extends StreamSubscription {
5
- private onChangeListeners: Set<Listener<TData>> = new Set()
6
- private listeners: Set<EventListener> = new Set()
7
- private state: TData | null = null
8
-
9
- constructor(
10
- private readonly ws: WebSocket,
11
- private readonly sub: ItemJoinMessage,
12
- ) {
13
- super()
14
-
15
- const message: Message = { type: 'join', data: sub }
16
- const listenerWrapper = (event: MessageEvent<string>) => {
17
- const message: ItemEventMessage<TData> = JSON.parse(event.data)
18
- const isStreamName = message.streamName === this.sub.streamName
19
- const isId = 'id' in message && message.id === this.sub.id
20
-
21
- if (isStreamName && isId) {
22
- if (message.event.type === 'sync' || message.event.type === 'create' || message.event.type === 'update') {
23
- this.state = message.event.data
24
- } else if (message.event.type === 'delete') {
25
- this.state = null
26
- } else if (message.event.type === 'event') {
27
- this.onEventReceived(message.event.event)
28
- }
29
-
30
- this.onChangeListeners.forEach((listener) => listener(this.state))
31
- }
32
- }
33
- this.ws.addEventListener('message', listenerWrapper as EventListener)
34
- this.listeners.add(listenerWrapper as EventListener)
35
-
36
- ws.send(JSON.stringify(message))
2
+ import { ItemEventMessage, JoinMessage } from './stream.types'
3
+
4
+ export class StreamItemSubscription<TData extends { id: string }> extends StreamSubscription<
5
+ TData | null,
6
+ ItemEventMessage<TData>
7
+ > {
8
+ constructor(sub: JoinMessage) {
9
+ super(sub, null)
37
10
  }
38
11
 
39
- /**
40
- * Close the subscription.
41
- */
42
- close() {
43
- const message: Message = { type: 'leave', data: this.sub }
44
- this.ws.send(JSON.stringify(message))
45
- this.listeners.forEach((listener) => this.ws.removeEventListener('message', listener))
46
- }
47
-
48
- /**
49
- * Add a change listener. This listener will be called whenever the state of the item changes.
50
- */
51
- addChangeListener(listener: Listener<TData>) {
52
- this.onChangeListeners.add(listener)
53
- }
54
-
55
- /**
56
- * Remove a change listener.
57
- */
58
- removeChangeListener(listener: Listener<TData>) {
59
- this.onChangeListeners.delete(listener)
60
- }
61
-
62
- /**
63
- * Get the current state of the item.
64
- */
65
- getState(): TData | null {
66
- return this.state
12
+ listener(message: ItemEventMessage<TData>): void {
13
+ if (message.event.type === 'sync' || message.event.type === 'create' || message.event.type === 'update') {
14
+ this.setState(message.event.data)
15
+ } else if (message.event.type === 'delete') {
16
+ this.setState(null)
17
+ } else if (message.event.type === 'event') {
18
+ this.onEventReceived(message.event.event)
19
+ }
67
20
  }
68
21
  }
@@ -1,10 +1,23 @@
1
- import { CustomEvent } from './stream.types'
1
+ import { CustomEvent, JoinMessage, Listener } from './stream.types'
2
2
 
3
3
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4
4
  type CustomEventListener = (event: any) => void
5
5
 
6
- export abstract class StreamSubscription {
6
+ export abstract class StreamSubscription<TData = unknown, TEventData = unknown> {
7
7
  private customEventListeners: Map<string, CustomEventListener[]> = new Map()
8
+ private closeListeners: Set<() => void> = new Set()
9
+
10
+ private onChangeListeners: Set<Listener<TData>> = new Set()
11
+ private state: TData
12
+
13
+ readonly sub: JoinMessage
14
+
15
+ constructor(sub: JoinMessage, state: TData) {
16
+ this.sub = sub
17
+ this.state = state
18
+ }
19
+
20
+ abstract listener(message: TEventData): void
8
21
 
9
22
  protected onEventReceived(event: CustomEvent) {
10
23
  const customEventListeners = this.customEventListeners.get(event.type)
@@ -33,4 +46,39 @@ export abstract class StreamSubscription {
33
46
  listeners.filter((l) => l !== listener),
34
47
  )
35
48
  }
49
+
50
+ onClose(listener: () => void) {
51
+ this.closeListeners.add(listener)
52
+ }
53
+
54
+ close() {
55
+ this.closeListeners.forEach((listener) => listener())
56
+ this.closeListeners.clear()
57
+ }
58
+
59
+ /**
60
+ * Add a change listener. This listener will be called whenever the state of the group changes.
61
+ */
62
+ addChangeListener(listener: Listener<TData>) {
63
+ this.onChangeListeners.add(listener)
64
+ }
65
+
66
+ /**
67
+ * Remove a change listener.
68
+ */
69
+ removeChangeListener(listener: Listener<TData>) {
70
+ this.onChangeListeners.delete(listener)
71
+ }
72
+
73
+ /**
74
+ * Get the current state of the group.
75
+ */
76
+ getState(): TData {
77
+ return this.state
78
+ }
79
+
80
+ protected setState(state: TData) {
81
+ this.state = state
82
+ this.onChangeListeners.forEach((listener) => listener(state))
83
+ }
36
84
  }
package/src/stream.ts CHANGED
@@ -1,24 +1,45 @@
1
1
  import { v4 as uuidv4 } from 'uuid'
2
2
  import { StreamGroupSubscription } from './stream-group'
3
3
  import { StreamItemSubscription } from './stream-item'
4
+ import { StreamSubscription } from './stream-subscription'
5
+ import { BaseMessage } from './stream.types'
4
6
 
5
7
  export class Stream {
6
8
  private ws: WebSocket
9
+ private listeners: { [channelId: string]: Set<StreamSubscription> } = {}
7
10
 
8
- constructor(address: string, onReady: () => void) {
9
- this.ws = new WebSocket(address)
10
- this.ws.onopen = () => onReady()
11
+ constructor(private address: string) {
12
+ this.ws = this.createSocket()
13
+ }
14
+
15
+ createSocket(): WebSocket {
16
+ this.ws = new WebSocket(this.address)
17
+ this.ws.addEventListener('message', (message) => this.messageListener(message))
18
+ this.ws.addEventListener('open', () => this.onSocketOpen())
19
+ this.ws.addEventListener('close', () => this.onSocketClose())
20
+
21
+ return this.ws
11
22
  }
12
23
 
13
24
  /**
14
25
  * Subscribe to an item in a stream.
15
26
  *
16
27
  * @argument streamName - The name of the stream to subscribe to.
28
+ * @argument groupId - The id of the group to subscribe to.
17
29
  * @argument id - The id of the item to subscribe to.
18
30
  */
19
- subscribeItem<TData extends { id: string }>(streamName: string, id: string): StreamItemSubscription<TData> {
31
+ subscribeItem<TData extends { id: string }>(
32
+ streamName: string,
33
+ groupId: string,
34
+ id: string,
35
+ ): StreamItemSubscription<TData> {
20
36
  const subscriptionId = uuidv4()
21
- return new StreamItemSubscription<TData>(this.ws, { streamName, id, subscriptionId })
37
+ const sub = { streamName, groupId, id, subscriptionId }
38
+ const subscription = new StreamItemSubscription<TData>(sub)
39
+
40
+ this.subscribe(subscription)
41
+
42
+ return subscription
22
43
  }
23
44
 
24
45
  /**
@@ -29,10 +50,72 @@ export class Stream {
29
50
  */
30
51
  subscribeGroup<TData extends { id: string }>(streamName: string, groupId: string): StreamGroupSubscription<TData> {
31
52
  const subscriptionId = uuidv4()
32
- return new StreamGroupSubscription<TData>(this.ws, { streamName, groupId, subscriptionId })
53
+ const sub = { streamName, groupId, subscriptionId }
54
+ const subscription = new StreamGroupSubscription<TData>(sub)
55
+
56
+ this.subscribe(subscription)
57
+
58
+ return subscription
33
59
  }
34
60
 
35
61
  close() {
62
+ this.listeners = {} // clean up all listeners
63
+ this.ws.removeEventListener('message', this.messageListener)
64
+ this.ws.removeEventListener('open', this.onSocketOpen)
65
+ this.ws.removeEventListener('close', this.onSocketClose)
36
66
  this.ws.close()
37
67
  }
68
+
69
+ private onSocketClose(): void {
70
+ // retry to connect
71
+ setTimeout(() => this.createSocket(), 2000)
72
+ }
73
+
74
+ private onSocketOpen(): void {
75
+ Object.values(this.listeners).forEach((listeners) => {
76
+ listeners.forEach((subscription) => this.join(subscription))
77
+ })
78
+ }
79
+
80
+ messageListener(event: MessageEvent<string>): void {
81
+ const message: BaseMessage = JSON.parse(event.data)
82
+ const room = this.roomName(message)
83
+
84
+ this.listeners[room]?.forEach((listener) => listener.listener(message as unknown))
85
+ }
86
+
87
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
+ private subscribe(subscription: StreamSubscription<any, any>): void {
89
+ const room = this.roomName(subscription.sub)
90
+
91
+ if (!this.listeners[room]) {
92
+ this.listeners[room] = new Set()
93
+ }
94
+
95
+ this.listeners[room].add(subscription)
96
+ this.join(subscription)
97
+
98
+ subscription.onClose(() => {
99
+ this.listeners[room].delete(subscription)
100
+ this.leave(subscription)
101
+ })
102
+ }
103
+
104
+ private join(subscription: StreamSubscription): void {
105
+ if (this.ws.readyState === WebSocket.OPEN) {
106
+ this.ws.send(JSON.stringify({ type: 'join', data: subscription.sub }))
107
+ }
108
+ }
109
+
110
+ private leave(subscription: StreamSubscription): void {
111
+ if (this.ws.readyState === WebSocket.OPEN) {
112
+ this.ws.send(JSON.stringify({ type: 'leave', data: subscription.sub }))
113
+ }
114
+ }
115
+
116
+ private roomName(message: BaseMessage): string {
117
+ return message.id
118
+ ? `${message.streamName}:group:${message.groupId}:item:${message.id}`
119
+ : `${message.streamName}:group:${message.groupId}`
120
+ }
38
121
  }
@@ -1,7 +1,5 @@
1
- export type BaseMessage = { streamName: string } & ({ id: string } | { groupId: string })
1
+ export type BaseMessage = { streamName: string; groupId: string; id?: string }
2
2
  export type JoinMessage = BaseMessage & { subscriptionId: string }
3
- export type ItemJoinMessage = BaseMessage & { id: string; subscriptionId: string }
4
- export type GroupJoinMessage = BaseMessage & { groupId: string; subscriptionId: string }
5
3
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
4
  export type CustomEvent = { type: string; data: any }
7
5
  export type StreamEvent<TData extends { id: string }> =