@asteby/metacore-websocket 0.3.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Asteby, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # @asteby/metacore-websocket
2
+
3
+ Typed WebSocket provider for React 18/19 apps in the Metacore ecosystem.
4
+
5
+ - Native `WebSocket` — no `react-use-websocket` dependency
6
+ - Auto-reconnect with exponential backoff (capped at 30s)
7
+ - Optional heartbeat (`{ type: 'ping' }` by default)
8
+ - Typed messages with a pub/sub registry (`useWebSocketMessage`)
9
+ - Token-aware: pass a `getToken` callback; token is appended as `?token=`
10
+ (or customize with `buildUrl`)
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @asteby/metacore-websocket
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```tsx
21
+ import {
22
+ WebSocketProvider,
23
+ useWebSocket,
24
+ useWebSocketMessage,
25
+ type WebSocketMessage,
26
+ } from '@asteby/metacore-websocket'
27
+ import { useAuthStore } from '@/stores/auth-store'
28
+
29
+ type AppMessage =
30
+ | WebSocketMessage<'NOTIFICATION', { title: string; body: string }>
31
+ | WebSocketMessage<'STATUS_UPDATE', { device_id: string; status: string }>
32
+
33
+ export function Root({ children }: { children: React.ReactNode }) {
34
+ return (
35
+ <WebSocketProvider<AppMessage>
36
+ url={import.meta.env.VITE_WS_URL}
37
+ getToken={() => useAuthStore.getState().auth.accessToken}
38
+ reconnectInterval={3000}
39
+ maxReconnectAttempts={10}
40
+ heartbeatInterval={30000}
41
+ >
42
+ {children}
43
+ </WebSocketProvider>
44
+ )
45
+ }
46
+
47
+ function MyComponent() {
48
+ const { status, isConnected, send } = useWebSocket<AppMessage>()
49
+
50
+ useWebSocketMessage<AppMessage>('NOTIFICATION', (msg) => {
51
+ // msg.payload is typed as { title, body }
52
+ console.log(msg.payload?.title)
53
+ })
54
+
55
+ return (
56
+ <button onClick={() => send({ type: 'SUBSCRIBE', conversation_id: '1' })}>
57
+ {isConnected ? 'Connected' : `Status: ${status}`}
58
+ </button>
59
+ )
60
+ }
61
+ ```
62
+
63
+ ## Props
64
+
65
+ | Prop | Type | Default | Notes |
66
+ | --- | --- | --- | --- |
67
+ | `url` | `string \| null` | — | Base WebSocket URL. `null` disconnects. |
68
+ | `getToken` | `() => string \| Promise<string>` | — | Optional token getter. Token appended as `?token=` unless `buildUrl` is used. |
69
+ | `buildUrl` | `(url, token) => string \| null` | — | Custom URL builder. Return `null` to skip. |
70
+ | `reconnectInterval` | `number` | `3000` | Base delay in ms. |
71
+ | `maxReconnectAttempts` | `number` | `10` | — |
72
+ | `exponentialBackoff` | `boolean` | `true` | `base * 2^attempt` capped at 30s. |
73
+ | `heartbeatInterval` | `number` | `0` | `0` disables heartbeat. |
74
+ | `heartbeatMessage` | `SendPayload` | `{ type: 'ping' }` | — |
75
+ | `onOpen` / `onClose` / `onError` / `onMessage` | handlers | — | — |
76
+
77
+ ## Hooks
78
+
79
+ - `useWebSocket<TMessage>()` — returns `{ status, isConnected, lastMessage, lastEvent, send, disconnect, reconnect, subscribe }`.
80
+ - `useWebSocketMessage<TMessage>(type, handler)` — typed subscription; auto-unsubscribes on unmount.
@@ -0,0 +1,15 @@
1
+ import type { WebSocketContextValue, WebSocketMessage } from './types';
2
+ /**
3
+ * Access the WebSocket context. Throws if used outside of
4
+ * `<WebSocketProvider>`.
5
+ */
6
+ export declare function useWebSocket<TMessage extends WebSocketMessage = WebSocketMessage>(): WebSocketContextValue<TMessage>;
7
+ /**
8
+ * Subscribe to messages of a specific `type`. The handler is kept fresh
9
+ * via a ref so consumers don't need to memoize it. The subscription is
10
+ * torn down automatically on unmount or when `type` changes.
11
+ */
12
+ export declare function useWebSocketMessage<TMessage extends WebSocketMessage = WebSocketMessage, TType extends TMessage['type'] = TMessage['type']>(type: TType, handler: (message: Extract<TMessage, {
13
+ type: TType;
14
+ }>) => void): void;
15
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAEtE;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,SAAS,gBAAgB,GAAG,gBAAgB,KACjD,qBAAqB,CAAC,QAAQ,CAAC,CAQnC;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,SAAS,gBAAgB,GAAG,gBAAgB,EACpD,KAAK,SAAS,QAAQ,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAEjD,IAAI,EAAE,KAAK,EACX,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,QAAQ,EAAE;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,CAAC,KAAK,IAAI,GAC7D,IAAI,CAWN"}
package/dist/hooks.js ADDED
@@ -0,0 +1,30 @@
1
+ import { useContext, useEffect, useRef } from 'react';
2
+ import { WebSocketContext } from './provider';
3
+ /**
4
+ * Access the WebSocket context. Throws if used outside of
5
+ * `<WebSocketProvider>`.
6
+ */
7
+ export function useWebSocket() {
8
+ const ctx = useContext(WebSocketContext);
9
+ if (!ctx) {
10
+ throw new Error('useWebSocket must be used within a <WebSocketProvider>');
11
+ }
12
+ return ctx;
13
+ }
14
+ /**
15
+ * Subscribe to messages of a specific `type`. The handler is kept fresh
16
+ * via a ref so consumers don't need to memoize it. The subscription is
17
+ * torn down automatically on unmount or when `type` changes.
18
+ */
19
+ export function useWebSocketMessage(type, handler) {
20
+ const { subscribe } = useWebSocket();
21
+ const handlerRef = useRef(handler);
22
+ handlerRef.current = handler;
23
+ useEffect(() => {
24
+ const unsubscribe = subscribe(type, (message) => {
25
+ handlerRef.current(message);
26
+ });
27
+ return unsubscribe;
28
+ }, [type, subscribe]);
29
+ }
30
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAA;AACrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAG7C;;;GAGG;AACH,MAAM,UAAU,YAAY;IAG1B,MAAM,GAAG,GAAG,UAAU,CAAC,gBAAgB,CAE1B,CAAA;IACb,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAA;IAC3E,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAIjC,IAAW,EACX,OAA8D;IAE9D,MAAM,EAAE,SAAS,EAAE,GAAG,YAAY,EAAY,CAAA;IAC9C,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;IAClC,UAAU,CAAC,OAAO,GAAG,OAAO,CAAA;IAE5B,SAAS,CAAC,GAAG,EAAE;QACb,MAAM,WAAW,GAAG,SAAS,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE;YAC9C,UAAU,CAAC,OAAO,CAAC,OAA6C,CAAC,CAAA;QACnE,CAAC,CAAC,CAAA;QACF,OAAO,WAAW,CAAA;IACpB,CAAC,EAAE,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAA;AACvB,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { WebSocketProvider, WebSocketContext } from './provider';
2
+ export { useWebSocket, useWebSocketMessage } from './hooks';
3
+ export { WebSocketStatus } from './types';
4
+ export type { WebSocketMessage, WebSocketContextValue, WebSocketProviderProps, SendPayload, TokenGetter, } from './types';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAChE,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AACzC,YAAY,EACV,gBAAgB,EAChB,qBAAqB,EACrB,sBAAsB,EACtB,WAAW,EACX,WAAW,GACZ,MAAM,SAAS,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { WebSocketProvider, WebSocketContext } from './provider';
2
+ export { useWebSocket, useWebSocketMessage } from './hooks';
3
+ export { WebSocketStatus } from './types';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAChE,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA"}
@@ -0,0 +1,9 @@
1
+ import type { WebSocketContextValue, WebSocketMessage, WebSocketProviderProps } from './types';
2
+ export declare const WebSocketContext: import("react").Context<WebSocketContextValue<any> | undefined>;
3
+ /**
4
+ * Unified WebSocket provider. Native `WebSocket` implementation with
5
+ * auto-reconnect (exponential backoff), optional heartbeat, typed message
6
+ * dispatch, and a pub/sub registry consumed by `useWebSocketMessage`.
7
+ */
8
+ export declare function WebSocketProvider<TMessage extends WebSocketMessage = WebSocketMessage>(props: WebSocketProviderProps<TMessage>): import("react/jsx-runtime").JSX.Element;
9
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.tsx"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,qBAAqB,EACrB,gBAAgB,EAChB,sBAAsB,EACvB,MAAM,SAAS,CAAA;AAIhB,eAAO,MAAM,gBAAgB,iEAE5B,CAAA;AAwBD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,SAAS,gBAAgB,GAAG,gBAAgB,EACpF,KAAK,EAAE,sBAAsB,CAAC,QAAQ,CAAC,2CA+RxC"}
@@ -0,0 +1,282 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useCallback, useEffect, useMemo, useRef, useState, } from 'react';
3
+ import { WebSocketStatus } from './types';
4
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
5
+ export const WebSocketContext = createContext(undefined);
6
+ const MAX_BACKOFF_MS = 30_000;
7
+ function isPlainObject(value) {
8
+ return typeof value === 'object' && value !== null && !(value instanceof Blob) &&
9
+ !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value);
10
+ }
11
+ function serialize(payload) {
12
+ if (typeof payload === 'string')
13
+ return payload;
14
+ if (payload instanceof Blob)
15
+ return payload;
16
+ if (payload instanceof ArrayBuffer)
17
+ return payload;
18
+ if (ArrayBuffer.isView(payload))
19
+ return payload;
20
+ if (isPlainObject(payload))
21
+ return JSON.stringify(payload);
22
+ return String(payload);
23
+ }
24
+ function defaultBuildUrl(url, token) {
25
+ if (!token)
26
+ return url;
27
+ const separator = url.includes('?') ? '&' : '?';
28
+ return `${url}${separator}token=${encodeURIComponent(token)}`;
29
+ }
30
+ /**
31
+ * Unified WebSocket provider. Native `WebSocket` implementation with
32
+ * auto-reconnect (exponential backoff), optional heartbeat, typed message
33
+ * dispatch, and a pub/sub registry consumed by `useWebSocketMessage`.
34
+ */
35
+ export function WebSocketProvider(props) {
36
+ const { url, getToken, buildUrl, reconnectInterval = 3000, maxReconnectAttempts = 10, exponentialBackoff = true, heartbeatInterval = 0, heartbeatMessage = { type: 'ping' }, onOpen, onClose, onError, onMessage, protocols, children, } = props;
37
+ const [status, setStatus] = useState(WebSocketStatus.CLOSED);
38
+ const [lastMessage, setLastMessage] = useState(null);
39
+ const [lastEvent, setLastEvent] = useState(null);
40
+ const wsRef = useRef(null);
41
+ const reconnectTimerRef = useRef(null);
42
+ const heartbeatTimerRef = useRef(null);
43
+ const reconnectAttemptsRef = useRef(0);
44
+ const manualCloseRef = useRef(false);
45
+ const subscribersRef = useRef(new Map());
46
+ // Latest callbacks kept in refs so connect() can stay referentially stable.
47
+ const handlersRef = useRef({ onOpen, onClose, onError, onMessage });
48
+ handlersRef.current = { onOpen, onClose, onError, onMessage };
49
+ const optsRef = useRef({
50
+ reconnectInterval,
51
+ maxReconnectAttempts,
52
+ exponentialBackoff,
53
+ heartbeatInterval,
54
+ heartbeatMessage,
55
+ protocols,
56
+ buildUrl,
57
+ getToken,
58
+ url,
59
+ });
60
+ optsRef.current = {
61
+ reconnectInterval,
62
+ maxReconnectAttempts,
63
+ exponentialBackoff,
64
+ heartbeatInterval,
65
+ heartbeatMessage,
66
+ protocols,
67
+ buildUrl,
68
+ getToken,
69
+ url,
70
+ };
71
+ const clearReconnectTimer = useCallback(() => {
72
+ if (reconnectTimerRef.current) {
73
+ clearTimeout(reconnectTimerRef.current);
74
+ reconnectTimerRef.current = null;
75
+ }
76
+ }, []);
77
+ const clearHeartbeat = useCallback(() => {
78
+ if (heartbeatTimerRef.current) {
79
+ clearInterval(heartbeatTimerRef.current);
80
+ heartbeatTimerRef.current = null;
81
+ }
82
+ }, []);
83
+ const send = useCallback((payload) => {
84
+ const ws = wsRef.current;
85
+ if (!ws || ws.readyState !== WebSocket.OPEN)
86
+ return false;
87
+ try {
88
+ ws.send(serialize(payload));
89
+ return true;
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }, []);
95
+ const startHeartbeat = useCallback(() => {
96
+ clearHeartbeat();
97
+ const { heartbeatInterval: hb, heartbeatMessage: hbMsg } = optsRef.current;
98
+ if (!hb || hb <= 0)
99
+ return;
100
+ heartbeatTimerRef.current = setInterval(() => {
101
+ send(hbMsg);
102
+ }, hb);
103
+ }, [clearHeartbeat, send]);
104
+ const teardownSocket = useCallback(() => {
105
+ const ws = wsRef.current;
106
+ if (ws) {
107
+ ws.onopen = null;
108
+ ws.onclose = null;
109
+ ws.onerror = null;
110
+ ws.onmessage = null;
111
+ try {
112
+ ws.close();
113
+ }
114
+ catch {
115
+ // ignore
116
+ }
117
+ wsRef.current = null;
118
+ }
119
+ }, []);
120
+ const connect = useCallback(async () => {
121
+ const opts = optsRef.current;
122
+ if (!opts.url) {
123
+ setStatus(WebSocketStatus.CLOSED);
124
+ return;
125
+ }
126
+ let token = null;
127
+ if (opts.getToken) {
128
+ try {
129
+ token = await opts.getToken();
130
+ }
131
+ catch {
132
+ token = null;
133
+ }
134
+ }
135
+ const builder = opts.buildUrl ?? defaultBuildUrl;
136
+ const finalUrl = builder(opts.url, token);
137
+ if (!finalUrl) {
138
+ setStatus(WebSocketStatus.CLOSED);
139
+ return;
140
+ }
141
+ manualCloseRef.current = false;
142
+ teardownSocket();
143
+ setStatus(WebSocketStatus.CONNECTING);
144
+ let ws;
145
+ try {
146
+ ws = opts.protocols
147
+ ? new WebSocket(finalUrl, opts.protocols)
148
+ : new WebSocket(finalUrl);
149
+ }
150
+ catch (err) {
151
+ setStatus(WebSocketStatus.CLOSED);
152
+ handlersRef.current.onError?.(err);
153
+ scheduleReconnect();
154
+ return;
155
+ }
156
+ wsRef.current = ws;
157
+ ws.onopen = (event) => {
158
+ reconnectAttemptsRef.current = 0;
159
+ setStatus(WebSocketStatus.OPEN);
160
+ startHeartbeat();
161
+ handlersRef.current.onOpen?.(event);
162
+ };
163
+ ws.onmessage = (event) => {
164
+ setLastEvent(event);
165
+ let parsed = null;
166
+ if (typeof event.data === 'string') {
167
+ try {
168
+ parsed = JSON.parse(event.data);
169
+ }
170
+ catch {
171
+ parsed = null;
172
+ }
173
+ }
174
+ if (parsed) {
175
+ setLastMessage(parsed);
176
+ const type = parsed.type;
177
+ if (typeof type === 'string') {
178
+ const subs = subscribersRef.current.get(type);
179
+ if (subs) {
180
+ subs.forEach((handler) => {
181
+ try {
182
+ handler(parsed);
183
+ }
184
+ catch {
185
+ // swallow — one bad subscriber shouldn't break the pipeline
186
+ }
187
+ });
188
+ }
189
+ }
190
+ handlersRef.current.onMessage?.(parsed, event);
191
+ }
192
+ };
193
+ ws.onerror = (event) => {
194
+ handlersRef.current.onError?.(event);
195
+ };
196
+ ws.onclose = (event) => {
197
+ clearHeartbeat();
198
+ setStatus(WebSocketStatus.CLOSED);
199
+ handlersRef.current.onClose?.(event);
200
+ if (!manualCloseRef.current) {
201
+ scheduleReconnect();
202
+ }
203
+ };
204
+ }, [clearHeartbeat, startHeartbeat, teardownSocket]);
205
+ const scheduleReconnect = useCallback(() => {
206
+ const opts = optsRef.current;
207
+ if (reconnectAttemptsRef.current >= opts.maxReconnectAttempts)
208
+ return;
209
+ clearReconnectTimer();
210
+ const base = opts.reconnectInterval;
211
+ const attempt = reconnectAttemptsRef.current;
212
+ const delay = opts.exponentialBackoff
213
+ ? Math.min(base * 2 ** attempt, MAX_BACKOFF_MS)
214
+ : base;
215
+ reconnectTimerRef.current = setTimeout(() => {
216
+ reconnectAttemptsRef.current += 1;
217
+ void connect();
218
+ }, delay);
219
+ }, [clearReconnectTimer, connect]);
220
+ const disconnect = useCallback(() => {
221
+ manualCloseRef.current = true;
222
+ clearReconnectTimer();
223
+ clearHeartbeat();
224
+ teardownSocket();
225
+ setStatus(WebSocketStatus.CLOSED);
226
+ }, [clearHeartbeat, clearReconnectTimer, teardownSocket]);
227
+ const reconnect = useCallback(() => {
228
+ clearReconnectTimer();
229
+ reconnectAttemptsRef.current = 0;
230
+ void connect();
231
+ }, [clearReconnectTimer, connect]);
232
+ const subscribe = useCallback((type, handler) => {
233
+ const key = String(type);
234
+ const map = subscribersRef.current;
235
+ let set = map.get(key);
236
+ if (!set) {
237
+ set = new Set();
238
+ map.set(key, set);
239
+ }
240
+ set.add(handler);
241
+ return () => {
242
+ const current = subscribersRef.current.get(key);
243
+ if (!current)
244
+ return;
245
+ current.delete(handler);
246
+ if (current.size === 0)
247
+ subscribersRef.current.delete(key);
248
+ };
249
+ }, []);
250
+ // Establish / tear down the connection when `url` changes.
251
+ useEffect(() => {
252
+ if (url) {
253
+ reconnectAttemptsRef.current = 0;
254
+ void connect();
255
+ }
256
+ else {
257
+ disconnect();
258
+ }
259
+ return () => {
260
+ manualCloseRef.current = true;
261
+ clearReconnectTimer();
262
+ clearHeartbeat();
263
+ teardownSocket();
264
+ };
265
+ // `connect`/`disconnect` are stable; re-running on every token change
266
+ // would thrash the connection — consumers who want to force a refresh
267
+ // on token changes can call `reconnect()` themselves.
268
+ // eslint-disable-next-line react-hooks/exhaustive-deps
269
+ }, [url]);
270
+ const value = useMemo(() => ({
271
+ status,
272
+ isConnected: status === WebSocketStatus.OPEN,
273
+ lastMessage,
274
+ lastEvent,
275
+ send,
276
+ disconnect,
277
+ reconnect,
278
+ subscribe,
279
+ }), [status, lastMessage, lastEvent, send, disconnect, reconnect, subscribe]);
280
+ return (_jsx(WebSocketContext.Provider, { value: value, children: children }));
281
+ }
282
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,aAAa,EACb,WAAW,EACX,SAAS,EACT,OAAO,EACP,MAAM,EACN,QAAQ,GACT,MAAM,OAAO,CAAA;AAOd,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAEzC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,gBAAgB,GAAG,aAAa,CAC3C,SAAS,CACV,CAAA;AAED,MAAM,cAAc,GAAG,MAAM,CAAA;AAE7B,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC;QAC5E,CAAC,CAAC,KAAK,YAAY,WAAW,CAAC,IAAI,CAA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L,KAAC,gBAAgB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAgD,YAC/E,QAAQ,GACiB,CAC7B,CAAA;AACH,CAAC"}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * WebSocket connection states mirroring the native `WebSocket.readyState`
3
+ * constants, exposed as an enum-like const for typed consumption.
4
+ */
5
+ export declare const WebSocketStatus: {
6
+ readonly CONNECTING: 0;
7
+ readonly OPEN: 1;
8
+ readonly CLOSING: 2;
9
+ readonly CLOSED: 3;
10
+ };
11
+ export type WebSocketStatus = (typeof WebSocketStatus)[keyof typeof WebSocketStatus];
12
+ /**
13
+ * Minimal shape shared by all messages flowing through the provider. A
14
+ * `type` discriminator is required so consumers can subscribe to specific
15
+ * message kinds via `useWebSocketMessage`. Additional fields (payload,
16
+ * channel, metadata, etc.) are left open to extension.
17
+ */
18
+ export interface WebSocketMessage<TType extends string = string, TPayload = unknown> {
19
+ type: TType;
20
+ payload?: TPayload;
21
+ [key: string]: unknown;
22
+ }
23
+ export type TokenGetter = () => string | null | undefined | Promise<string | null | undefined>;
24
+ export type SendPayload = string | ArrayBufferLike | Blob | ArrayBufferView | WebSocketMessage;
25
+ export interface WebSocketProviderProps<TMessage extends WebSocketMessage = WebSocketMessage> {
26
+ /** WebSocket endpoint (e.g. `wss://api.example.com/ws`). */
27
+ url: string | null | undefined;
28
+ /**
29
+ * Optional token getter. When provided and a token is available, the
30
+ * token is appended as `?token=<token>` to the URL (unless a custom
31
+ * `buildUrl` is supplied). Returning `null`/`undefined` suppresses the
32
+ * connection until a token becomes available.
33
+ */
34
+ getToken?: TokenGetter;
35
+ /**
36
+ * Override how the final connection URL is built. Receives the base
37
+ * `url` and the resolved token. Return `null` to skip the connection.
38
+ */
39
+ buildUrl?: (url: string, token: string | null | undefined) => string | null;
40
+ /** Base delay (ms) between reconnect attempts. Default: 3000. */
41
+ reconnectInterval?: number;
42
+ /** Max reconnect attempts before giving up. Default: 10. */
43
+ maxReconnectAttempts?: number;
44
+ /**
45
+ * When true (default), uses exponential backoff capped at 30s based on
46
+ * `reconnectInterval`. Set to false for a fixed interval.
47
+ */
48
+ exponentialBackoff?: boolean;
49
+ /** Heartbeat interval (ms). Set to 0 or omit to disable. */
50
+ heartbeatInterval?: number;
51
+ /** Custom heartbeat message. Default: `{ type: 'ping' }`. */
52
+ heartbeatMessage?: SendPayload;
53
+ /** Called after the socket successfully opens. */
54
+ onOpen?: (event: Event) => void;
55
+ /** Called when the socket closes. */
56
+ onClose?: (event: CloseEvent) => void;
57
+ /** Called on any error event from the socket. */
58
+ onError?: (event: Event) => void;
59
+ /**
60
+ * Called for every parsed message. Invoked after type-specific
61
+ * subscribers registered via `useWebSocketMessage`.
62
+ */
63
+ onMessage?: (message: TMessage, event: MessageEvent) => void;
64
+ /** Protocols forwarded to the native `WebSocket` constructor. */
65
+ protocols?: string | string[];
66
+ children?: React.ReactNode;
67
+ }
68
+ export interface WebSocketContextValue<TMessage extends WebSocketMessage = WebSocketMessage> {
69
+ /** Current connection status. */
70
+ status: WebSocketStatus;
71
+ /** True while the socket is OPEN. */
72
+ isConnected: boolean;
73
+ /** Last parsed message received, or null. */
74
+ lastMessage: TMessage | null;
75
+ /** Raw last MessageEvent (useful for binary frames). */
76
+ lastEvent: MessageEvent | null;
77
+ /**
78
+ * Send a message. Objects are serialized with `JSON.stringify`; strings
79
+ * and binary frames are passed straight through.
80
+ */
81
+ send: (payload: SendPayload) => boolean;
82
+ /** Force-disconnect and prevent further reconnect attempts. */
83
+ disconnect: () => void;
84
+ /** Manually trigger a (re)connection attempt. */
85
+ reconnect: () => void;
86
+ /** Register a handler for a specific message `type`. Returns an unsubscribe fn. */
87
+ subscribe: <T extends TMessage = TMessage>(type: T['type'], handler: (message: T) => void) => () => void;
88
+ }
89
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,eAA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,IAAI,CAAA;IAC/B,qCAAqC;IACrC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAA;IACrC,iDAAiD;IACjD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;IAChC;;;OAGG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,KAAK,IAAI,CAAA;IAC5D,iEAAiE;IACjE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC7B,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAA;CAC3B;AAED,MAAM,WAAW,qBAAqB,CAAC,QAAQ,SAAS,gBAAgB,GAAG,gBAAgB;IACzF,iCAAiC;IACjC,MAAM,EAAE,eAAe,CAAA;IACvB,qCAAqC;IACrC,WAAW,EAAE,OAAO,CAAA;IACpB,6CAA6C;IAC7C,WAAW,EAAE,QAAQ,GAAG,IAAI,CAAA;IAC5B,wDAAwD;IACxD,SAAS,EAAE,YAAY,GAAG,IAAI,CAAA;IAC9B;;;OAGG;IACH,IAAI,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAA;IACvC,+DAA+D;IAC/D,UAAU,EAAE,MAAM,IAAI,CAAA;IACtB,iDAAiD;IACjD,SAAS,EAAE,MAAM,IAAI,CAAA;IACrB,mFAAmF;IACnF,SAAS,EAAE,CAAC,CAAC,SAAS,QAAQ,GAAG,QAAQ,EACvC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,EACf,OAAO,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,IAAI,KAC1B,MAAM,IAAI,CAAA;CAChB"}
package/dist/types.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * WebSocket connection states mirroring the native `WebSocket.readyState`
3
+ * constants, exposed as an enum-like const for typed consumption.
4
+ */
5
+ export const WebSocketStatus = {
6
+ CONNECTING: 0,
7
+ OPEN: 1,
8
+ CLOSING: 2,
9
+ CLOSED: 3,
10
+ };
11
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,UAAU,EAAE,CAAC;IACb,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;IACV,MAAM,EAAE,CAAC;CACD,CAAA"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@asteby/metacore-websocket",
3
+ "version": "0.3.0",
4
+ "description": "Metacore WebSocket provider — auto-reconnect, typed messages, channel subscriptions",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/asteby/metacore-sdk",
9
+ "directory": "packages/websocket"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./provider": {
24
+ "types": "./dist/provider.d.ts",
25
+ "import": "./dist/provider.js"
26
+ },
27
+ "./hooks": {
28
+ "types": "./dist/hooks.d.ts",
29
+ "import": "./dist/hooks.js"
30
+ }
31
+ },
32
+ "peerDependencies": {
33
+ "react": ">=18",
34
+ "react-dom": ">=18"
35
+ },
36
+ "devDependencies": {
37
+ "@types/react": "^19.0.0",
38
+ "@types/react-dom": "^19.0.0",
39
+ "react": "^19.2.4",
40
+ "react-dom": "^19.2.4",
41
+ "typescript": "^5.6.0"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc -p tsconfig.json",
48
+ "dev": "tsc -w -p tsconfig.json",
49
+ "typecheck": "tsc -p tsconfig.json --noEmit",
50
+ "clean": "rm -rf dist"
51
+ }
52
+ }