nostr-websocket-utils 0.2.2 โ†’ 0.2.3

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.
Files changed (2) hide show
  1. package/README.md +129 -86
  2. package/package.json +11 -3
package/README.md CHANGED
@@ -11,13 +11,14 @@ A TypeScript library providing WebSocket utilities for Nostr applications, focus
11
11
  ## Features
12
12
 
13
13
  - ๐Ÿ”„ Automatic reconnection with configurable attempts
14
- - ๐Ÿ’“ Heartbeat monitoring
14
+ - ๐Ÿ’“ Heartbeat monitoring with configurable intervals
15
15
  - ๐Ÿ“จ Message queueing during disconnections
16
- - ๐Ÿ“ข Channel-based broadcasting
16
+ - ๐Ÿ“ข Channel-based broadcasting with filtered subscriptions
17
17
  - ๐Ÿ”’ Type-safe message handling with required handlers
18
- - ๐Ÿ“ Built-in logging
19
- - ๐Ÿ›ก๏ธ Comprehensive error handling
20
- - ๐Ÿงช Full test coverage
18
+ - ๐Ÿ“ Built-in logging with Winston integration
19
+ - ๐Ÿ›ก๏ธ Comprehensive error handling and validation
20
+ - ๐Ÿงช 100% test coverage with Jest
21
+ - ๐Ÿ“ฆ Zero DOM dependencies
21
22
 
22
23
  ## Installation
23
24
 
@@ -27,130 +28,172 @@ npm install nostr-websocket-utils
27
28
 
28
29
  ## Breaking Changes in v0.2.2
29
30
 
30
- - Removed all DOM-related code to focus solely on WebSocket functionality.
31
- - Added UUID support for message tracking and correlation.
32
- - Introduced a new `WebSocketImpl` option for custom WebSocket implementations.
33
- - Improved TypeScript type safety across the codebase.
34
- - Enhanced error handling for WebSocket connections.
31
+ - ๐Ÿ”ฅ Removed all DOM-related code for better server-side compatibility
32
+ - ๐Ÿ†” Added UUID support for message tracking and correlation
33
+ - ๐Ÿ”Œ Introduced `WebSocketImpl` option for custom WebSocket implementations
34
+ - ๐Ÿ›ก๏ธ Enhanced TypeScript type safety and validation
35
+ - ๐Ÿ”„ Improved reconnection and error handling logic
36
+ - ๐Ÿ“ Added comprehensive logging support
35
37
 
36
38
  ## Usage
37
39
 
38
40
  ### Server Example
39
41
 
40
42
  ```typescript
41
- import express from 'express';
42
- import { createServer } from 'http';
43
43
  import { NostrWSServer } from 'nostr-websocket-utils';
44
- import winston from 'winston';
44
+ import { WebSocketServer } from 'ws';
45
+ import { getLogger } from './utils/logger';
45
46
 
46
- const app = express();
47
- const server = createServer(app);
47
+ // Create WebSocket server
48
+ const wss = new WebSocketServer({ port: 8080 });
48
49
 
49
- // Create a logger
50
- const logger = winston.createLogger({
51
- level: 'info',
52
- format: winston.format.json(),
53
- transports: [new winston.transports.Console()]
54
- });
55
-
56
- // Initialize the WebSocket server with custom WebSocket implementation
57
- const wsServer = new NostrWSServer(server, {
58
- logger,
50
+ // Initialize NostrWSServer with handlers
51
+ const server = new NostrWSServer(wss, {
52
+ logger: getLogger('nostr-server'),
53
+ heartbeatInterval: 30000, // Optional: 30 seconds
59
54
  handlers: {
55
+ // Required: Handle incoming messages
60
56
  message: async (ws, message) => {
61
- logger.info('Received message:', message);
62
- // Handle message
57
+ switch (message.type) {
58
+ case 'subscribe':
59
+ // Handle subscription
60
+ ws.subscriptions?.add(message.data.channel);
61
+ break;
62
+ case 'event':
63
+ // Broadcast to relevant subscribers
64
+ server.broadcastToChannel(message.data.channel, message);
65
+ break;
66
+ }
63
67
  },
68
+ // Optional: Handle errors
64
69
  error: (ws, error) => {
65
70
  logger.error('WebSocket error:', error);
66
71
  },
72
+ // Optional: Handle client disconnection
67
73
  close: (ws) => {
68
- logger.info('Connection closed');
74
+ logger.info(`Client ${ws.clientId} disconnected`);
69
75
  }
70
76
  }
71
77
  });
72
-
73
- server.listen(3000);
74
78
  ```
75
79
 
76
80
  ### Client Example
77
81
 
78
82
  ```typescript
79
83
  import { NostrWSClient } from 'nostr-websocket-utils';
80
- import winston from 'winston';
84
+ import { getLogger } from './utils/logger';
81
85
 
82
- const logger = winston.createLogger({
83
- level: 'info',
84
- format: winston.format.json(),
85
- transports: [new winston.transports.Console()]
86
- });
87
-
88
- const client = new NostrWSClient('ws://localhost:3000', {
89
- logger,
90
- WebSocketImpl: CustomWebSocketImplementation // Optional custom WebSocket implementation
86
+ const client = new NostrWSClient('ws://localhost:8080', {
87
+ logger: getLogger('nostr-client'),
88
+ heartbeatInterval: 30000,
89
+ handlers: {
90
+ // Required: Handle incoming messages
91
+ message: async (ws, message) => {
92
+ console.log('Received:', message);
93
+ }
94
+ }
91
95
  });
92
96
 
93
- client.on('message', (message) => {
94
- console.log('Received message:', message);
97
+ // Listen for connection events
98
+ client.on('connect', () => {
99
+ console.log('Connected to server');
100
+
101
+ // Subscribe to a channel
102
+ client.subscribe('my-channel');
103
+
104
+ // Send an event
105
+ client.send({
106
+ type: 'event',
107
+ data: {
108
+ channel: 'my-channel',
109
+ content: 'Hello, Nostr!'
110
+ }
111
+ });
95
112
  });
96
113
 
114
+ // Connect to server
97
115
  client.connect();
98
116
  ```
99
117
 
100
- ## Interface Reference
118
+ ## API Reference
101
119
 
102
- ### NostrWSOptions
120
+ ### NostrWSServer
121
+
122
+ The server-side WebSocket handler with support for channels and broadcasting.
103
123
 
104
124
  ```typescript
105
- interface NostrWSOptions {
106
- // Interval for sending heartbeat pings (ms)
107
- heartbeatInterval?: number;
108
- // Interval between reconnection attempts (ms)
109
- reconnectInterval?: number;
110
- // Maximum number of reconnection attempts
111
- maxReconnectAttempts?: number;
112
- // Required logger instance
113
- logger: Logger;
114
- // Required handlers object
115
- handlers: {
116
- // Required message handler
117
- message: (ws: ExtendedWebSocket, message: NostrWSMessage) => Promise<void> | void;
118
- // Optional error handler
119
- error?: (ws: WebSocket, error: Error) => void;
120
- // Optional close handler
121
- close?: (ws: WebSocket) => void;
122
- };
123
- // Optional custom WebSocket implementation
124
- WebSocketImpl?: WebSocketImpl;
125
+ class NostrWSServer {
126
+ constructor(wss: WebSocketServer, options: NostrWSOptions);
127
+
128
+ // Broadcast to all connected clients
129
+ broadcast(message: NostrWSMessage): void;
130
+
131
+ // Broadcast to specific channel subscribers
132
+ broadcastToChannel(channel: string, message: NostrWSMessage): void;
133
+
134
+ // Close the server and all connections
135
+ close(): void;
125
136
  }
126
137
  ```
127
138
 
128
- ## Why This Library is Perfect for Nostr Development
139
+ ### NostrWSClient
140
+
141
+ The client-side WebSocket handler with automatic reconnection and message queueing.
142
+
143
+ ```typescript
144
+ class NostrWSClient {
145
+ constructor(url: string, options: NostrWSOptions);
146
+
147
+ // Connect to the server
148
+ connect(): void;
149
+
150
+ // Subscribe to a channel
151
+ subscribe(channel: string, filter?: unknown): void;
152
+
153
+ // Unsubscribe from a channel
154
+ unsubscribe(channel: string): void;
155
+
156
+ // Send a message to the server
157
+ send(message: NostrWSMessage): Promise<void>;
158
+
159
+ // Close the connection
160
+ close(): void;
161
+ }
162
+ ```
163
+
164
+ ### NostrWSMessage
165
+
166
+ The standard message format for communication.
167
+
168
+ ```typescript
169
+ interface NostrWSMessage {
170
+ id?: string; // Auto-generated UUID if not provided
171
+ type: string; // Message type (e.g., 'subscribe', 'event')
172
+ data: {
173
+ channel?: string; // Target channel for subscription/broadcast
174
+ [key: string]: any; // Additional message data
175
+ };
176
+ }
177
+ ```
129
178
 
130
- This library is specifically designed to accelerate Nostr application development by providing a robust foundation for WebSocket communication. Here's what makes it particularly valuable:
179
+ ## Why Choose This Library
131
180
 
132
- ### 1. Nostr-Specific Message Types
133
- - Built-in support for core Nostr protocol message types (`subscribe`, `unsubscribe`, `event`, `request/response`)
134
- - Perfectly aligned with Nostr's pub/sub model
181
+ ### 1. Nostr-Optimized
182
+ - Built specifically for Nostr protocol requirements
183
+ - Efficient pub/sub model with filtered subscriptions
135
184
  - Type-safe message handling for all Nostr events
136
185
 
137
- ### 2. Advanced WebSocket Management
138
- - Zero-config connection maintenance with automatic reconnection
139
- - Built-in heartbeat mechanism prevents stale connections
140
- - Smart message queuing ensures no events are lost during disconnections
141
- - Comprehensive connection state tracking
142
-
143
- ### 3. Efficient Event Distribution
144
- - Channel-based broadcasting for targeted event distribution
145
- - Support for filtered subscriptions (crucial for Nostr event filtering)
146
- - Memory-efficient subscription tracking
147
- - Optimized message routing to relevant subscribers
148
-
149
- ### 4. Developer Experience
150
- - Full TypeScript support with comprehensive type definitions
151
- - Event-driven architecture matching Nostr's event-centric nature
152
- - Clear, consistent error handling and validation
153
- - Required handlers pattern ensures type safety
186
+ ### 2. Production-Ready
187
+ - Comprehensive error handling and recovery
188
+ - Memory-efficient subscription management
189
+ - Built-in logging and monitoring
190
+ - Extensive test coverage
191
+
192
+ ### 3. Developer-Friendly
193
+ - Clear TypeScript definitions
194
+ - Flexible configuration options
195
+ - Detailed documentation
196
+ - Active maintenance
154
197
 
155
198
  ## Contributing
156
199
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nostr-websocket-utils",
3
- "version": "0.2.2",
4
- "description": "WebSocket utilities for Nostr applications",
3
+ "version": "0.2.3",
4
+ "description": "Robust WebSocket utilities for Nostr applications with automatic reconnection, channel-based messaging, and type-safe handlers. Features heartbeat monitoring, message queueing, and comprehensive error handling.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "type": "module",
@@ -17,7 +17,15 @@
17
17
  "keywords": [
18
18
  "nostr",
19
19
  "websocket",
20
- "utils",
20
+ "typescript",
21
+ "ws",
22
+ "realtime",
23
+ "pubsub",
24
+ "channel-based",
25
+ "reconnection",
26
+ "heartbeat",
27
+ "message-queue",
28
+ "type-safe",
21
29
  "maiqr"
22
30
  ],
23
31
  "author": "vveerrgg",