react-nats 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +254 -0
- package/dist/index.d.mts +47 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.js +290 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +263 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
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,254 @@
|
|
|
1
|
+
# react-nats
|
|
2
|
+
|
|
3
|
+
React hooks for NATS messaging and JetStream.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- ๐ **NatsProvider** - WebSocket connection management with auto-reconnect
|
|
8
|
+
- ๐ **useNatsKvTable** - Reactive NATS KV bucket with real-time updates
|
|
9
|
+
- ๐จ **useNatsStream** - JetStream consumer with time-based replay
|
|
10
|
+
- โก **Performance optimized** - Batched updates and stable sorting
|
|
11
|
+
- ๐ฏ **TypeScript first** - Full type safety with generics
|
|
12
|
+
- ๐งช **Zero dependencies** - Only peer dependencies on React and NATS
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install react-nats @nats-io/nats-core @nats-io/jetstream @nats-io/kv
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick Start
|
|
21
|
+
|
|
22
|
+
### 1. Wrap your app with NatsProvider
|
|
23
|
+
|
|
24
|
+
```tsx
|
|
25
|
+
import { NatsProvider } from 'react-nats';
|
|
26
|
+
|
|
27
|
+
function App() {
|
|
28
|
+
return (
|
|
29
|
+
<NatsProvider url="ws://localhost:4222">
|
|
30
|
+
<YourApp />
|
|
31
|
+
</NatsProvider>
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### 2. Use NATS KV for real-time data
|
|
37
|
+
|
|
38
|
+
```tsx
|
|
39
|
+
import { useNatsKvTable } from 'react-nats';
|
|
40
|
+
|
|
41
|
+
interface MyData {
|
|
42
|
+
id: string;
|
|
43
|
+
value: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function MyComponent() {
|
|
47
|
+
const entries = useNatsKvTable({
|
|
48
|
+
bucketName: 'my-bucket',
|
|
49
|
+
decoder: {
|
|
50
|
+
decode: (data: Uint8Array) => JSON.parse(new TextDecoder().decode(data)),
|
|
51
|
+
},
|
|
52
|
+
refreshInterval: 50, // Batch updates every 50ms
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
return (
|
|
56
|
+
<ul>
|
|
57
|
+
{entries.map((entry) => (
|
|
58
|
+
<li key={entry.key}>
|
|
59
|
+
{entry.key}: {entry.value.value}
|
|
60
|
+
</li>
|
|
61
|
+
))}
|
|
62
|
+
</ul>
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 3. Consume JetStream messages
|
|
68
|
+
|
|
69
|
+
```tsx
|
|
70
|
+
import { useNatsStream } from 'react-nats';
|
|
71
|
+
|
|
72
|
+
function StreamComponent() {
|
|
73
|
+
const messages = useNatsStream({
|
|
74
|
+
stream: 'my-stream',
|
|
75
|
+
subject: 'events.*',
|
|
76
|
+
decoder: {
|
|
77
|
+
decode: (data: Uint8Array) => JSON.parse(new TextDecoder().decode(data)),
|
|
78
|
+
},
|
|
79
|
+
reducer: {
|
|
80
|
+
reduce: (arr, msg) => [...arr, msg].slice(-100), // Keep last 100
|
|
81
|
+
},
|
|
82
|
+
opt_start_time: new Date(Date.now() - 3600000), // Last hour
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
return <div>Received {messages.length} messages</div>;
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## API Reference
|
|
90
|
+
|
|
91
|
+
### `<NatsProvider>`
|
|
92
|
+
|
|
93
|
+
Manages WebSocket connection to NATS server.
|
|
94
|
+
|
|
95
|
+
**Props:**
|
|
96
|
+
- `url: string` - NATS WebSocket URL (e.g., `ws://localhost:4222`)
|
|
97
|
+
- `options?: Partial<ConnectionOptions>` - Additional NATS connection options
|
|
98
|
+
- `children: React.ReactNode`
|
|
99
|
+
|
|
100
|
+
**Example:**
|
|
101
|
+
```tsx
|
|
102
|
+
<NatsProvider
|
|
103
|
+
url="wss://nats.example.com"
|
|
104
|
+
options={{
|
|
105
|
+
maxReconnectAttempts: 10,
|
|
106
|
+
reconnectTimeWait: 2000,
|
|
107
|
+
}}
|
|
108
|
+
>
|
|
109
|
+
<App />
|
|
110
|
+
</NatsProvider>
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### `useNatsConnection()`
|
|
114
|
+
|
|
115
|
+
Returns the current NATS connection or `null` if not connected.
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
const connection = useNatsConnection();
|
|
119
|
+
if (connection) {
|
|
120
|
+
// Use connection directly
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### `useNatsKvTable<T, U>(options)`
|
|
125
|
+
|
|
126
|
+
Watches a NATS KV bucket and returns reactive entries.
|
|
127
|
+
|
|
128
|
+
**Options:**
|
|
129
|
+
- `bucketName: string` - Name of the KV bucket
|
|
130
|
+
- `decoder: { decode: (data: Uint8Array) => T }` - Decode function for values
|
|
131
|
+
- `enrich?: (key: string, created: Date, decoded: T) => U` - Optional transform
|
|
132
|
+
- `refreshInterval?: number` - Batch update interval in ms (default: 50)
|
|
133
|
+
- `key?: string | string[]` - Filter specific keys
|
|
134
|
+
|
|
135
|
+
**Returns:** `NatsEntry<U>[]`
|
|
136
|
+
```typescript
|
|
137
|
+
type NatsEntry<T> = {
|
|
138
|
+
key: string;
|
|
139
|
+
value: T;
|
|
140
|
+
created: Date;
|
|
141
|
+
};
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
**Example with enrichment:**
|
|
145
|
+
```tsx
|
|
146
|
+
const entries = useNatsKvTable({
|
|
147
|
+
bucketName: 'prices',
|
|
148
|
+
decoder: { decode: (data) => parseFloat(new TextDecoder().decode(data)) },
|
|
149
|
+
enrich: (key, created, price) => ({
|
|
150
|
+
symbol: key,
|
|
151
|
+
price,
|
|
152
|
+
age: Date.now() - created.getTime(),
|
|
153
|
+
}),
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### `useNatsStream<T>(options)`
|
|
158
|
+
|
|
159
|
+
Consumes messages from a JetStream stream.
|
|
160
|
+
|
|
161
|
+
**Options:**
|
|
162
|
+
- `stream?: string` - Stream name (required)
|
|
163
|
+
- `subject?: string | string[]` - Filter subjects
|
|
164
|
+
- `decoder: { decode: (data: Uint8Array) => T }` - Decode function
|
|
165
|
+
- `reducer: { reduce: (arr: NatsMessage<T>[], msg: NatsMessage<T>) => NatsMessage<T>[] }` - State reducer
|
|
166
|
+
- `opt_start_time?: Date` - Start consuming from this time
|
|
167
|
+
|
|
168
|
+
**Returns:** `NatsMessage<T>[]`
|
|
169
|
+
```typescript
|
|
170
|
+
type NatsMessage<T> = {
|
|
171
|
+
subject: string;
|
|
172
|
+
value: T;
|
|
173
|
+
received: Date;
|
|
174
|
+
};
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
**Example with filtering:**
|
|
178
|
+
```tsx
|
|
179
|
+
const trades = useNatsStream({
|
|
180
|
+
stream: 'TRADES',
|
|
181
|
+
subject: 'trades.BTC.*',
|
|
182
|
+
decoder: { decode: (data) => JSON.parse(new TextDecoder().decode(data)) },
|
|
183
|
+
reducer: {
|
|
184
|
+
reduce: (arr, msg) => {
|
|
185
|
+
// Keep only profitable trades
|
|
186
|
+
if (msg.value.profit > 0) {
|
|
187
|
+
return [...arr, msg];
|
|
188
|
+
}
|
|
189
|
+
return arr;
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
opt_start_time: new Date(Date.now() - 86400000), // Last 24 hours
|
|
193
|
+
});
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## Common Patterns
|
|
197
|
+
|
|
198
|
+
### JSON Decoder
|
|
199
|
+
|
|
200
|
+
```tsx
|
|
201
|
+
const jsonDecoder = {
|
|
202
|
+
decode: (data: Uint8Array) => JSON.parse(new TextDecoder().decode(data)),
|
|
203
|
+
};
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### Protobuf Decoder
|
|
207
|
+
|
|
208
|
+
```tsx
|
|
209
|
+
import { MyMessage } from './generated/proto';
|
|
210
|
+
|
|
211
|
+
const protobufDecoder = {
|
|
212
|
+
decode: (data: Uint8Array) => MyMessage.decode(data),
|
|
213
|
+
};
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### Sliding Window Reducer
|
|
217
|
+
|
|
218
|
+
```tsx
|
|
219
|
+
const slidingWindowReducer = (windowSize: number) => ({
|
|
220
|
+
reduce: (arr: NatsMessage<any>[], msg: NatsMessage<any>) =>
|
|
221
|
+
[...arr, msg].slice(-windowSize),
|
|
222
|
+
});
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
## Performance Tips
|
|
226
|
+
|
|
227
|
+
1. **Batch updates** - Use `refreshInterval` in `useNatsKvTable` to batch rapid updates
|
|
228
|
+
2. **Filter early** - Use `key` parameter to watch only specific keys
|
|
229
|
+
3. **Limit state** - Use reducer to keep only necessary messages in memory
|
|
230
|
+
4. **Memoize decoders** - Create decoder objects outside components
|
|
231
|
+
|
|
232
|
+
## Development
|
|
233
|
+
|
|
234
|
+
```bash
|
|
235
|
+
# Install dependencies
|
|
236
|
+
npm install
|
|
237
|
+
|
|
238
|
+
# Build the library
|
|
239
|
+
npm run build
|
|
240
|
+
|
|
241
|
+
# Run tests
|
|
242
|
+
npm test
|
|
243
|
+
|
|
244
|
+
# Watch mode
|
|
245
|
+
npm run dev
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## License
|
|
249
|
+
|
|
250
|
+
MIT
|
|
251
|
+
|
|
252
|
+
## Contributing
|
|
253
|
+
|
|
254
|
+
Contributions welcome! Please open an issue or PR.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ConnectionOptions, NatsConnection } from '@nats-io/nats-core';
|
|
2
|
+
|
|
3
|
+
interface NatsProviderProps {
|
|
4
|
+
url: string;
|
|
5
|
+
options?: Partial<ConnectionOptions>;
|
|
6
|
+
children: React.ReactNode;
|
|
7
|
+
}
|
|
8
|
+
declare const NatsProvider: React.FC<NatsProviderProps>;
|
|
9
|
+
|
|
10
|
+
declare function useNatsConnection(): NatsConnection | null;
|
|
11
|
+
|
|
12
|
+
type NatsEntry<T> = {
|
|
13
|
+
key: string;
|
|
14
|
+
value: T;
|
|
15
|
+
created: Date;
|
|
16
|
+
};
|
|
17
|
+
type NatsMessage<T> = {
|
|
18
|
+
subject: string;
|
|
19
|
+
value: T;
|
|
20
|
+
received: Date;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
interface NatsKvTableOptions<T, U> {
|
|
24
|
+
bucketName: string;
|
|
25
|
+
decoder: {
|
|
26
|
+
decode: (data: Uint8Array) => T;
|
|
27
|
+
};
|
|
28
|
+
enrich?: (key: string, created: Date, decoded: T) => U;
|
|
29
|
+
refreshInterval?: number;
|
|
30
|
+
key?: string | string[];
|
|
31
|
+
}
|
|
32
|
+
declare function useNatsKvTable<T, U = T>({ bucketName, decoder, enrich, refreshInterval, key, }: NatsKvTableOptions<T, U>): NatsEntry<U>[];
|
|
33
|
+
|
|
34
|
+
interface NatsStreamOptions<T> {
|
|
35
|
+
stream?: string;
|
|
36
|
+
subject?: string | string[];
|
|
37
|
+
decoder: {
|
|
38
|
+
decode: (data: Uint8Array) => T;
|
|
39
|
+
};
|
|
40
|
+
reducer: {
|
|
41
|
+
reduce: (arr: NatsMessage<T>[], element: NatsMessage<T>) => NatsMessage<T>[];
|
|
42
|
+
};
|
|
43
|
+
opt_start_time?: Date;
|
|
44
|
+
}
|
|
45
|
+
declare function useNatsStream<T>({ stream, decoder, reducer, subject, opt_start_time, }: NatsStreamOptions<T>): NatsMessage<T>[];
|
|
46
|
+
|
|
47
|
+
export { type NatsEntry, type NatsKvTableOptions, type NatsMessage, NatsProvider, type NatsProviderProps, type NatsStreamOptions, useNatsConnection, useNatsKvTable, useNatsStream };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ConnectionOptions, NatsConnection } from '@nats-io/nats-core';
|
|
2
|
+
|
|
3
|
+
interface NatsProviderProps {
|
|
4
|
+
url: string;
|
|
5
|
+
options?: Partial<ConnectionOptions>;
|
|
6
|
+
children: React.ReactNode;
|
|
7
|
+
}
|
|
8
|
+
declare const NatsProvider: React.FC<NatsProviderProps>;
|
|
9
|
+
|
|
10
|
+
declare function useNatsConnection(): NatsConnection | null;
|
|
11
|
+
|
|
12
|
+
type NatsEntry<T> = {
|
|
13
|
+
key: string;
|
|
14
|
+
value: T;
|
|
15
|
+
created: Date;
|
|
16
|
+
};
|
|
17
|
+
type NatsMessage<T> = {
|
|
18
|
+
subject: string;
|
|
19
|
+
value: T;
|
|
20
|
+
received: Date;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
interface NatsKvTableOptions<T, U> {
|
|
24
|
+
bucketName: string;
|
|
25
|
+
decoder: {
|
|
26
|
+
decode: (data: Uint8Array) => T;
|
|
27
|
+
};
|
|
28
|
+
enrich?: (key: string, created: Date, decoded: T) => U;
|
|
29
|
+
refreshInterval?: number;
|
|
30
|
+
key?: string | string[];
|
|
31
|
+
}
|
|
32
|
+
declare function useNatsKvTable<T, U = T>({ bucketName, decoder, enrich, refreshInterval, key, }: NatsKvTableOptions<T, U>): NatsEntry<U>[];
|
|
33
|
+
|
|
34
|
+
interface NatsStreamOptions<T> {
|
|
35
|
+
stream?: string;
|
|
36
|
+
subject?: string | string[];
|
|
37
|
+
decoder: {
|
|
38
|
+
decode: (data: Uint8Array) => T;
|
|
39
|
+
};
|
|
40
|
+
reducer: {
|
|
41
|
+
reduce: (arr: NatsMessage<T>[], element: NatsMessage<T>) => NatsMessage<T>[];
|
|
42
|
+
};
|
|
43
|
+
opt_start_time?: Date;
|
|
44
|
+
}
|
|
45
|
+
declare function useNatsStream<T>({ stream, decoder, reducer, subject, opt_start_time, }: NatsStreamOptions<T>): NatsMessage<T>[];
|
|
46
|
+
|
|
47
|
+
export { type NatsEntry, type NatsKvTableOptions, type NatsMessage, NatsProvider, type NatsProviderProps, type NatsStreamOptions, useNatsConnection, useNatsKvTable, useNatsStream };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
NatsProvider: () => NatsProvider,
|
|
24
|
+
useNatsConnection: () => useNatsConnection,
|
|
25
|
+
useNatsKvTable: () => useNatsKvTable,
|
|
26
|
+
useNatsStream: () => useNatsStream
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
|
|
30
|
+
// src/NatsProvider.tsx
|
|
31
|
+
var import_react = require("react");
|
|
32
|
+
var import_nats_core = require("@nats-io/nats-core");
|
|
33
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
34
|
+
var NatsContext = (0, import_react.createContext)(null);
|
|
35
|
+
var DEFAULT_OPTIONS = {
|
|
36
|
+
reconnect: true,
|
|
37
|
+
pingInterval: 1e4,
|
|
38
|
+
maxPingOut: 5
|
|
39
|
+
};
|
|
40
|
+
var NatsProvider = ({
|
|
41
|
+
url,
|
|
42
|
+
options,
|
|
43
|
+
children
|
|
44
|
+
}) => {
|
|
45
|
+
const [connection, setConnection] = (0, import_react.useState)(null);
|
|
46
|
+
const connRef = (0, import_react.useRef)(null);
|
|
47
|
+
const isConnectingRef = (0, import_react.useRef)(false);
|
|
48
|
+
const connectionOptions = (0, import_react.useMemo)(
|
|
49
|
+
() => ({ ...DEFAULT_OPTIONS, ...options }),
|
|
50
|
+
[options]
|
|
51
|
+
);
|
|
52
|
+
(0, import_react.useEffect)(() => {
|
|
53
|
+
if (isConnectingRef.current || connRef.current) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
isConnectingRef.current = true;
|
|
57
|
+
let isActive = true;
|
|
58
|
+
const establishConnection = async () => {
|
|
59
|
+
try {
|
|
60
|
+
const newConnection = await (0, import_nats_core.wsconnect)({
|
|
61
|
+
servers: url,
|
|
62
|
+
...connectionOptions
|
|
63
|
+
});
|
|
64
|
+
if (isActive) {
|
|
65
|
+
connRef.current = newConnection;
|
|
66
|
+
setConnection(newConnection);
|
|
67
|
+
newConnection.closed().then((err) => {
|
|
68
|
+
console.log("NATS connection closed:", err?.message || "Manual close");
|
|
69
|
+
if (isActive) {
|
|
70
|
+
connRef.current = null;
|
|
71
|
+
setConnection(null);
|
|
72
|
+
isConnectingRef.current = false;
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
} else {
|
|
76
|
+
newConnection.close().then(() => console.log("Closed superseded connection")).catch((err) => {
|
|
77
|
+
console.error("Error closing superseded connection:", err);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
} catch (err) {
|
|
81
|
+
if (isActive) {
|
|
82
|
+
console.error("NATS connection failed:", err);
|
|
83
|
+
setConnection(null);
|
|
84
|
+
isConnectingRef.current = false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
establishConnection();
|
|
89
|
+
return () => {
|
|
90
|
+
isActive = false;
|
|
91
|
+
if (connRef.current) {
|
|
92
|
+
connRef.current.close().catch((err) => {
|
|
93
|
+
console.error("Error closing NATS connection:", err);
|
|
94
|
+
});
|
|
95
|
+
connRef.current = null;
|
|
96
|
+
setConnection(null);
|
|
97
|
+
}
|
|
98
|
+
isConnectingRef.current = false;
|
|
99
|
+
};
|
|
100
|
+
}, [url, connectionOptions]);
|
|
101
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(NatsContext.Provider, { value: connection, children });
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// src/useNatsConnection.ts
|
|
105
|
+
var import_react2 = require("react");
|
|
106
|
+
function useNatsConnection() {
|
|
107
|
+
const connection = (0, import_react2.useContext)(NatsContext);
|
|
108
|
+
return connection;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/useNatsKvTable.ts
|
|
112
|
+
var import_react3 = require("react");
|
|
113
|
+
var import_jetstream = require("@nats-io/jetstream");
|
|
114
|
+
var import_kv = require("@nats-io/kv");
|
|
115
|
+
var stableUpsert = (arr, newEntry, inPlace = false) => {
|
|
116
|
+
const index = arr.findIndex((item) => item.key === newEntry.key);
|
|
117
|
+
if (index >= 0) {
|
|
118
|
+
if (inPlace) {
|
|
119
|
+
arr[index] = newEntry;
|
|
120
|
+
return arr;
|
|
121
|
+
}
|
|
122
|
+
return [...arr.slice(0, index), newEntry, ...arr.slice(index + 1)];
|
|
123
|
+
} else {
|
|
124
|
+
if (inPlace) {
|
|
125
|
+
arr.push(newEntry);
|
|
126
|
+
arr.sort((a, b) => a.key.localeCompare(b.key));
|
|
127
|
+
return arr;
|
|
128
|
+
}
|
|
129
|
+
return [...arr, newEntry].sort((a, b) => a.key.localeCompare(b.key));
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
function useNatsKvTable({
|
|
133
|
+
bucketName,
|
|
134
|
+
decoder,
|
|
135
|
+
enrich,
|
|
136
|
+
refreshInterval = 50,
|
|
137
|
+
key
|
|
138
|
+
}) {
|
|
139
|
+
const connection = useNatsConnection();
|
|
140
|
+
const [entries, setEntries] = (0, import_react3.useState)([]);
|
|
141
|
+
const pendingUpdates = (0, import_react3.useRef)([]);
|
|
142
|
+
(0, import_react3.useEffect)(() => {
|
|
143
|
+
if (!connection) return;
|
|
144
|
+
let kv;
|
|
145
|
+
let watch;
|
|
146
|
+
let interval;
|
|
147
|
+
const setupNats = async () => {
|
|
148
|
+
const js = (0, import_jetstream.jetstream)(connection);
|
|
149
|
+
const kvm = new import_kv.Kvm(js);
|
|
150
|
+
kv = await kvm.open(bucketName, { bindOnly: true });
|
|
151
|
+
watch = await kv.watch({ key });
|
|
152
|
+
const flushUpdates = () => {
|
|
153
|
+
const updatesToProcess = [...pendingUpdates.current];
|
|
154
|
+
if (updatesToProcess.length > 0) {
|
|
155
|
+
pendingUpdates.current = [];
|
|
156
|
+
setEntries((prev) => {
|
|
157
|
+
const newEntries = [...prev];
|
|
158
|
+
return updatesToProcess.reduce(
|
|
159
|
+
(acc, newEntry) => stableUpsert(acc, newEntry, true),
|
|
160
|
+
newEntries
|
|
161
|
+
);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
if (refreshInterval > 0) {
|
|
166
|
+
flushUpdates();
|
|
167
|
+
interval = setInterval(flushUpdates, refreshInterval);
|
|
168
|
+
(async () => {
|
|
169
|
+
for await (const e of watch) {
|
|
170
|
+
if (e.operation === "PUT") {
|
|
171
|
+
const decoded = decoder.decode(e.value);
|
|
172
|
+
const enrichedValue = enrich ? enrich(e.key, e.created, decoded) : decoded;
|
|
173
|
+
const newEntry = {
|
|
174
|
+
key: e.key,
|
|
175
|
+
value: enrichedValue,
|
|
176
|
+
created: e.created
|
|
177
|
+
};
|
|
178
|
+
pendingUpdates.current.push(newEntry);
|
|
179
|
+
} else if (e.operation === "DEL" || e.operation === "PURGE") {
|
|
180
|
+
pendingUpdates.current = pendingUpdates.current.filter(
|
|
181
|
+
(item) => item.key !== e.key
|
|
182
|
+
);
|
|
183
|
+
setEntries((prev) => prev.filter((item) => item.key !== e.key));
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
})();
|
|
187
|
+
} else {
|
|
188
|
+
(async () => {
|
|
189
|
+
for await (const e of watch) {
|
|
190
|
+
if (e.operation === "PUT") {
|
|
191
|
+
const decoded = decoder.decode(e.value);
|
|
192
|
+
const enrichedValue = enrich ? enrich(e.key, e.created, decoded) : decoded;
|
|
193
|
+
const newEntry = {
|
|
194
|
+
key: e.key,
|
|
195
|
+
value: enrichedValue,
|
|
196
|
+
created: e.created
|
|
197
|
+
};
|
|
198
|
+
setEntries((prev) => stableUpsert(prev, newEntry));
|
|
199
|
+
} else if (e.operation === "DEL" || e.operation === "PURGE") {
|
|
200
|
+
setEntries((prev) => prev.filter((item) => item.key !== e.key));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
})();
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
setupNats().catch((err) => console.error("NATS setup error:", err));
|
|
207
|
+
return () => {
|
|
208
|
+
watch?.stop();
|
|
209
|
+
if (interval) clearInterval(interval);
|
|
210
|
+
kv = void 0;
|
|
211
|
+
watch = void 0;
|
|
212
|
+
};
|
|
213
|
+
}, [bucketName, connection, decoder, enrich, key, refreshInterval]);
|
|
214
|
+
return entries;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/useNatsStream.ts
|
|
218
|
+
var import_react4 = require("react");
|
|
219
|
+
var import_jetstream2 = require("@nats-io/jetstream");
|
|
220
|
+
function useNatsStream({
|
|
221
|
+
stream,
|
|
222
|
+
decoder,
|
|
223
|
+
reducer,
|
|
224
|
+
subject,
|
|
225
|
+
opt_start_time
|
|
226
|
+
}) {
|
|
227
|
+
const connection = useNatsConnection();
|
|
228
|
+
const [data, setData] = (0, import_react4.useState)([]);
|
|
229
|
+
(0, import_react4.useEffect)(() => {
|
|
230
|
+
setData([]);
|
|
231
|
+
if (!connection) return;
|
|
232
|
+
if (!opt_start_time) return;
|
|
233
|
+
if (!stream) return;
|
|
234
|
+
let isCurrent = true;
|
|
235
|
+
let c = null;
|
|
236
|
+
const setupNats = async () => {
|
|
237
|
+
const js = (0, import_jetstream2.jetstream)(connection);
|
|
238
|
+
const opt = {};
|
|
239
|
+
if (opt_start_time) {
|
|
240
|
+
opt.opt_start_time = opt_start_time.toISOString();
|
|
241
|
+
opt.deliver_policy = import_jetstream2.DeliverPolicy.StartTime;
|
|
242
|
+
}
|
|
243
|
+
if (subject) {
|
|
244
|
+
opt.filter_subjects = subject;
|
|
245
|
+
}
|
|
246
|
+
c = await js.consumers.get(stream, opt);
|
|
247
|
+
try {
|
|
248
|
+
const messages = await c.consume({ max_messages: 1 });
|
|
249
|
+
let effectData = [];
|
|
250
|
+
for await (const m of messages) {
|
|
251
|
+
const d = {
|
|
252
|
+
received: m.time,
|
|
253
|
+
subject: m.subject,
|
|
254
|
+
value: decoder.decode(m.data)
|
|
255
|
+
};
|
|
256
|
+
effectData = reducer.reduce(effectData, d);
|
|
257
|
+
m.ack();
|
|
258
|
+
if (!isCurrent) {
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
setData(effectData);
|
|
262
|
+
}
|
|
263
|
+
} finally {
|
|
264
|
+
if (!await c.delete()) {
|
|
265
|
+
console.warn(`Failed to delete consumer for stream ${stream}`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
setupNats().catch((error) => {
|
|
270
|
+
if (error.name === "AbortError") {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (isCurrent) {
|
|
274
|
+
console.error("NATS setup error:", error);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
return () => {
|
|
278
|
+
isCurrent = false;
|
|
279
|
+
};
|
|
280
|
+
}, [connection, stream, decoder, reducer, subject, opt_start_time]);
|
|
281
|
+
return data;
|
|
282
|
+
}
|
|
283
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
284
|
+
0 && (module.exports = {
|
|
285
|
+
NatsProvider,
|
|
286
|
+
useNatsConnection,
|
|
287
|
+
useNatsKvTable,
|
|
288
|
+
useNatsStream
|
|
289
|
+
});
|
|
290
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/NatsProvider.tsx","../src/useNatsConnection.ts","../src/useNatsKvTable.ts","../src/useNatsStream.ts"],"sourcesContent":["export { NatsProvider } from './NatsProvider';\nexport type { NatsProviderProps } from './NatsProvider';\n\nexport { useNatsConnection } from './useNatsConnection';\nexport { useNatsKvTable } from './useNatsKvTable';\nexport type { NatsKvTableOptions } from './useNatsKvTable';\nexport { useNatsStream } from './useNatsStream';\nexport type { NatsStreamOptions } from './useNatsStream';\n\nexport type { NatsEntry, NatsMessage } from './types';\n","import { createContext, useEffect, useState, useRef, useMemo } from 'react';\nimport { wsconnect, NatsConnection, ConnectionOptions } from '@nats-io/nats-core';\n\nexport const NatsContext = createContext<NatsConnection | null>(null);\n\nexport interface NatsProviderProps {\n url: string;\n options?: Partial<ConnectionOptions>;\n children: React.ReactNode;\n}\n\nconst DEFAULT_OPTIONS: Partial<ConnectionOptions> = {\n reconnect: true,\n pingInterval: 10000,\n maxPingOut: 5,\n};\n\nexport const NatsProvider: React.FC<NatsProviderProps> = ({\n url,\n options,\n children,\n}) => {\n const [connection, setConnection] = useState<NatsConnection | null>(null);\n const connRef = useRef<NatsConnection | null>(null);\n const isConnectingRef = useRef(false);\n const connectionOptions = useMemo(\n () => ({ ...DEFAULT_OPTIONS, ...options }),\n [options]\n );\n\n useEffect(() => {\n if (isConnectingRef.current || connRef.current) {\n return;\n }\n\n isConnectingRef.current = true;\n let isActive = true;\n\n const establishConnection = async () => {\n try {\n const newConnection = await wsconnect({\n servers: url,\n ...connectionOptions,\n });\n if (isActive) {\n connRef.current = newConnection;\n setConnection(newConnection);\n\n newConnection.closed().then((err: Error | void) => {\n console.log('NATS connection closed:', err?.message || 'Manual close');\n if (isActive) {\n connRef.current = null;\n setConnection(null);\n isConnectingRef.current = false;\n }\n });\n } else {\n newConnection.close()\n .then(() => console.log('Closed superseded connection'))\n .catch((err) => {\n console.error('Error closing superseded connection:', err);\n });\n }\n } catch (err) {\n if (isActive) {\n console.error('NATS connection failed:', err);\n setConnection(null);\n isConnectingRef.current = false;\n }\n }\n };\n\n establishConnection();\n\n return () => {\n isActive = false;\n if (connRef.current) {\n connRef.current.close().catch((err) => {\n console.error('Error closing NATS connection:', err);\n });\n connRef.current = null;\n setConnection(null);\n }\n isConnectingRef.current = false;\n };\n }, [url, connectionOptions]);\n\n return (\n <NatsContext.Provider value={connection}>\n {children}\n </NatsContext.Provider>\n );\n};\n","import { useContext } from 'react';\nimport { NatsConnection } from '@nats-io/nats-core';\nimport { NatsContext } from './NatsProvider';\n\nexport function useNatsConnection(): NatsConnection | null {\n const connection = useContext(NatsContext);\n return connection;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport { jetstream } from '@nats-io/jetstream';\nimport { KV, Kvm, KvWatchEntry } from '@nats-io/kv';\nimport { QueuedIterator } from '@nats-io/nats-core';\nimport { useNatsConnection } from './useNatsConnection';\nimport { NatsEntry } from './types';\n\nexport interface NatsKvTableOptions<T, U> {\n bucketName: string;\n decoder: { decode: (data: Uint8Array) => T };\n enrich?: (key: string, created: Date, decoded: T) => U;\n refreshInterval?: number;\n key?: string | string[];\n}\n\nconst stableUpsert = (\n arr: NatsEntry<any>[],\n newEntry: NatsEntry<any>,\n inPlace: boolean = false\n) => {\n const index = arr.findIndex((item) => item.key === newEntry.key);\n if (index >= 0) {\n if (inPlace) {\n arr[index] = newEntry;\n return arr;\n }\n return [...arr.slice(0, index), newEntry, ...arr.slice(index + 1)];\n } else {\n if (inPlace) {\n arr.push(newEntry);\n arr.sort((a, b) => a.key.localeCompare(b.key));\n return arr;\n }\n return [...arr, newEntry].sort((a, b) => a.key.localeCompare(b.key));\n }\n};\n\nexport function useNatsKvTable<T, U = T>({\n bucketName,\n decoder,\n enrich,\n refreshInterval = 50,\n key,\n}: NatsKvTableOptions<T, U>) {\n const connection = useNatsConnection();\n const [entries, setEntries] = useState<NatsEntry<U>[]>([]);\n const pendingUpdates = useRef<NatsEntry<U>[]>([]);\n\n useEffect(() => {\n if (!connection) return;\n\n let kv: KV | undefined;\n let watch: QueuedIterator<KvWatchEntry> | undefined;\n let interval: ReturnType<typeof setInterval> | undefined;\n\n const setupNats = async () => {\n const js = jetstream(connection);\n const kvm = new Kvm(js);\n kv = await kvm.open(bucketName, { bindOnly: true });\n watch = await kv.watch({ key });\n\n const flushUpdates = () => {\n const updatesToProcess = [...pendingUpdates.current];\n if (updatesToProcess.length > 0) {\n pendingUpdates.current = [];\n setEntries((prev) => {\n const newEntries = [...prev];\n return updatesToProcess.reduce(\n (acc, newEntry) => stableUpsert(acc, newEntry, true),\n newEntries\n );\n });\n }\n };\n\n if (refreshInterval > 0) {\n flushUpdates();\n interval = setInterval(flushUpdates, refreshInterval);\n\n (async () => {\n for await (const e of watch) {\n if (e.operation === 'PUT') {\n const decoded = decoder.decode(e.value);\n const enrichedValue = enrich\n ? enrich(e.key, e.created, decoded)\n : (decoded as unknown as U);\n const newEntry: NatsEntry<U> = {\n key: e.key,\n value: enrichedValue,\n created: e.created,\n };\n pendingUpdates.current.push(newEntry);\n } else if (e.operation === 'DEL' || e.operation === 'PURGE') {\n pendingUpdates.current = pendingUpdates.current.filter(\n (item) => item.key !== e.key\n );\n setEntries((prev) => prev.filter((item) => item.key !== e.key));\n }\n }\n })();\n } else {\n (async () => {\n for await (const e of watch) {\n if (e.operation === 'PUT') {\n const decoded = decoder.decode(e.value);\n const enrichedValue = enrich\n ? enrich(e.key, e.created, decoded)\n : (decoded as unknown as U);\n const newEntry: NatsEntry<U> = {\n key: e.key,\n value: enrichedValue,\n created: e.created,\n };\n setEntries((prev) => stableUpsert(prev, newEntry));\n } else if (e.operation === 'DEL' || e.operation === 'PURGE') {\n setEntries((prev) => prev.filter((item) => item.key !== e.key));\n }\n }\n })();\n }\n };\n\n setupNats().catch((err) => console.error('NATS setup error:', err));\n\n return () => {\n watch?.stop();\n if (interval) clearInterval(interval);\n kv = undefined;\n watch = undefined;\n };\n }, [bucketName, connection, decoder, enrich, key, refreshInterval]);\n\n return entries;\n}\n","import { useEffect, useState } from 'react';\nimport {\n jetstream,\n Consumer,\n DeliverPolicy,\n OrderedConsumerOptions,\n} from '@nats-io/jetstream';\nimport { useNatsConnection } from './useNatsConnection';\nimport { NatsMessage } from './types';\n\nexport interface NatsStreamOptions<T> {\n stream?: string;\n subject?: string | string[];\n decoder: { decode: (data: Uint8Array) => T };\n reducer: {\n reduce: (arr: NatsMessage<T>[], element: NatsMessage<T>) => NatsMessage<T>[];\n };\n opt_start_time?: Date;\n}\n\nexport function useNatsStream<T>({\n stream,\n decoder,\n reducer,\n subject,\n opt_start_time,\n}: NatsStreamOptions<T>) {\n const connection = useNatsConnection();\n const [data, setData] = useState<NatsMessage<T>[]>([]);\n\n useEffect(() => {\n setData([]);\n if (!connection) return;\n if (!opt_start_time) return;\n if (!stream) return;\n\n let isCurrent = true;\n let c: Consumer | null = null;\n\n const setupNats = async () => {\n const js = jetstream(connection);\n const opt: Partial<OrderedConsumerOptions> = {};\n\n if (opt_start_time) {\n opt.opt_start_time = opt_start_time.toISOString();\n opt.deliver_policy = DeliverPolicy.StartTime;\n }\n\n if (subject) {\n opt.filter_subjects = subject;\n }\n\n c = await js.consumers.get(stream, opt);\n\n try {\n const messages = await c.consume({ max_messages: 1 });\n let effectData: NatsMessage<T>[] = [];\n\n for await (const m of messages) {\n const d: NatsMessage<T> = {\n received: m.time,\n subject: m.subject,\n value: decoder.decode(m.data),\n };\n\n effectData = reducer.reduce(effectData, d);\n m.ack();\n\n if (!isCurrent) {\n break;\n }\n\n setData(effectData);\n }\n } finally {\n if (!(await c.delete())) {\n console.warn(`Failed to delete consumer for stream ${stream}`);\n }\n }\n };\n\n setupNats().catch((error) => {\n if (error.name === 'AbortError') {\n return;\n }\n if (isCurrent) {\n console.error('NATS setup error:', error);\n }\n });\n\n return () => {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AAAA,IACd;AAAA,EACF,GAAG,CAAC,YAAY,QAAQ,SAAS,SAAS,SAAS,cAAc,CAAC;AAElE,SAAO;AACT;","names":["import_react","import_react","import_react","import_jetstream"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// src/NatsProvider.tsx
|
|
2
|
+
import { createContext, useEffect, useState, useRef, useMemo } from "react";
|
|
3
|
+
import { wsconnect } from "@nats-io/nats-core";
|
|
4
|
+
import { jsx } from "react/jsx-runtime";
|
|
5
|
+
var NatsContext = createContext(null);
|
|
6
|
+
var DEFAULT_OPTIONS = {
|
|
7
|
+
reconnect: true,
|
|
8
|
+
pingInterval: 1e4,
|
|
9
|
+
maxPingOut: 5
|
|
10
|
+
};
|
|
11
|
+
var NatsProvider = ({
|
|
12
|
+
url,
|
|
13
|
+
options,
|
|
14
|
+
children
|
|
15
|
+
}) => {
|
|
16
|
+
const [connection, setConnection] = useState(null);
|
|
17
|
+
const connRef = useRef(null);
|
|
18
|
+
const isConnectingRef = useRef(false);
|
|
19
|
+
const connectionOptions = useMemo(
|
|
20
|
+
() => ({ ...DEFAULT_OPTIONS, ...options }),
|
|
21
|
+
[options]
|
|
22
|
+
);
|
|
23
|
+
useEffect(() => {
|
|
24
|
+
if (isConnectingRef.current || connRef.current) {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
isConnectingRef.current = true;
|
|
28
|
+
let isActive = true;
|
|
29
|
+
const establishConnection = async () => {
|
|
30
|
+
try {
|
|
31
|
+
const newConnection = await wsconnect({
|
|
32
|
+
servers: url,
|
|
33
|
+
...connectionOptions
|
|
34
|
+
});
|
|
35
|
+
if (isActive) {
|
|
36
|
+
connRef.current = newConnection;
|
|
37
|
+
setConnection(newConnection);
|
|
38
|
+
newConnection.closed().then((err) => {
|
|
39
|
+
console.log("NATS connection closed:", err?.message || "Manual close");
|
|
40
|
+
if (isActive) {
|
|
41
|
+
connRef.current = null;
|
|
42
|
+
setConnection(null);
|
|
43
|
+
isConnectingRef.current = false;
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
} else {
|
|
47
|
+
newConnection.close().then(() => console.log("Closed superseded connection")).catch((err) => {
|
|
48
|
+
console.error("Error closing superseded connection:", err);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (isActive) {
|
|
53
|
+
console.error("NATS connection failed:", err);
|
|
54
|
+
setConnection(null);
|
|
55
|
+
isConnectingRef.current = false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
establishConnection();
|
|
60
|
+
return () => {
|
|
61
|
+
isActive = false;
|
|
62
|
+
if (connRef.current) {
|
|
63
|
+
connRef.current.close().catch((err) => {
|
|
64
|
+
console.error("Error closing NATS connection:", err);
|
|
65
|
+
});
|
|
66
|
+
connRef.current = null;
|
|
67
|
+
setConnection(null);
|
|
68
|
+
}
|
|
69
|
+
isConnectingRef.current = false;
|
|
70
|
+
};
|
|
71
|
+
}, [url, connectionOptions]);
|
|
72
|
+
return /* @__PURE__ */ jsx(NatsContext.Provider, { value: connection, children });
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// src/useNatsConnection.ts
|
|
76
|
+
import { useContext } from "react";
|
|
77
|
+
function useNatsConnection() {
|
|
78
|
+
const connection = useContext(NatsContext);
|
|
79
|
+
return connection;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/useNatsKvTable.ts
|
|
83
|
+
import { useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
|
|
84
|
+
import { jetstream } from "@nats-io/jetstream";
|
|
85
|
+
import { Kvm } from "@nats-io/kv";
|
|
86
|
+
var stableUpsert = (arr, newEntry, inPlace = false) => {
|
|
87
|
+
const index = arr.findIndex((item) => item.key === newEntry.key);
|
|
88
|
+
if (index >= 0) {
|
|
89
|
+
if (inPlace) {
|
|
90
|
+
arr[index] = newEntry;
|
|
91
|
+
return arr;
|
|
92
|
+
}
|
|
93
|
+
return [...arr.slice(0, index), newEntry, ...arr.slice(index + 1)];
|
|
94
|
+
} else {
|
|
95
|
+
if (inPlace) {
|
|
96
|
+
arr.push(newEntry);
|
|
97
|
+
arr.sort((a, b) => a.key.localeCompare(b.key));
|
|
98
|
+
return arr;
|
|
99
|
+
}
|
|
100
|
+
return [...arr, newEntry].sort((a, b) => a.key.localeCompare(b.key));
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
function useNatsKvTable({
|
|
104
|
+
bucketName,
|
|
105
|
+
decoder,
|
|
106
|
+
enrich,
|
|
107
|
+
refreshInterval = 50,
|
|
108
|
+
key
|
|
109
|
+
}) {
|
|
110
|
+
const connection = useNatsConnection();
|
|
111
|
+
const [entries, setEntries] = useState2([]);
|
|
112
|
+
const pendingUpdates = useRef2([]);
|
|
113
|
+
useEffect2(() => {
|
|
114
|
+
if (!connection) return;
|
|
115
|
+
let kv;
|
|
116
|
+
let watch;
|
|
117
|
+
let interval;
|
|
118
|
+
const setupNats = async () => {
|
|
119
|
+
const js = jetstream(connection);
|
|
120
|
+
const kvm = new Kvm(js);
|
|
121
|
+
kv = await kvm.open(bucketName, { bindOnly: true });
|
|
122
|
+
watch = await kv.watch({ key });
|
|
123
|
+
const flushUpdates = () => {
|
|
124
|
+
const updatesToProcess = [...pendingUpdates.current];
|
|
125
|
+
if (updatesToProcess.length > 0) {
|
|
126
|
+
pendingUpdates.current = [];
|
|
127
|
+
setEntries((prev) => {
|
|
128
|
+
const newEntries = [...prev];
|
|
129
|
+
return updatesToProcess.reduce(
|
|
130
|
+
(acc, newEntry) => stableUpsert(acc, newEntry, true),
|
|
131
|
+
newEntries
|
|
132
|
+
);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
if (refreshInterval > 0) {
|
|
137
|
+
flushUpdates();
|
|
138
|
+
interval = setInterval(flushUpdates, refreshInterval);
|
|
139
|
+
(async () => {
|
|
140
|
+
for await (const e of watch) {
|
|
141
|
+
if (e.operation === "PUT") {
|
|
142
|
+
const decoded = decoder.decode(e.value);
|
|
143
|
+
const enrichedValue = enrich ? enrich(e.key, e.created, decoded) : decoded;
|
|
144
|
+
const newEntry = {
|
|
145
|
+
key: e.key,
|
|
146
|
+
value: enrichedValue,
|
|
147
|
+
created: e.created
|
|
148
|
+
};
|
|
149
|
+
pendingUpdates.current.push(newEntry);
|
|
150
|
+
} else if (e.operation === "DEL" || e.operation === "PURGE") {
|
|
151
|
+
pendingUpdates.current = pendingUpdates.current.filter(
|
|
152
|
+
(item) => item.key !== e.key
|
|
153
|
+
);
|
|
154
|
+
setEntries((prev) => prev.filter((item) => item.key !== e.key));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
})();
|
|
158
|
+
} else {
|
|
159
|
+
(async () => {
|
|
160
|
+
for await (const e of watch) {
|
|
161
|
+
if (e.operation === "PUT") {
|
|
162
|
+
const decoded = decoder.decode(e.value);
|
|
163
|
+
const enrichedValue = enrich ? enrich(e.key, e.created, decoded) : decoded;
|
|
164
|
+
const newEntry = {
|
|
165
|
+
key: e.key,
|
|
166
|
+
value: enrichedValue,
|
|
167
|
+
created: e.created
|
|
168
|
+
};
|
|
169
|
+
setEntries((prev) => stableUpsert(prev, newEntry));
|
|
170
|
+
} else if (e.operation === "DEL" || e.operation === "PURGE") {
|
|
171
|
+
setEntries((prev) => prev.filter((item) => item.key !== e.key));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
})();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
setupNats().catch((err) => console.error("NATS setup error:", err));
|
|
178
|
+
return () => {
|
|
179
|
+
watch?.stop();
|
|
180
|
+
if (interval) clearInterval(interval);
|
|
181
|
+
kv = void 0;
|
|
182
|
+
watch = void 0;
|
|
183
|
+
};
|
|
184
|
+
}, [bucketName, connection, decoder, enrich, key, refreshInterval]);
|
|
185
|
+
return entries;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/useNatsStream.ts
|
|
189
|
+
import { useEffect as useEffect3, useState as useState3 } from "react";
|
|
190
|
+
import {
|
|
191
|
+
jetstream as jetstream2,
|
|
192
|
+
DeliverPolicy
|
|
193
|
+
} from "@nats-io/jetstream";
|
|
194
|
+
function useNatsStream({
|
|
195
|
+
stream,
|
|
196
|
+
decoder,
|
|
197
|
+
reducer,
|
|
198
|
+
subject,
|
|
199
|
+
opt_start_time
|
|
200
|
+
}) {
|
|
201
|
+
const connection = useNatsConnection();
|
|
202
|
+
const [data, setData] = useState3([]);
|
|
203
|
+
useEffect3(() => {
|
|
204
|
+
setData([]);
|
|
205
|
+
if (!connection) return;
|
|
206
|
+
if (!opt_start_time) return;
|
|
207
|
+
if (!stream) return;
|
|
208
|
+
let isCurrent = true;
|
|
209
|
+
let c = null;
|
|
210
|
+
const setupNats = async () => {
|
|
211
|
+
const js = jetstream2(connection);
|
|
212
|
+
const opt = {};
|
|
213
|
+
if (opt_start_time) {
|
|
214
|
+
opt.opt_start_time = opt_start_time.toISOString();
|
|
215
|
+
opt.deliver_policy = DeliverPolicy.StartTime;
|
|
216
|
+
}
|
|
217
|
+
if (subject) {
|
|
218
|
+
opt.filter_subjects = subject;
|
|
219
|
+
}
|
|
220
|
+
c = await js.consumers.get(stream, opt);
|
|
221
|
+
try {
|
|
222
|
+
const messages = await c.consume({ max_messages: 1 });
|
|
223
|
+
let effectData = [];
|
|
224
|
+
for await (const m of messages) {
|
|
225
|
+
const d = {
|
|
226
|
+
received: m.time,
|
|
227
|
+
subject: m.subject,
|
|
228
|
+
value: decoder.decode(m.data)
|
|
229
|
+
};
|
|
230
|
+
effectData = reducer.reduce(effectData, d);
|
|
231
|
+
m.ack();
|
|
232
|
+
if (!isCurrent) {
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
setData(effectData);
|
|
236
|
+
}
|
|
237
|
+
} finally {
|
|
238
|
+
if (!await c.delete()) {
|
|
239
|
+
console.warn(`Failed to delete consumer for stream ${stream}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
setupNats().catch((error) => {
|
|
244
|
+
if (error.name === "AbortError") {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (isCurrent) {
|
|
248
|
+
console.error("NATS setup error:", error);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
return () => {
|
|
252
|
+
isCurrent = false;
|
|
253
|
+
};
|
|
254
|
+
}, [connection, stream, decoder, reducer, subject, opt_start_time]);
|
|
255
|
+
return data;
|
|
256
|
+
}
|
|
257
|
+
export {
|
|
258
|
+
NatsProvider,
|
|
259
|
+
useNatsConnection,
|
|
260
|
+
useNatsKvTable,
|
|
261
|
+
useNatsStream
|
|
262
|
+
};
|
|
263
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NatsProvider.tsx","../src/useNatsConnection.ts","../src/useNatsKvTable.ts","../src/useNatsStream.ts"],"sourcesContent":["import { createContext, useEffect, useState, useRef, useMemo } from 'react';\nimport { wsconnect, NatsConnection, ConnectionOptions } from '@nats-io/nats-core';\n\nexport const NatsContext = createContext<NatsConnection | null>(null);\n\nexport interface NatsProviderProps {\n url: string;\n options?: Partial<ConnectionOptions>;\n children: React.ReactNode;\n}\n\nconst DEFAULT_OPTIONS: Partial<ConnectionOptions> = {\n reconnect: true,\n pingInterval: 10000,\n maxPingOut: 5,\n};\n\nexport const NatsProvider: React.FC<NatsProviderProps> = ({\n url,\n options,\n children,\n}) => {\n const [connection, setConnection] = useState<NatsConnection | null>(null);\n const connRef = useRef<NatsConnection | null>(null);\n const isConnectingRef = useRef(false);\n const connectionOptions = useMemo(\n () => ({ ...DEFAULT_OPTIONS, ...options }),\n [options]\n );\n\n useEffect(() => {\n if (isConnectingRef.current || connRef.current) {\n return;\n }\n\n isConnectingRef.current = true;\n let isActive = true;\n\n const establishConnection = async () => {\n try {\n const newConnection = await wsconnect({\n servers: url,\n ...connectionOptions,\n });\n if (isActive) {\n connRef.current = newConnection;\n setConnection(newConnection);\n\n newConnection.closed().then((err: Error | void) => {\n console.log('NATS connection closed:', err?.message || 'Manual close');\n if (isActive) {\n connRef.current = null;\n setConnection(null);\n isConnectingRef.current = false;\n }\n });\n } else {\n newConnection.close()\n .then(() => console.log('Closed superseded connection'))\n .catch((err) => {\n console.error('Error closing superseded connection:', err);\n });\n }\n } catch (err) {\n if (isActive) {\n console.error('NATS connection failed:', err);\n setConnection(null);\n isConnectingRef.current = false;\n }\n }\n };\n\n establishConnection();\n\n return () => {\n isActive = false;\n if (connRef.current) {\n connRef.current.close().catch((err) => {\n console.error('Error closing NATS connection:', err);\n });\n connRef.current = null;\n setConnection(null);\n }\n isConnectingRef.current = false;\n };\n }, [url, connectionOptions]);\n\n return (\n <NatsContext.Provider value={connection}>\n {children}\n </NatsContext.Provider>\n );\n};\n","import { useContext } from 'react';\nimport { NatsConnection } from '@nats-io/nats-core';\nimport { NatsContext } from './NatsProvider';\n\nexport function useNatsConnection(): NatsConnection | null {\n const connection = useContext(NatsContext);\n return connection;\n}\n","import { useEffect, useRef, useState } from 'react';\nimport { jetstream } from '@nats-io/jetstream';\nimport { KV, Kvm, KvWatchEntry } from '@nats-io/kv';\nimport { QueuedIterator } from '@nats-io/nats-core';\nimport { useNatsConnection } from './useNatsConnection';\nimport { NatsEntry } from './types';\n\nexport interface NatsKvTableOptions<T, U> {\n bucketName: string;\n decoder: { decode: (data: Uint8Array) => T };\n enrich?: (key: string, created: Date, decoded: T) => U;\n refreshInterval?: number;\n key?: string | string[];\n}\n\nconst stableUpsert = (\n arr: NatsEntry<any>[],\n newEntry: NatsEntry<any>,\n inPlace: boolean = false\n) => {\n const index = arr.findIndex((item) => item.key === newEntry.key);\n if (index >= 0) {\n if (inPlace) {\n arr[index] = newEntry;\n return arr;\n }\n return [...arr.slice(0, index), newEntry, ...arr.slice(index + 1)];\n } else {\n if (inPlace) {\n arr.push(newEntry);\n arr.sort((a, b) => a.key.localeCompare(b.key));\n return arr;\n }\n return [...arr, newEntry].sort((a, b) => a.key.localeCompare(b.key));\n }\n};\n\nexport function useNatsKvTable<T, U = T>({\n bucketName,\n decoder,\n enrich,\n refreshInterval = 50,\n key,\n}: NatsKvTableOptions<T, U>) {\n const connection = useNatsConnection();\n const [entries, setEntries] = useState<NatsEntry<U>[]>([]);\n const pendingUpdates = useRef<NatsEntry<U>[]>([]);\n\n useEffect(() => {\n if (!connection) return;\n\n let kv: KV | undefined;\n let watch: QueuedIterator<KvWatchEntry> | undefined;\n let interval: ReturnType<typeof setInterval> | undefined;\n\n const setupNats = async () => {\n const js = jetstream(connection);\n const kvm = new Kvm(js);\n kv = await kvm.open(bucketName, { bindOnly: true });\n watch = await kv.watch({ key });\n\n const flushUpdates = () => {\n const updatesToProcess = [...pendingUpdates.current];\n if (updatesToProcess.length > 0) {\n pendingUpdates.current = [];\n setEntries((prev) => {\n const newEntries = [...prev];\n return updatesToProcess.reduce(\n (acc, newEntry) => stableUpsert(acc, newEntry, true),\n newEntries\n );\n });\n }\n };\n\n if (refreshInterval > 0) {\n flushUpdates();\n interval = setInterval(flushUpdates, refreshInterval);\n\n (async () => {\n for await (const e of watch) {\n if (e.operation === 'PUT') {\n const decoded = decoder.decode(e.value);\n const enrichedValue = enrich\n ? enrich(e.key, e.created, decoded)\n : (decoded as unknown as U);\n const newEntry: NatsEntry<U> = {\n key: e.key,\n value: enrichedValue,\n created: e.created,\n };\n pendingUpdates.current.push(newEntry);\n } else if (e.operation === 'DEL' || e.operation === 'PURGE') {\n pendingUpdates.current = pendingUpdates.current.filter(\n (item) => item.key !== e.key\n );\n setEntries((prev) => prev.filter((item) => item.key !== e.key));\n }\n }\n })();\n } else {\n (async () => {\n for await (const e of watch) {\n if (e.operation === 'PUT') {\n const decoded = decoder.decode(e.value);\n const enrichedValue = enrich\n ? enrich(e.key, e.created, decoded)\n : (decoded as unknown as U);\n const newEntry: NatsEntry<U> = {\n key: e.key,\n value: enrichedValue,\n created: e.created,\n };\n setEntries((prev) => stableUpsert(prev, newEntry));\n } else if (e.operation === 'DEL' || e.operation === 'PURGE') {\n setEntries((prev) => prev.filter((item) => item.key !== e.key));\n }\n }\n })();\n }\n };\n\n setupNats().catch((err) => console.error('NATS setup error:', err));\n\n return () => {\n watch?.stop();\n if (interval) clearInterval(interval);\n kv = undefined;\n watch = undefined;\n };\n }, [bucketName, connection, decoder, enrich, key, refreshInterval]);\n\n return entries;\n}\n","import { useEffect, useState } from 'react';\nimport {\n jetstream,\n Consumer,\n DeliverPolicy,\n OrderedConsumerOptions,\n} from '@nats-io/jetstream';\nimport { useNatsConnection } from './useNatsConnection';\nimport { NatsMessage } from './types';\n\nexport interface NatsStreamOptions<T> {\n stream?: string;\n subject?: string | string[];\n decoder: { decode: (data: Uint8Array) => T };\n reducer: {\n reduce: (arr: NatsMessage<T>[], element: NatsMessage<T>) => NatsMessage<T>[];\n };\n opt_start_time?: Date;\n}\n\nexport function useNatsStream<T>({\n stream,\n decoder,\n reducer,\n subject,\n opt_start_time,\n}: NatsStreamOptions<T>) {\n const connection = useNatsConnection();\n const [data, setData] = useState<NatsMessage<T>[]>([]);\n\n useEffect(() => {\n setData([]);\n if (!connection) return;\n if (!opt_start_time) return;\n if (!stream) return;\n\n let isCurrent = true;\n let c: Consumer | null = null;\n\n const setupNats = async () => {\n const js = jetstream(connection);\n const opt: Partial<OrderedConsumerOptions> = {};\n\n if (opt_start_time) {\n opt.opt_start_time = opt_start_time.toISOString();\n opt.deliver_policy = DeliverPolicy.StartTime;\n }\n\n if (subject) {\n opt.filter_subjects = subject;\n }\n\n c = await js.consumers.get(stream, opt);\n\n try {\n const messages = await c.consume({ max_messages: 1 });\n let effectData: NatsMessage<T>[] = [];\n\n for await (const m of messages) {\n const d: NatsMessage<T> = {\n received: m.time,\n subject: m.subject,\n value: decoder.decode(m.data),\n };\n\n effectData = reducer.reduce(effectData, d);\n m.ack();\n\n if (!isCurrent) {\n break;\n }\n\n setData(effectData);\n }\n } finally {\n if (!(await c.delete())) {\n console.warn(`Failed to delete consumer for stream ${stream}`);\n }\n }\n };\n\n setupNats().catch((error) => {\n if (error.name === 'AbortError') {\n return;\n }\n if (isCurrent) {\n console.error('NATS setup error:', error);\n }\n });\n\n return () => {\n isCurrent = false;\n };\n }, [connection, stream, decoder, reducer, subject, opt_start_time]);\n\n return data;\n}\n"],"mappings":";AAAA,SAAS,eAAe,WAAW,UAAU,QAAQ,eAAe;AACpE,SAAS,iBAAoD;AAuFzD;AArFG,IAAM,cAAc,cAAqC,IAAI;AAQpE,IAAM,kBAA8C;AAAA,EAClD,WAAW;AAAA,EACX,cAAc;AAAA,EACd,YAAY;AACd;AAEO,IAAM,eAA4C,CAAC;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,CAAC,YAAY,aAAa,IAAI,SAAgC,IAAI;AACxE,QAAM,UAAU,OAA8B,IAAI;AAClD,QAAM,kBAAkB,OAAO,KAAK;AACpC,QAAM,oBAAoB;AAAA,IACxB,OAAO,EAAE,GAAG,iBAAiB,GAAG,QAAQ;AAAA,IACxC,CAAC,OAAO;AAAA,EACV;AAEA,YAAU,MAAM;AACd,QAAI,gBAAgB,WAAW,QAAQ,SAAS;AAC9C;AAAA,IACF;AAEA,oBAAgB,UAAU;AAC1B,QAAI,WAAW;AAEf,UAAM,sBAAsB,YAAY;AACtC,UAAI;AACF,cAAM,gBAAgB,MAAM,UAAU;AAAA,UACpC,SAAS;AAAA,UACT,GAAG;AAAA,QACL,CAAC;AACD,YAAI,UAAU;AACZ,kBAAQ,UAAU;AAClB,wBAAc,aAAa;AAE3B,wBAAc,OAAO,EAAE,KAAK,CAAC,QAAsB;AACjD,oBAAQ,IAAI,2BAA2B,KAAK,WAAW,cAAc;AACrE,gBAAI,UAAU;AACZ,sBAAQ,UAAU;AAClB,4BAAc,IAAI;AAClB,8BAAgB,UAAU;AAAA,YAC5B;AAAA,UACF,CAAC;AAAA,QACH,OAAO;AACL,wBAAc,MAAM,EACjB,KAAK,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AEA,cAAU,EAAE,MAAM,CAAC,UAAU;AAC3B,UAAI,MAAM,SAAS,cAAc;AAC/B;AAAA,MACF;AACA,UAAI,WAAW;AACb,gBAAQ,MAAM,qBAAqB,KAAK;AAAA,MAC1C;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,YAAY,QAAQ,SAAS,SAAS,SAAS,cAAc,CAAC;AAElE,SAAO;AACT;","names":["useEffect","useRef","useState","useState","useRef","useEffect","useEffect","useState","jetstream","useState","useEffect","jetstream"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "react-nats",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React hooks for NATS messaging and JetStream",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"require": "./dist/index.js",
|
|
11
|
+
"import": "./dist/index.mjs"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsup",
|
|
19
|
+
"dev": "tsup --watch",
|
|
20
|
+
"test": "vitest",
|
|
21
|
+
"lint": "eslint src --ext .ts,.tsx",
|
|
22
|
+
"prepublishOnly": "npm run build"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"react",
|
|
26
|
+
"nats",
|
|
27
|
+
"jetstream",
|
|
28
|
+
"hooks",
|
|
29
|
+
"websocket",
|
|
30
|
+
"messaging",
|
|
31
|
+
"kv",
|
|
32
|
+
"key-value"
|
|
33
|
+
],
|
|
34
|
+
"author": "jeff@jeffplourde.com",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@nats-io/jetstream": "^3.0.2-1",
|
|
38
|
+
"@nats-io/kv": "^3.0.2-1",
|
|
39
|
+
"@nats-io/nats-core": "^3.0.2-1",
|
|
40
|
+
"react": "^19.0.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/react": "^19.0.0",
|
|
44
|
+
"@typescript-eslint/eslint-plugin": "^8.54.0",
|
|
45
|
+
"@typescript-eslint/parser": "^8.54.0",
|
|
46
|
+
"eslint": "^9.39.2",
|
|
47
|
+
"react": "^19.0.0",
|
|
48
|
+
"tsup": "^8.0.0",
|
|
49
|
+
"typescript": "^5.0.0",
|
|
50
|
+
"vitest": "^4.0.18"
|
|
51
|
+
},
|
|
52
|
+
"repository": {
|
|
53
|
+
"type": "git",
|
|
54
|
+
"url": "https://github.com/jeffplourde/react-nats"
|
|
55
|
+
}
|
|
56
|
+
}
|