@motiadev/stream-client 0.5.2-beta.104-330172

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Motia
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/README.md ADDED
@@ -0,0 +1,185 @@
1
+ # @motiadev/stream-client
2
+
3
+ Motia Stream Client Package – Responsible for managing real-time [Motia](https://motia.dev) streams of data in browser environments. This package provides a simple, type-safe interface for subscribing to item and group streams over WebSockets, handling live updates, and managing stream state in your web applications.
4
+
5
+ ## Features
6
+
7
+ - **WebSocket-based streaming** for real-time data updates
8
+ - **Item and group subscriptions** with automatic state management
9
+ - **Change listeners** for reactive UI updates
10
+ - **Custom event handling** for extensibility
11
+ - **TypeScript support** for strong typing and autocompletion
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @motiadev/stream-client
19
+ ```
20
+
21
+ ---
22
+
23
+ ## Usage
24
+
25
+ ### 1. Creating a Stream Connection
26
+
27
+ ```typescript
28
+ import { Stream } from '@motiadev/stream-client-browser'
29
+
30
+ const stream = new Stream('wss://your-stream-server', () => {
31
+ console.log('WebSocket connection established!')
32
+ })
33
+ ```
34
+
35
+ ### 2. Subscribing to an Item Stream
36
+
37
+ ```typescript
38
+ const itemSubscription = stream.subscribeItem<{ id: string; name: string }>('users', 'user-123')
39
+
40
+ itemSubscription.addChangeListener((user) => {
41
+ console.log('User updated:', user)
42
+ })
43
+
44
+ // Listen for custom events
45
+ itemSubscription.onEvent('custom-event', (data) => {
46
+ console.log('Received custom event:', data)
47
+ })
48
+ ```
49
+
50
+ ### 3. Subscribing to a Group Stream
51
+
52
+ ```typescript
53
+ const groupSubscription = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-abc')
54
+
55
+ groupSubscription.addChangeListener((users) => {
56
+ console.log('Group users updated:', users)
57
+ })
58
+ ```
59
+
60
+ ### 4. Cleaning Up
61
+
62
+ ```typescript
63
+ itemSubscription.close()
64
+ groupSubscription.close()
65
+ stream.close()
66
+ ```
67
+
68
+ ---
69
+
70
+ ## API Reference
71
+
72
+ ### `Stream`
73
+
74
+ - **constructor(address: string, onReady: () => void)**
75
+
76
+ - Establishes a WebSocket connection to the given address.
77
+ - Calls `onReady` when the connection is open.
78
+
79
+ - **subscribeItem<T>(streamName: string, id: string): StreamItemSubscription<T>**
80
+
81
+ - Subscribes to a single item in a stream.
82
+ - Returns a `StreamItemSubscription` instance.
83
+
84
+ - **subscribeGroup<T>(streamName: string, groupId: string): StreamGroupSubscription<T>**
85
+
86
+ - Subscribes to a group of items in a stream.
87
+ - Returns a `StreamGroupSubscription` instance.
88
+
89
+ - **close()**
90
+ - Closes the WebSocket connection.
91
+
92
+ ---
93
+
94
+ ### `StreamItemSubscription<T>`
95
+
96
+ - **addChangeListener(listener: (item: T | null) => void)**
97
+
98
+ - Registers a callback for when the item changes.
99
+
100
+ - **removeChangeListener(listener)**
101
+
102
+ - Unregisters a change listener.
103
+
104
+ - **onEvent(type: string, listener: (event: any) => void)**
105
+
106
+ - Registers a custom event listener.
107
+
108
+ - **offEvent(type: string, listener)**
109
+
110
+ - Unregisters a custom event listener.
111
+
112
+ - **getState(): T | null**
113
+
114
+ - Returns the current state of the item.
115
+
116
+ - **close()**
117
+ - Unsubscribes from the item stream and cleans up listeners.
118
+
119
+ ---
120
+
121
+ ### `StreamGroupSubscription<T>`
122
+
123
+ - **addChangeListener(listener: (items: T[]) => void)**
124
+
125
+ - Registers a callback for when the group changes.
126
+
127
+ - **removeChangeListener(listener)**
128
+
129
+ - Unregisters a change listener.
130
+
131
+ - **onEvent(type: string, listener: (event: any) => void)**
132
+
133
+ - Registers a custom event listener.
134
+
135
+ - **offEvent(type: string, listener: (event: any) => void)**
136
+
137
+ - Unregisters a custom event listener.
138
+
139
+ - **getState(): T[]**
140
+
141
+ - Returns the current state of the group.
142
+
143
+ - **close()**
144
+ - Unsubscribes from the group stream and cleans up listeners.
145
+
146
+ ---
147
+
148
+ ### `StreamSubscription` (Base Class)
149
+
150
+ - **onEvent(type: string, listener: (event: any) => void)**
151
+ - **offEvent(type: string, listener: (event: any) => void)**
152
+
153
+ ---
154
+
155
+ ## Types
156
+
157
+ All types are exported from `stream.types.ts` for advanced usage and type safety.
158
+
159
+ ---
160
+
161
+ ## Example
162
+
163
+ ```typescript
164
+ import { Stream } from '@motiadev/stream-client-browser'
165
+
166
+ const stream = new Stream('wss://example.com', () => {
167
+ const userSub = stream.subscribeItem<{ id: string; name: string }>('users', 'user-1')
168
+
169
+ userSub.addChangeListener((user) => {
170
+ // React to user changes
171
+ })
172
+
173
+ const groupSub = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-1')
174
+
175
+ groupSub.addChangeListener((users) => {
176
+ // React to group changes
177
+ })
178
+ })
179
+ ```
180
+
181
+ ---
182
+
183
+ ## License
184
+
185
+ MIT
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,105 @@
1
+ import { StreamGroupSubscription } from '../src/stream-group';
2
+ describe('StreamGroupSubscription', () => {
3
+ const joinMessage = {
4
+ streamName: 'test-stream',
5
+ groupId: 'test-group',
6
+ subscriptionId: 'sub-1',
7
+ };
8
+ function makeMessage(type, data, timestamp = Date.now()) {
9
+ return {
10
+ streamName: 'test-stream',
11
+ groupId: 'test-group',
12
+ timestamp,
13
+ event: { type, ...(type === 'event' ? { event: data } : { data }) },
14
+ };
15
+ }
16
+ it('notifies change listeners on state change', () => {
17
+ const sub = new StreamGroupSubscription(joinMessage);
18
+ const listener = jest.fn();
19
+ sub.addChangeListener(listener);
20
+ const syncData = [
21
+ { id: '1', name: 'A' },
22
+ { id: '2', name: 'B' },
23
+ ];
24
+ sub.listener(makeMessage('sync', syncData));
25
+ expect(listener).toHaveBeenCalledWith(syncData);
26
+ });
27
+ it('should be able to sort by a key', () => {
28
+ const sub = new StreamGroupSubscription(joinMessage, 'name');
29
+ const listener = jest.fn();
30
+ sub.addChangeListener(listener);
31
+ const syncData = [
32
+ { id: '1', name: 'B' },
33
+ { id: '2', name: 'A' },
34
+ ];
35
+ sub.listener(makeMessage('sync', syncData));
36
+ expect(listener).toHaveBeenCalledWith(syncData);
37
+ expect(sub.getState()).toEqual([
38
+ { id: '2', name: 'A' },
39
+ { id: '1', name: 'B' },
40
+ ]);
41
+ });
42
+ it('should discard old events', () => {
43
+ const sub = new StreamGroupSubscription(joinMessage);
44
+ const listener = jest.fn();
45
+ sub.addChangeListener(listener);
46
+ const syncData = [
47
+ { id: '1', name: 'A' },
48
+ { id: '2', name: 'B' },
49
+ ];
50
+ sub.listener(makeMessage('sync', syncData));
51
+ const oldSyncData = [
52
+ { id: '3', name: 'C' },
53
+ { id: '4', name: 'D' },
54
+ ];
55
+ sub.listener(makeMessage('sync', oldSyncData, Date.now() - 1000));
56
+ expect(sub.getState()).toEqual(syncData);
57
+ });
58
+ it('should add items', () => {
59
+ const sub = new StreamGroupSubscription(joinMessage);
60
+ const syncData = [
61
+ { id: '1', name: 'A' },
62
+ { id: '2', name: 'B' },
63
+ ];
64
+ sub.listener(makeMessage('sync', syncData));
65
+ sub.listener(makeMessage('create', { id: '3', name: 'C' }));
66
+ expect(sub.getState()).toEqual([...syncData, { id: '3', name: 'C' }]);
67
+ });
68
+ it('should update items', () => {
69
+ const sub = new StreamGroupSubscription(joinMessage);
70
+ const syncData = [
71
+ { id: '1', name: 'A' },
72
+ { id: '2', name: 'B' },
73
+ ];
74
+ sub.listener(makeMessage('sync', syncData));
75
+ sub.listener(makeMessage('update', { id: '1', name: 'A1' }));
76
+ expect(sub.getState()).toEqual([
77
+ { id: '1', name: 'A1' },
78
+ { id: '2', name: 'B' },
79
+ ]);
80
+ });
81
+ it('should remove items', () => {
82
+ const sub = new StreamGroupSubscription(joinMessage);
83
+ const syncData = [
84
+ { id: '1', name: 'A' },
85
+ { id: '2', name: 'B' },
86
+ ];
87
+ sub.listener(makeMessage('sync', syncData));
88
+ sub.listener(makeMessage('delete', { id: '1' }));
89
+ expect(sub.getState()).toEqual([{ id: '2', name: 'B' }]);
90
+ });
91
+ it('should discard old on event on a particular item', () => {
92
+ const sub = new StreamGroupSubscription(joinMessage);
93
+ const syncData = [
94
+ { id: '1', name: 'A' },
95
+ { id: '2', name: 'B' },
96
+ ];
97
+ sub.listener(makeMessage('sync', syncData));
98
+ sub.listener(makeMessage('update', { id: '1', name: 'A1' }));
99
+ sub.listener(makeMessage('update', { id: '1', name: 'A2' }, Date.now() - 1000));
100
+ expect(sub.getState()).toEqual([
101
+ { id: '1', name: 'A1' },
102
+ { id: '2', name: 'B' },
103
+ ]);
104
+ });
105
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,46 @@
1
+ import { StreamItemSubscription } from '../src/stream-item';
2
+ describe('StreamItemSubscription', () => {
3
+ const joinMessage = {
4
+ streamName: 'test-stream',
5
+ groupId: 'test-group',
6
+ subscriptionId: 'sub-1',
7
+ };
8
+ function makeMessage(type, data, timestamp = Date.now()) {
9
+ return {
10
+ streamName: 'test-stream',
11
+ groupId: 'test-group',
12
+ timestamp,
13
+ event: { type, ...(type === 'event' ? { event: data } : { data }) },
14
+ };
15
+ }
16
+ it('notifies change listeners on state change', () => {
17
+ const sub = new StreamItemSubscription(joinMessage);
18
+ const listener = jest.fn();
19
+ sub.addChangeListener(listener);
20
+ const syncData = { id: '1', name: 'A', value: 1 };
21
+ sub.listener(makeMessage('sync', syncData));
22
+ expect(listener).toHaveBeenCalledWith(syncData);
23
+ });
24
+ it('should discard old events', () => {
25
+ const sub = new StreamItemSubscription(joinMessage);
26
+ const syncData = { id: '1', name: 'A', value: 1 };
27
+ const oldSyncData = { id: '1', name: 'B', value: 3 };
28
+ sub.listener(makeMessage('sync', syncData));
29
+ sub.listener(makeMessage('sync', oldSyncData, Date.now() - 1000));
30
+ expect(sub.getState()).toEqual(syncData);
31
+ });
32
+ it('should update item', () => {
33
+ const sub = new StreamItemSubscription(joinMessage);
34
+ const syncData = { id: '1', name: 'A', value: 1 };
35
+ sub.listener(makeMessage('sync', syncData));
36
+ sub.listener(makeMessage('update', { id: '1', name: 'A1', value: 2 }, Date.now() + 1000));
37
+ expect(sub.getState()).toEqual({ id: '1', name: 'A1', value: 2 });
38
+ });
39
+ it('should remove item', () => {
40
+ const sub = new StreamItemSubscription(joinMessage);
41
+ const syncData = { id: '1', name: 'A', value: 1 };
42
+ sub.listener(makeMessage('sync', syncData));
43
+ sub.listener(makeMessage('delete', { id: '1' }, Date.now() + 1000));
44
+ expect(sub.getState()).toEqual(null);
45
+ });
46
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,81 @@
1
+ import { Stream } from '../src/stream';
2
+ class MockSocket {
3
+ constructor() {
4
+ this.listeners = {};
5
+ }
6
+ addEventListener(event, cb) {
7
+ if (!this.listeners[event])
8
+ this.listeners[event] = [];
9
+ this.listeners[event].push(cb);
10
+ }
11
+ connect() { }
12
+ isOpen() {
13
+ return true;
14
+ }
15
+ onMessage(callback) {
16
+ this.addEventListener('message', callback);
17
+ }
18
+ onOpen(callback) {
19
+ this.addEventListener('open', callback);
20
+ }
21
+ onClose(callback) {
22
+ this.addEventListener('close', callback);
23
+ }
24
+ send(data) {
25
+ this.listeners['message']?.forEach((cb) => cb(data));
26
+ }
27
+ close() {
28
+ this.listeners = {};
29
+ }
30
+ }
31
+ function getSocket(stream) {
32
+ return stream.ws;
33
+ }
34
+ function makeGroupMessage(type, data, timestamp = Date.now()) {
35
+ return {
36
+ streamName: 'test-stream',
37
+ groupId: 'test-group',
38
+ timestamp,
39
+ event: { type, ...(type === 'event' ? { event: data } : { data }) },
40
+ };
41
+ }
42
+ function makeItemMessage(type, data, timestamp = Date.now()) {
43
+ return {
44
+ streamName: 'test-stream',
45
+ groupId: 'test-group',
46
+ id: '1',
47
+ timestamp,
48
+ event: { type, ...(type === 'event' ? { event: data } : { data }) },
49
+ };
50
+ }
51
+ describe('Stream', () => {
52
+ beforeEach(() => {
53
+ global.WebSocket = MockSocket;
54
+ });
55
+ afterEach(() => {
56
+ delete global.WebSocket;
57
+ });
58
+ it('should sync group events', () => {
59
+ const stream = new Stream(() => new MockSocket());
60
+ const socket = getSocket(stream);
61
+ const sub = stream.subscribeGroup('test-stream', 'test-group');
62
+ const syncData = [
63
+ { id: '1', name: 'A' },
64
+ { id: '2', name: 'B' },
65
+ ];
66
+ socket.send(JSON.stringify(makeGroupMessage('sync', syncData)));
67
+ expect(sub.getState()).toEqual(syncData);
68
+ });
69
+ it('should not sync item events in group subscriptions', () => {
70
+ const stream = new Stream(() => new MockSocket());
71
+ const socket = getSocket(stream);
72
+ const sub = stream.subscribeGroup('test-stream', 'test-group');
73
+ const syncData = [
74
+ { id: '1', name: 'A' },
75
+ { id: '2', name: 'B' },
76
+ ];
77
+ socket.send(JSON.stringify(makeGroupMessage('sync', syncData)));
78
+ socket.send(JSON.stringify(makeItemMessage('sync', syncData[0])));
79
+ expect(sub.getState()).toEqual(syncData);
80
+ });
81
+ });
@@ -0,0 +1,7 @@
1
+ export { Stream } from './src/stream';
2
+ export { StreamItemSubscription } from './src/stream-item';
3
+ export { StreamGroupSubscription } from './src/stream-group';
4
+ export { StreamSubscription } from './src/stream-subscription';
5
+ export { SocketAdapter } from './src/socket-adapter';
6
+ export { SocketAdapterFactory } from './src/adapter-factory';
7
+ export * from './src/stream.types';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { Stream } from './src/stream';
2
+ export { StreamItemSubscription } from './src/stream-item';
3
+ export { StreamGroupSubscription } from './src/stream-group';
4
+ export { StreamSubscription } from './src/stream-subscription';
5
+ export * from './src/stream.types';
@@ -0,0 +1,2 @@
1
+ import { SocketAdapter } from './socket-adapter';
2
+ export type SocketAdapterFactory = () => SocketAdapter;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ export interface SocketAdapter {
2
+ connect(): void;
3
+ close(): void;
4
+ send(message: string): void;
5
+ isOpen(): boolean;
6
+ onMessage(callback: (message: string) => void): void;
7
+ onOpen(callback: () => void): void;
8
+ onClose(callback: () => void): void;
9
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ import { GroupEventMessage, JoinMessage } from './stream.types';
3
+ export declare class StreamGroupSubscription<TData extends {
4
+ id: string;
5
+ }> extends StreamSubscription<TData[], GroupEventMessage<TData>> {
6
+ private sortKey?;
7
+ private lastTimestamp;
8
+ private lastTimestampMap;
9
+ constructor(sub: JoinMessage, sortKey?: keyof TData | undefined);
10
+ private sort;
11
+ protected setState(state: TData[]): void;
12
+ listener(message: GroupEventMessage<TData>): void;
13
+ }
@@ -0,0 +1,65 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ export class StreamGroupSubscription extends StreamSubscription {
3
+ constructor(sub, sortKey) {
4
+ super(sub, []);
5
+ this.sortKey = sortKey;
6
+ this.lastTimestamp = 0;
7
+ this.lastTimestampMap = new Map();
8
+ }
9
+ sort(state) {
10
+ const sortKey = this.sortKey;
11
+ if (sortKey) {
12
+ return state.sort((a, b) => {
13
+ const aValue = a[sortKey];
14
+ const bValue = b[sortKey];
15
+ if (aValue && bValue) {
16
+ return aValue.toString().localeCompare(bValue.toString());
17
+ }
18
+ return 0;
19
+ });
20
+ }
21
+ return state;
22
+ }
23
+ setState(state) {
24
+ super.setState(this.sort(state));
25
+ }
26
+ listener(message) {
27
+ if (message.event.type === 'sync') {
28
+ if (message.timestamp < this.lastTimestamp) {
29
+ return;
30
+ }
31
+ this.lastTimestampMap = new Map();
32
+ this.lastTimestamp = message.timestamp;
33
+ this.setState(message.event.data);
34
+ }
35
+ else if (message.event.type === 'create') {
36
+ const id = message.event.data.id;
37
+ const state = this.getState();
38
+ if (!state.find((item) => item.id === id)) {
39
+ this.setState([...state, message.event.data]);
40
+ }
41
+ }
42
+ else if (message.event.type === 'update') {
43
+ const messageData = message.event.data;
44
+ const messageDataId = messageData.id;
45
+ const state = this.getState();
46
+ const currentItemTimestamp = this.lastTimestampMap.get(messageDataId);
47
+ if (currentItemTimestamp && currentItemTimestamp >= message.timestamp) {
48
+ return;
49
+ }
50
+ this.lastTimestamp = message.timestamp;
51
+ this.lastTimestampMap.set(messageDataId, message.timestamp);
52
+ this.setState(state.map((item) => (item.id === messageDataId ? messageData : item)));
53
+ }
54
+ else if (message.event.type === 'delete') {
55
+ const messageDataId = message.event.data.id;
56
+ const state = this.getState();
57
+ this.lastTimestamp = message.timestamp;
58
+ this.lastTimestampMap.set(messageDataId, message.timestamp);
59
+ this.setState(state.filter((item) => item.id !== messageDataId));
60
+ }
61
+ else if (message.event.type === 'event') {
62
+ this.onEventReceived(message.event.event);
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,9 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ import { ItemEventMessage, JoinMessage } from './stream.types';
3
+ export declare class StreamItemSubscription<TData extends {
4
+ id: string;
5
+ }> extends StreamSubscription<TData | null, ItemEventMessage<TData>> {
6
+ private lastEventTimestamp;
7
+ constructor(sub: JoinMessage);
8
+ listener(message: ItemEventMessage<TData>): void;
9
+ }
@@ -0,0 +1,22 @@
1
+ import { StreamSubscription } from './stream-subscription';
2
+ export class StreamItemSubscription extends StreamSubscription {
3
+ constructor(sub) {
4
+ super(sub, null);
5
+ this.lastEventTimestamp = 0;
6
+ }
7
+ listener(message) {
8
+ if (message.timestamp <= this.lastEventTimestamp) {
9
+ return;
10
+ }
11
+ this.lastEventTimestamp = message.timestamp;
12
+ if (message.event.type === 'sync' || message.event.type === 'create' || message.event.type === 'update') {
13
+ this.setState(message.event.data);
14
+ }
15
+ else if (message.event.type === 'delete') {
16
+ this.setState(null);
17
+ }
18
+ else if (message.event.type === 'event') {
19
+ this.onEventReceived(message.event.event);
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,36 @@
1
+ import { CustomEvent, JoinMessage, Listener } from './stream.types';
2
+ type CustomEventListener = (event: any) => void;
3
+ export declare abstract class StreamSubscription<TData = unknown, TEventData = unknown> {
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;
11
+ protected onEventReceived(event: CustomEvent): void;
12
+ /**
13
+ * Add a custom event listener. This listener will be called whenever the custom event is received.
14
+ */
15
+ onEvent(type: string, listener: CustomEventListener): void;
16
+ /**
17
+ * Remove a custom event listener.
18
+ */
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;
35
+ }
36
+ export {};
@@ -0,0 +1,59 @@
1
+ export class StreamSubscription {
2
+ constructor(sub, state) {
3
+ this.customEventListeners = new Map();
4
+ this.closeListeners = new Set();
5
+ this.onChangeListeners = new Set();
6
+ this.sub = sub;
7
+ this.state = state;
8
+ }
9
+ onEventReceived(event) {
10
+ const customEventListeners = this.customEventListeners.get(event.type);
11
+ if (customEventListeners) {
12
+ const eventData = event.data;
13
+ customEventListeners.forEach((listener) => listener(eventData));
14
+ }
15
+ }
16
+ /**
17
+ * Add a custom event listener. This listener will be called whenever the custom event is received.
18
+ */
19
+ onEvent(type, listener) {
20
+ const listeners = this.customEventListeners.get(type) || [];
21
+ this.customEventListeners.set(type, [...listeners, listener]);
22
+ }
23
+ /**
24
+ * Remove a custom event listener.
25
+ */
26
+ offEvent(type, listener) {
27
+ const listeners = this.customEventListeners.get(type) || [];
28
+ this.customEventListeners.set(type, listeners.filter((l) => l !== listener));
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
+ }
59
+ }
@@ -0,0 +1,38 @@
1
+ import { StreamGroupSubscription } from './stream-group';
2
+ import { StreamItemSubscription } from './stream-item';
3
+ import { SocketAdapter } from './socket-adapter';
4
+ import { SocketAdapterFactory } from './adapter-factory';
5
+ export declare class Stream {
6
+ private adapterFactory;
7
+ private ws;
8
+ private listeners;
9
+ constructor(adapterFactory: SocketAdapterFactory);
10
+ createSocket(): SocketAdapter;
11
+ /**
12
+ * Subscribe to an item in a stream.
13
+ *
14
+ * @argument streamName - The name of the stream to subscribe to.
15
+ * @argument groupId - The id of the group to subscribe to.
16
+ * @argument id - The id of the item to subscribe to.
17
+ */
18
+ subscribeItem<TData extends {
19
+ id: string;
20
+ }>(streamName: string, groupId: string, id: string): StreamItemSubscription<TData>;
21
+ /**
22
+ * Subscribe to a group in a stream.
23
+ *
24
+ * @argument streamName - The name of the stream to subscribe to.
25
+ * @argument groupId - The id of the group to subscribe to.
26
+ */
27
+ subscribeGroup<TData extends {
28
+ id: string;
29
+ }>(streamName: string, groupId: string, sortKey?: keyof TData): StreamGroupSubscription<TData>;
30
+ close(): void;
31
+ private onSocketClose;
32
+ private onSocketOpen;
33
+ messageListener(event: string): void;
34
+ private subscribe;
35
+ private join;
36
+ private leave;
37
+ private roomName;
38
+ }
@@ -0,0 +1,98 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+ import { StreamGroupSubscription } from './stream-group';
3
+ import { StreamItemSubscription } from './stream-item';
4
+ export class Stream {
5
+ constructor(adapterFactory) {
6
+ this.adapterFactory = adapterFactory;
7
+ this.listeners = {};
8
+ this.ws = this.createSocket();
9
+ }
10
+ createSocket() {
11
+ this.ws = this.adapterFactory();
12
+ this.ws.onMessage((message) => this.messageListener(message));
13
+ this.ws.onOpen(() => this.onSocketOpen());
14
+ this.ws.onClose(() => this.onSocketClose());
15
+ return this.ws;
16
+ }
17
+ /**
18
+ * Subscribe to an item in a stream.
19
+ *
20
+ * @argument streamName - The name of the stream to subscribe to.
21
+ * @argument groupId - The id of the group to subscribe to.
22
+ * @argument id - The id of the item to subscribe to.
23
+ */
24
+ subscribeItem(streamName, groupId, id) {
25
+ const subscriptionId = uuidv4();
26
+ const sub = { streamName, groupId, id, subscriptionId };
27
+ const subscription = new StreamItemSubscription(sub);
28
+ this.subscribe(subscription);
29
+ return subscription;
30
+ }
31
+ /**
32
+ * Subscribe to a group in a stream.
33
+ *
34
+ * @argument streamName - The name of the stream to subscribe to.
35
+ * @argument groupId - The id of the group to subscribe to.
36
+ */
37
+ subscribeGroup(streamName, groupId, sortKey) {
38
+ const subscriptionId = uuidv4();
39
+ const sub = { streamName, groupId, subscriptionId };
40
+ const subscription = new StreamGroupSubscription(sub, sortKey);
41
+ this.subscribe(subscription);
42
+ return subscription;
43
+ }
44
+ close() {
45
+ this.listeners = {}; // clean up all listeners
46
+ this.ws.close();
47
+ }
48
+ onSocketClose() {
49
+ // retry to connect
50
+ setTimeout(() => this.createSocket(), 2000);
51
+ }
52
+ onSocketOpen() {
53
+ Object.values(this.listeners).forEach((listeners) => {
54
+ listeners.forEach((subscription) => this.join(subscription));
55
+ });
56
+ }
57
+ messageListener(event) {
58
+ const message = JSON.parse(event);
59
+ const room = this.roomName(message);
60
+ this.listeners[room]?.forEach((listener) => listener.listener(message));
61
+ // we need to discard sync to group subs when it's an item event
62
+ if (message.id && message.event.type !== 'sync') {
63
+ const groupRoom = this.roomName({
64
+ streamName: message.streamName,
65
+ groupId: message.groupId,
66
+ });
67
+ this.listeners[groupRoom]?.forEach((listener) => listener.listener(message));
68
+ }
69
+ }
70
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
71
+ subscribe(subscription) {
72
+ const room = this.roomName(subscription.sub);
73
+ if (!this.listeners[room]) {
74
+ this.listeners[room] = new Set();
75
+ }
76
+ this.listeners[room].add(subscription);
77
+ this.join(subscription);
78
+ subscription.onClose(() => {
79
+ this.listeners[room]?.delete(subscription);
80
+ this.leave(subscription);
81
+ });
82
+ }
83
+ join(subscription) {
84
+ if (this.ws.isOpen()) {
85
+ this.ws.send(JSON.stringify({ type: 'join', data: subscription.sub }));
86
+ }
87
+ }
88
+ leave(subscription) {
89
+ if (this.ws.isOpen()) {
90
+ this.ws.send(JSON.stringify({ type: 'leave', data: subscription.sub }));
91
+ }
92
+ }
93
+ roomName(message) {
94
+ return message.id
95
+ ? `${message.streamName}:group:${message.groupId}:item:${message.id}`
96
+ : `${message.streamName}:group:${message.groupId}`;
97
+ }
98
+ }
@@ -0,0 +1,56 @@
1
+ export type BaseMessage = {
2
+ streamName: string;
3
+ groupId: string;
4
+ id?: string;
5
+ timestamp: number;
6
+ };
7
+ export type JoinMessage = Omit<BaseMessage, 'timestamp'> & {
8
+ subscriptionId: string;
9
+ };
10
+ export type CustomEvent = {
11
+ type: string;
12
+ data: any;
13
+ };
14
+ export type StreamEvent<TData extends {
15
+ id: string;
16
+ }> = {
17
+ type: 'create';
18
+ data: TData;
19
+ } | {
20
+ type: 'update';
21
+ data: TData;
22
+ } | {
23
+ type: 'delete';
24
+ data: TData;
25
+ } | {
26
+ type: 'event';
27
+ event: CustomEvent;
28
+ };
29
+ export type ItemStreamEvent<TData extends {
30
+ id: string;
31
+ }> = StreamEvent<TData> | {
32
+ type: 'sync';
33
+ data: TData;
34
+ };
35
+ export type GroupStreamEvent<TData extends {
36
+ id: string;
37
+ }> = StreamEvent<TData> | {
38
+ type: 'sync';
39
+ data: TData[];
40
+ };
41
+ export type ItemEventMessage<TData extends {
42
+ id: string;
43
+ }> = BaseMessage & {
44
+ event: ItemStreamEvent<TData>;
45
+ };
46
+ export type GroupEventMessage<TData extends {
47
+ id: string;
48
+ }> = BaseMessage & {
49
+ event: GroupStreamEvent<TData>;
50
+ };
51
+ export type Message = {
52
+ type: 'join' | 'leave';
53
+ data: JoinMessage;
54
+ };
55
+ export type Listener<TData> = (state: TData | null) => void;
56
+ export type CustomEventListener<TData> = (event: TData) => void;
@@ -0,0 +1 @@
1
+ export {};
package/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { Stream } from './src/stream'
2
+ export { StreamItemSubscription } from './src/stream-item'
3
+ export { StreamGroupSubscription } from './src/stream-group'
4
+ export { StreamSubscription } from './src/stream-subscription'
5
+ export { SocketAdapter } from './src/socket-adapter'
6
+ export { SocketAdapterFactory } from './src/adapter-factory'
7
+ export * from './src/stream.types'
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@motiadev/stream-client",
3
+ "description": "Motia Stream Client Package – Responsible for managing streams of data.",
4
+ "version": "0.5.2-beta.104-330172",
5
+ "license": "MIT",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "dependencies": {
9
+ "uuid": "^11.1.0"
10
+ },
11
+ "devDependencies": {
12
+ "@types/jest": "^29.5.14",
13
+ "@types/ws": "^8.18.1",
14
+ "jest": "^29.7.0",
15
+ "ts-jest": "^29.3.2",
16
+ "typescript": "^5.7.2"
17
+ },
18
+ "scripts": {
19
+ "build": "rm -rf dist && tsc",
20
+ "lint": "eslint --config ../../eslint.config.js",
21
+ "test": "jest"
22
+ }
23
+ }